Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cursor adapter and sqlite example [closed]

Hello I am looking for sample code in which cursor adapter is used with sqlite?

like image 216
Gainster Avatar asked Mar 28 '11 10:03

Gainster


2 Answers

Really simple example.

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:

  1. Create a proper Cursor from the Database.

  2. 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.

1. Create a proper Cursor from the Database.

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); 

2. Create a Custom Cursor 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")));     } } 
like image 66
Joshua Pinter Avatar answered Sep 22 '22 23:09

Joshua Pinter


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(); 
like image 43
Eric Leschinski Avatar answered Sep 21 '22 23:09

Eric Leschinski