Create SQLite database and show it on a ListView using cursor in Android.
In previous post we study how to create SQLite data base , and tables,insert values to the table.here we are showing the database details on a ListView.complete source code is given below
Sqldemo1Activity .java
package a.b;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ListActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Sqldemo1Activity extends ListActivity {
SQLiteDatabase db;
TextView txtMsg;
ArrayList results = new ArrayList();
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
txtMsg= (TextView) findViewById(R.id.txtMsg);
try
{
createdb();
insertvalues();
showlist();
db.close();
}
catch(Exception e)
{
}
}
private void showlist() {
// TODO Auto-generated method stub
Cursor cursor = db.query("jithu12345", null, null, null, null, null,
null);
int count = 0;
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
count++;
//fetching from database and adding to arrayList
results.add(count+" :"+cursor.getString(cursor.getColumnIndex("name"))
+" "+cursor.getString(cursor.getColumnIndex("name"))
+" ("+cursor.getInt(cursor.getColumnIndex("phone"))+")");
}
//display in screen
this.setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, results));
}
private void createdb()
{
try
{
db= SQLiteDatabase.openDatabase("/data/data/a.b/jithunew",null,SQLiteDatabase.CREATE_IF_NECESSARY);
}
catch(SQLiteException e)
{
Toast.makeText(this, e.getMessage(), 1).show();
}
}
private void insertvalues()
{
try
{
db.execSQL("create table jithu12345("
+ " recID integer PRIMARY KEY autoincrement, "
+ " name text, "
+ " phone text ); ");
Toast.makeText(this, "Table was created",1).show();
}
catch(SQLiteException e1)
{
Toast.makeText(this, e1.getMessage(),1).show();
}
try{
db.execSQL( "insert into jithu12345(name, phone) "+ " values ('AAA', '555' );");
db.execSQL("insert into jithu12345(name, phone) " + " values ('BBB', '777' );");
db.execSQL("insert into jithu12345(name, phone) " + " values ('CCC', '999' );");
db.execSQL( "insert into jithu12345(name, phone) " + " values ('AAAaaaaa', '55523545' );");
db.execSQL("insert into jithu12345(name, phone) " + " values ('BBBbbbb', '777345345' );");
db.execSQL("insert into jithu12345(name, phone) "+ " values ('CCCcccc', '999345345' );");
Toast.makeText(this, " records were inserted",1).show();
}
catch(SQLiteException e2) {
Toast.makeText(this, e2.getMessage(),1).show();
}
}
}
No comments:
Post a Comment