Learn How To Create ListView From SQLite Database In Android Development

Description:
This example will show you how you can create listview from sqlitedb data.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it ListViewFromSQLiteDB.

2.)
Write following into layout/main.xml:

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>

 

 

3.) Write following into DBHelper.java:

 

package com.example.ListViewFromSQLiteDB;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper{

public SQLiteDatabase DB;
public String DBPath;
public static String DBName = "sample";
public static final int version = '1';
public static Context currentContext;
public static String tableName = "Resource";

public DBHelper(Context context) {
super(context, DBName, null, version);
currentContext = context;
DBPath = "/data/data/" + context.getPackageName() + "/databases";
createDatabase();

}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub

}

private void createDatabase() {
boolean dbExists = checkDbExists();

if (dbExists) {
// do nothing
} else {
DB = currentContext.openOrCreateDatabase(DBName, 0, null);
DB.execSQL("CREATE TABLE IF NOT EXISTS " +
tableName +
" (LastName VARCHAR, FirstName VARCHAR," +
" Country VARCHAR, Age INT(3));");

DB.execSQL("INSERT INTO " +
tableName +
" Values ('M','shumi','India',25);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('C','sarah','India',25);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('D','Lavya','USA',20);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('V','Avi','EU',25);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('T','Shenoi','Bangla',25);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('L','Lamha','Australia',20);");
}

}

private boolean checkDbExists() {
SQLiteDatabase checkDB = null;

try {
String myPath = DBPath + DBName;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);

} catch (SQLiteException e) {

// database does't exist yet.

}

if (checkDB != null) {

checkDB.close();

}

return checkDB != null ? true : false;
}
}

 

 

4.) Write following into your manifest file:

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ListViewFromSQLiteDB"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name="com.example.ListViewFromSQLiteDB.DataListView"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

</application>

</manifest>

 

 

5.) Run for output.

Steps:

1.) Create a project named ListViewFromSQLiteDB and set the information as stated in the image.

Build Target: Android 4.2
Application Name: ListViewFromSQLiteDB
Package Name: com.example.ListViewFromSQLiteDB
Activity Name: ListViewFromSQLiteDB
Min SDK Version: 4.2

2.) Open ListViewFromSQLiteDB.java file and write following code there:

 

package com.example.ListViewFromSQLiteDB;

import java.util.ArrayList;

import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class DataListView extends ListActivity {

private ArrayList<String> results = new ArrayList<String>();
private String tableName = DBHelper.tableName;
private SQLiteDatabase newDB;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openAndQueryDatabase();

displayResultList();

}
private void displayResultList() {
TextView tView = new TextView(this);
tView.setText("This data is retrieved from the database and only 4 " +
"of the results are displayed");
getListView().addHeaderView(tView);

setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);

}
private void openAndQueryDatabase() {
try {
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT FirstName, Age FROM " +
tableName +
" where Age > 10 LIMIT 4", null);

if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("FirstName"));
int age = c.getInt(c.getColumnIndex("Age"));
results.add("Name: " + firstName + ",Age: " + age);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}

}

}

 

 

3.) Compile and build the project.

Output

Leave a Comment:

5 comments
nitzan farhi says July 13, 2013

hey awesome tutorial, could you send me the source code?

nitzan2611@gmail.com

thanks!

Reply
Shramik says July 25, 2013

Hi Sushant,

Awesome!! I got the output. I have one doubt that can we extract that data in the form of document?

Thanks for sharing such a nice tutorial.

Thanks,
Shramik
VentureHire

Reply
Mohamed yaseen says September 29, 2013

Nice tutorial dude… 🙂
keep it up

But i’m a bit confused…
can i get a zip file of this code (project) ????

Reply
Naeem says March 3, 2015

i implement this but get Error please have a look

[code]
03-03 09:31:53.588: E/AndroidRuntime(1715): FATAL EXCEPTION: main
03-03 09:31:53.588: E/AndroidRuntime(1715): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.listviewdemo/com.example.listviewdemo.MainActivity}: java.lang.NullPointerException
03-03 09:31:53.588: E/AndroidRuntime(1715): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
03-03 09:31:53.588: E/AndroidRuntime(1715): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
03-03 09:31:53.588: E/AndroidRuntime(1715): at android.app.ActivityThread.access$600(ActivityThread.java:130)
03-03 09:31:53.588: E/AndroidRuntime(1715): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
03-03 09:31:53.588: E/AndroidRuntime(1715): at android.os.Handler.dispatchMessage(Handler.java:99)
03-03 09:31:53.588: E/AndroidRuntime(1715): at android.os.Looper.loop(Looper.java:137)
03-03 09:31:53.588: E/AndroidRuntime(1715): at android.app.ActivityThread.main(ActivityThread.java:4745)
03-03 09:31:53.588: E/AndroidRuntime(1715): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 09:31:53.588: E/AndroidRuntime(1715): at java.lang.reflect.Method.invoke(Method.java:511)
03-03 09:31:53.588: E/AndroidRuntime(1715): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
03-03 09:31:53.588: E/AndroidRuntime(1715): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-03 09:31:53.588: E/AndroidRuntime(1715): at dalvik.system.NativeStart.main(Native Method)
03-03 09:31:53.588: E/AndroidRuntime(1715): Caused by: java.lang.NullPointerException
03-03 09:31:53.588: E/AndroidRuntime(1715): at com.example.listviewdemo.MainActivity.displayResultList(MainActivity.java:34)
03-03 09:31:53.588: E/AndroidRuntime(1715): at com.example.listviewdemo.MainActivity.onCreate(MainActivity.java:27)
03-03 09:31:53.588: E/AndroidRuntime(1715): at android.app.Activity.performCreate(Activity.java:5008)
03-03 09:31:53.588: E/AndroidRuntime(1715): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
03-03 09:31:53.588: E/AndroidRuntime(1715): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
03-03 09:31:53.588: E/AndroidRuntime(1715): ... 11 more

[/code]

Reply
How To Create A Table Layout In Android | MY NEWS says May 26, 2015

[…] Learn How to Create ListView From SQLite Database … – Description: This example will show you how you can create listview from sqlitedb data. Algorithm: 1.) Create a new project by File-> New -> Android Project name it …… […]

Reply
Add Your Reply