Android Project

Android Project
Android Project

Monday, September 19, 2011

Using Sqlite to populate a ListView in Android

In this below application we had populated the listview using the data from the sqlite

Here we are using a java class for creating the table

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/** Helper to the database, manages versions and creation */
public class PlaceDataSQL extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "sample.db";
private static final int DATABASE_VERSION = 1;

private Context context;

public PlaceDataSQL(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;

public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE gallery (id varchar(20), image varchar(2000),caption varchar(160),description varchar(200))");

private void versionUpdation(SQLiteDatabase db) {


* Check if the database already exist to avoid re-copying the file each
* time you open the application.
* @return true if it exists, false if it doesn't
public boolean checkDataBase(String db) {

SQLiteDatabase checkDB = null;

try {
String myPath = "data/data/" + db;
checkDB = SQLiteDatabase.openDatabase(myPath, null,

} catch (SQLiteException e) {

// database does't exist yet.

} catch (Exception e) {


if (checkDB != null) {



return checkDB != null ? true : false;

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion >= newVersion)

if (oldVersion == 1) {
Log.d("New Version", "Datas can be upgraded");

Log.d("Sample Data", "onUpgrade : " + newVersion);


Here in the onCreate function the table is created and the onUpgrade function is used to upgrade the table on the next release, for example you had create an application and published it in market and a guy is using your application, now suddenly you like to add another field on your table means you need to change the " DATABASE_VERSION " to 2 and in the onUpgrade funtion you need to write the alter query there. Likewise i had using a funtion checkDataBase(), this is to check whether the database is exist or not.

Then in the main activity we are calling delete to delete the table content, likewise we will be using a function insertData, inside this function we will be inserting data to the table, like that we will be using getDataAndPopulate(), here we will be retrieving data from the table and displaying in the list.

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class SqliteDBActivity extends ListActivity {
private static PlaceDataSQL placeData;
private ArrayList id = new ArrayList();
private ArrayList image = new ArrayList();
private ArrayList caption = new ArrayList();
private ArrayList description = new ArrayList();
private Button populate;

/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
populate = (Button) findViewById(;
placeData = new PlaceDataSQL(this);

SQLiteDatabase db = placeData.getWritableDatabase();

Cursor cursors = getRawEvents("select * from gallery");

if (cursors.moveToNext()) {
} else {

db.delete("gallery", "id=?", new String[] {
"12" });
populate.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
insertData("1","","First","This is the first item");
insertData("2","","Second","This is the second item");


private void insertData(String id, String image, String caption, String description) {
SQLiteDatabase db = placeData.getWritableDatabase();
ContentValues values;
values = new ContentValues();
values.put("id", id);
values.put("image", image);
values.put("caption", caption);
values.put("description", description);

db.insert("gallery", null, values);

private void getDataAndPopulate() {
id = new ArrayList();
image = new ArrayList();
caption = new ArrayList();
description = new ArrayList();
Cursor cursor = getEvents("gallery");
while (cursor.moveToNext()) {
String temp_id = cursor.getString(0);
String temp_image = cursor.getString(1);
String temp_caption = cursor.getString(2);
String temp_description = cursor.getString(3);
String[] captionArray = (String[]) caption.toArray(
new String[caption.size()]);

ItemsAdapter itemsAdapter = new ItemsAdapter(
SqliteDBActivity.this, R.layout.item,

private class ItemsAdapter extends BaseAdapter {
String[] items;

public ItemsAdapter(Context context, int textViewResourceId,
String[] items) {
this.items = items;

public View getView(final int POSITION, View convertView,
ViewGroup parent) {
TextView desc;
TextView cap;
View view = convertView;
ImageView img;
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.item, null);

img = (ImageView) view.findViewById(;
cap = (TextView) view.findViewById(;

desc = (TextView) view.findViewById(;

try {
URL url = new URL(image.get(POSITION));
HttpURLConnection connection = (HttpURLConnection) url
InputStream input = connection.getInputStream();
BitmapFactory.Options bfOptions = new BitmapFactory.Options();
bfOptions.inDither = false; // Disable Dithering
// mode
bfOptions.inPurgeable = true; // Tell to gc that
// whether it needs
// free memory, the
// Bitmap can be
// cleared
bfOptions.inInputShareable = true; // Which kind of
// reference
// will be used
// to recover
// the Bitmap
// data after
// being clear,
// when it will
// be used in
// the future
bfOptions.inTempStorage = new byte[16 * 1024];
Bitmap bmp = null;
bmp = BitmapFactory.decodeStream(input, null,

} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (IllegalAccessError e) {
} catch (NullPointerException e) {

return view;

public int getCount() {
return items.length;

public Object getItem(int position) {
return position;

public long getItemId(int position) {
return position;

private Cursor getRawEvents(String sql) {
SQLiteDatabase db = (placeData).getReadableDatabase();
Cursor cursor = db.rawQuery(sql, null);

return cursor;

private Cursor getEvents(String table) {
SQLiteDatabase db = (placeData).getReadableDatabase();
Cursor cursor = db.query(table, null, null, null, null, null, null);

return cursor;

In this example i had wrote two types of retrieving methods from the table, by writing the query and specifying the table name itself.

You can download the full source code

Download source

Have a good day.


  1. Thanks for the example really nice example. Get more other Android Examples, Basic android sample Example source code, tutorial, gridview, progressdialog, listview, orientation, notificaiton etc simple basic example with Firs "Hello World" and Android sdk installation etc. just visit:

  2. Really well written, the listactivity in android has always been a constant source of confusion....

  3. Really nice application. Thanks a lot
    and i have one more doubt .How to retrieve image from remote database

  4. can't able to download source code. Plz help.

  5. everything is good but how to download the source code, whenever I press that stupid download button it is redirecting to take a survey.Again in that survey I need to take 1 lakh stupid worth insurance policy.And there are 2 more other stupid options can anyone tell me how to download the source code


  6. watch SQLite Database CRUD Operation in Android


  7. watch records to storing database in an array. list of type student and passing this list to the adapter .update and delete record .

  8. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.Android Training in chennai with placement | Android Training in velachery