Search code examples
androidsqliteandroid-listviewsimplecursoradapter

Updating listview based on sqlite query with SimpleCursorAdapter




I am having a listview with one profile imageview, two text views and a favorite imageview.
In search box which I have provided above list view I want to query sqlite DB and get updated results populated in my listview using SimpleCursorAdapter.

The following is my create table statement which shows all columns involved.

public static String CREATE_TABLE_STMT="create table "
            +CONTACT_TABLE+" ("
            +ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"
            +NAME+" varchar(100) NOT NULL UNIQUE ,"
            +PHONE+" varchar(100) ,"
            +EMAIL+" varchar(100) ,"
            +JOBTITLE+" varchar(100) ,"
            +WEBPAGE+" varchar(100) ,"
            +PICTUREURL+" varchar(100) ,"
            +THUMBNAILURL+" varchar(100) ,"
            +PICTUREPATH+" varchar(100) ,"
            +THUMBNAILPATH+" varchar(100))";

I am trying to run the following query to search rows which has "NAME" matching with my search text. To be specific I am trying to retrieve rows who's name column value starts with search query .

String searchQuery = "SELECT ID as _id," + AppConstants.NAME+","+AppConstants.JOBTITLE+","+AppConstants.THUMBNAILURL +  " from " + AppConstants.CONTACT_TABLE + " where " + AppConstants.NAME + " LIKE '" + query + "';";


  • Searching for "al" should return back full row having name as "Alan"
  • Searching for "tho" should return back full row having name as "Thomas"

After running the query I am checking the cursor values and trying to update my list view

if (cursor != null) {
            Log.i(AppConstants.APPUILOG,"cursor not null");
            cursor.moveToFirst();
            String[] from = new String[] new String[] {NAME,JOBTITLE,THUMBNAILURL};
            int[] to = new int[] {R.id.textViewMain,R.id.textViewSub,R.id.contact_icon};
            SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.contact_list_item, cursor, from, to);
            mainListView.setAdapter(cursorAdapter);
        }else {
            Log.i(AppConstants.APPUILOG,"cursor is null");
        }

But this code is always giving back blank listview.

  • Do I have to customize SimpleCursorAdapter to implement the same?
  • What modification I need to do in my query?
  • How to create a custom SimpleCursorAdapter and display the updated results?

Solution

  • As I am getting ,You want to search in ListView . Am I right ? If yes then you need change your approach , You don't need to interact with DB while searching in ListView . You need to implement Filters in ListView . You can see this link for complete solution .