Database with Cursor Adapter
Retrieving data from the database and showing in listview:
1) Create a method in Database class\
2) Open database by calling getReadableDatabase()
3) Create a query in the form of String
4) Execute the query using raqQuery method, which returns Cursor object
public class MyDatabase extends SQLiteOpenHelper
{
| | | public Cursor getAllStudents()
{
SQLiteDatabase database = getReadableDatabase();
String query = “SELECT * FROM STUDENT”;
Cursor cursor = database.rawQuery(query, null);
return cursor;
}}
To show the above data in ListView,
1) Create a list item in XML and provide ids to views
2) Create a CursorAdapter object as follows Requires column names in the form of String array ids of list item in the form of int[]
3) Set the adapter to listview as mentioned in below method
public void showList()
{
MyDatabase database = new MyDatabase(this);
Cursor cursor = database.getAllStudents();
String[] from = {“NAME”, “ROLLNO”, “MARKS”};
int[] to = {R.id.textName, R.id.textRNo, R.id.textMarks};
CursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_item, cursor, from, to, Adapter.IGNORE_ITEM_VIEW_TYPE); studentsList.setAdapter(adapter);
}
Create an Android application to work with retrieving data from database and showing ListView
Refer the following link