Hello I am looking for sample code in which cursor adapter is used with sqlite?
Here is a really simple, but very effective, example. Once you have the basics down you can easily build off of it.
There are two main parts to using a Cursor Adapter with SQLite:
Create a proper Cursor from the Database.
Create a custom Cursor Adapter that takes the Cursor data from the database and pairs it with the View you intend to represent the data with.
In your Activity:
SQLiteOpenHelper sqLiteOpenHelper = new SQLiteOpenHelper( context, DATABASE_NAME, null, DATABASE_VERSION); SQLiteDatabase sqLiteDatabase = sqLiteOpenHelper.getReadableDatabase(); String query = "SELECT * FROM clients ORDER BY company_name ASC"; // No trailing ';' Cursor cursor = sqLiteDatabase.rawQuery(query, null); ClientCursorAdapter adapter = new ClientCursorAdapter( this, R.layout.clients_listview_row, cursor, 0 ); this.setListAdapter(adapter);
Note: Extending from ResourceCursorAdapter
assumes you use XML to create your views.
public class ClientCursorAdapter extends ResourceCursorAdapter { public ClientCursorAdapter(Context context, int layout, Cursor cursor, int flags) { super(context, layout, cursor, flags); } @Override public void bindView(View view, Context context, Cursor cursor) { TextView name = (TextView) view.findViewById(R.id.name); name.setText(cursor.getString(cursor.getColumnIndex("name"))); TextView phone = (TextView) view.findViewById(R.id.phone); phone.setText(cursor.getString(cursor.getColumnIndex("phone"))); } }
In Android, How to use a Cursor with a raw query in sqlite:
Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM mytable " + "where Age > 10 LIMIT 5", null); if (c != null ) { if (c.moveToFirst()) { do { String firstName = c.getString(c.getColumnIndex("FirstName")); int age = c.getInt(c.getColumnIndex("Age")); results.add("" + firstName + ",Age: " + age); }while (c.moveToNext()); } } c.close();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With