Android Listview Example using CursorAdapter and SQLite database

The objective of this tutorial is to get data from SQLite database by extending the SimpleCursorAdapter and then attach that to the Listview. In this example we create a database of countries and then insert some countries when the activity starts. After that we create a SimpleCursorAdapter and attach that to cursor returned from our database custom query selection. The data columns returned from the cursor is then mapped to our custom view for display.

Android Listview CursorAdapter SQLite Example
Android Listview CursorAdapter SQLite Example

Source for Activity - AndroidListViewCursorAdaptorActivity.java

package com.as400samplecode;


import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class AndroidListViewCursorAdaptorActivity extends Activity {

 private CountriesDbAdapter dbHelper;
 private SimpleCursorAdapter dataAdapter;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  dbHelper = new CountriesDbAdapter(this);
  dbHelper.open();

  //Clean all data
  dbHelper.deleteAllCountries();
  //Add some data
  dbHelper.insertSomeCountries();

  //Generate ListView from SQLite Database
  displayListView();

 }

 private void displayListView() {


  Cursor cursor = dbHelper.fetchAllCountries();

  // The desired columns to be bound
  String[] columns = new String[] {
    CountriesDbAdapter.KEY_CODE,
    CountriesDbAdapter.KEY_NAME,
    CountriesDbAdapter.KEY_CONTINENT,
    CountriesDbAdapter.KEY_REGION
  };

  // the XML defined views which the data will be bound to
  int[] to = new int[] { 
    R.id.code,
    R.id.name,
    R.id.continent,
    R.id.region,
  };

  // create the adapter using the cursor pointing to the desired data 
  //as well as the layout information
  dataAdapter = new SimpleCursorAdapter(
    this, R.layout.country_info, 
    cursor, 
    columns, 
    to,
    0);

  ListView listView = (ListView) findViewById(R.id.listView1);
  // Assign adapter to ListView
  listView.setAdapter(dataAdapter);


  listView.setOnItemClickListener(new OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> listView, View view, 
     int position, long id) {
   // Get the cursor, positioned to the corresponding row in the result set
   Cursor cursor = (Cursor) listView.getItemAtPosition(position);

   // Get the state's capital from this row in the database.
   String countryCode = 
    cursor.getString(cursor.getColumnIndexOrThrow("code"));
   Toast.makeText(getApplicationContext(),
     countryCode, Toast.LENGTH_SHORT).show();

   }
  });

  EditText myFilter = (EditText) findViewById(R.id.myFilter);
  myFilter.addTextChangedListener(new TextWatcher() {

   public void afterTextChanged(Editable s) {
   }

   public void beforeTextChanged(CharSequence s, int start, 
     int count, int after) {
   }

   public void onTextChanged(CharSequence s, int start, 
     int before, int count) {
    dataAdapter.getFilter().filter(s.toString());
   }
  });
  
  dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
         public Cursor runQuery(CharSequence constraint) {
             return dbHelper.fetchCountriesByName(constraint.toString());
         }
     });

 }
}

Source for SQLite DB Adapter - CountriesDbAdapter.java

package com.as400samplecode;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class CountriesDbAdapter {

 public static final String KEY_ROWID = "_id";
 public static final String KEY_CODE = "code";
 public static final String KEY_NAME = "name";
 public static final String KEY_CONTINENT = "continent";
 public static final String KEY_REGION = "region";

 private static final String TAG = "CountriesDbAdapter";
 private DatabaseHelper mDbHelper;
 private SQLiteDatabase mDb;

 private static final String DATABASE_NAME = "World";
 private static final String SQLITE_TABLE = "Country";
 private static final int DATABASE_VERSION = 1;

 private final Context mCtx;

 private static final String DATABASE_CREATE =
  "CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
  KEY_ROWID + " integer PRIMARY KEY autoincrement," +
  KEY_CODE + "," +
  KEY_NAME + "," +
  KEY_CONTINENT + "," +
  KEY_REGION + "," +
  " UNIQUE (" + KEY_CODE +"));";

 private static class DatabaseHelper extends SQLiteOpenHelper {

  DatabaseHelper(Context context) {
   super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }


  @Override
  public void onCreate(SQLiteDatabase db) {
   Log.w(TAG, DATABASE_CREATE);
   db.execSQL(DATABASE_CREATE);
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
   Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
     + newVersion + ", which will destroy all old data");
   db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
   onCreate(db);
  }
 }

 public CountriesDbAdapter(Context ctx) {
  this.mCtx = ctx;
 }

 public CountriesDbAdapter open() throws SQLException {
  mDbHelper = new DatabaseHelper(mCtx);
  mDb = mDbHelper.getWritableDatabase();
  return this;
 }

 public void close() {
  if (mDbHelper != null) {
   mDbHelper.close();
  }
 }

 public long createCountry(String code, String name, 
   String continent, String region) {

  ContentValues initialValues = new ContentValues();
  initialValues.put(KEY_CODE, code);
  initialValues.put(KEY_NAME, name);
  initialValues.put(KEY_CONTINENT, continent);
  initialValues.put(KEY_REGION, region);

  return mDb.insert(SQLITE_TABLE, null, initialValues);
 }

 public boolean deleteAllCountries() {

  int doneDelete = 0;
  doneDelete = mDb.delete(SQLITE_TABLE, null , null);
  Log.w(TAG, Integer.toString(doneDelete));
  return doneDelete > 0;

 }

 public Cursor fetchCountriesByName(String inputText) throws SQLException {
  Log.w(TAG, inputText);
  Cursor mCursor = null;
  if (inputText == null  ||  inputText.length () == 0)  {
   mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
     KEY_CODE, KEY_NAME, KEY_CONTINENT, KEY_REGION}, 
     null, null, null, null, null);

  }
  else {
   mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
     KEY_CODE, KEY_NAME, KEY_CONTINENT, KEY_REGION}, 
     KEY_NAME + " like '%" + inputText + "%'", null,
     null, null, null, null);
  }
  if (mCursor != null) {
   mCursor.moveToFirst();
  }
  return mCursor;

 }

 public Cursor fetchAllCountries() {

  Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
    KEY_CODE, KEY_NAME, KEY_CONTINENT, KEY_REGION}, 
    null, null, null, null, null);

  if (mCursor != null) {
   mCursor.moveToFirst();
  }
  return mCursor;
 }

 public void insertSomeCountries() {

  createCountry("AFG","Afghanistan","Asia","Southern and Central Asia");
  createCountry("ALB","Albania","Europe","Southern Europe");
  createCountry("DZA","Algeria","Africa","Northern Africa");
  createCountry("ASM","American Samoa","Oceania","Polynesia");
  createCountry("AND","Andorra","Europe","Southern Europe");
  createCountry("AGO","Angola","Africa","Central Africa");
  createCountry("AIA","Anguilla","North America","Caribbean");

 }

}

Source for POJO - Country.java

package com.as400samplecode;

public class Country {
 
 String code = null;
 String name = null;
 String continent = null;
 String region = null;
 
 public String getCode() {
  return code;
 }
 public void setCode(String code) {
  this.code = code;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getContinent() {
  return continent;
 }
 public void setContinent(String continent) {
  this.continent = continent;
 }
 public String getRegion() {
  return region;
 }
 public void setRegion(String region) {
  this.region = region;
 }

 
}

Source for Main Screen Layout - main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent" android:layout_height="fill_parent"
 android:orientation="vertical">

 <TextView android:layout_width="fill_parent"
  android:layout_height="wrap_content" android:padding="10dp"
  android:text="@string/some_text" android:textSize="20sp" />

 <EditText android:id="@+id/myFilter" android:layout_width="match_parent"
  android:layout_height="wrap_content" android:ems="10" 
  android:hint="@string/some_hint">
  <requestFocus />
 </EditText>

 <ListView android:id="@+id/listView1" android:layout_width="fill_parent"
  android:layout_height="fill_parent" />

</LinearLayout>

Source for List Layout - country_info.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="6dip" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Code: "
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:text="Name: "
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_below="@+id/textView2"
        android:text="Continent: "
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView3"
        android:layout_below="@+id/textView3"
        android:text="Region: "
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/continent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView3"
        android:layout_alignBottom="@+id/textView3"
        android:layout_toRightOf="@+id/textView3"
        android:text="TextView" />

    <TextView
        android:id="@+id/region"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView4"
        android:layout_alignBottom="@+id/textView4"
        android:layout_alignLeft="@+id/continent"
        android:text="TextView" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView3"
        android:layout_toRightOf="@+id/textView3"
        android:text="TextView" />

    <TextView
        android:id="@+id/code"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView2"
        android:layout_alignLeft="@+id/name"
        android:text="TextView" />

</RelativeLayout>

Source for application variables - strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">ListView CusrsorAdapter</string>
 <string name="some_text">
     Some North American Countries!
 </string>
 <string name="some_hint">
  Type here to filter&#8230;
 </string>
 
</resources>

Source for application manifest - AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.as400samplecode" android:versionCode="1"
 android:versionName="1.0">

 <uses-sdk android:minSdkVersion="15" />

 <application android:icon="@drawable/ic_launcher"
  android:label="@string/app_name" android:theme="@android:style/Theme.Light">
  <activity android:name=".AndroidListViewCursorAdaptorActivity"
   android:label="@string/app_name">
   <intent-filter>
    <action android:name="android.intent.action.MAIN" />

    <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>
 </application>

</manifest>

References


76 comments :

  1. Thanks for the example. very useful
    One question only works for later versions to 15, as I can make it work with version 8

    google translator

    ReplyDelete
    Replies
    1. In the Android manifest file you need to change the minsdkversion value to 8.

      Delete
    2. not working when changed value to 8

      Delete
    3. Working with v8 too!
      Thanks a lot!

      Delete
  2. Very useful. Finding good tutorial of data binding with list view is difficult.

    ReplyDelete
  3. Thanks a lot, these is no tutorial like this on the web :)

    ReplyDelete
  4. Thanks heaps! This is one of the few current as of Oct 2012 sqlite tutorials i've found that i can start learning from.

    ReplyDelete
  5. Hello,
    Please I want to ask what to do in order to make the list enter the text box when you click on it. Please I need an urgent help.

    Thanks for your attention.

    ReplyDelete
    Replies
    1. I don't follow your question. Please explain. If you need a EditText in the list then just replace the Checkbox with that and if you want to click on the list and have the contents populate an EditText then look for a ListView example where I have shown how to check for the contents that you clicked on a row and then get reference to your EditText and set the Text value there.

      Delete
  6. Really Helpfull!thx

    ReplyDelete
  7. thanks a lot, it's very very helpful

    ReplyDelete
    Replies
    1. If i want to display multiple value then how it is posible

      Delete
    2. What do you mean by multiple values? This example does display more than one field.

      Delete
  8. I cant get it to work ):

    ReplyDelete
  9. Where do you reference the Countries class? You have getters and setters but I don't see them being used anywhere.

    ReplyDelete
    Replies
    1. Well I looked at my code again and yes its not getting used anywhere in this example.

      Delete
  10. Source : Android_List_View_Cursor_Adaptor_Activity.java

    public void onTextChanged(CharSequence s, int start, int before, int count) {
    dataAdapter.getFilter().filter(s.toString());
    }
    });

    error :
    C:\Users\Compaq\Documents\NetBeansProjects\Android List View Cursor Adaptor\src\com\samplecode\Android_List_View_Cursor_Adaptor_Activity.java:97: local variable dataAdapter is accessed from within inner class; needs to be declared final
    dataAdapter.getFilter().filter(s.toString());

    how to fix this program???

    ReplyDelete
    Replies
    1. Not sure why you are getting this error. All I can say is you need to declare the variable dataAdapter to be final when you assign it so that you can use it within an inner class.

      Delete
  11. Fantastic tutorial!! thanks

    ReplyDelete
  12. Thanks for the tutorial...

    I have similar situation where the data is huge in sqlite DB,its around 50K records.
    Any better suggestions for the fetchCountriesByName() method implementatioins for frequent quering of the sqlite table.

    ReplyDelete
  13. its a very good tutorial.
    do have an example of this with images which has functionality like deleting an entry from the database?

    ReplyDelete
    Replies
    1. Don't know if I have one where there is a delete but you can read these to get some idea

      Android Database Content Provider Example using SQLite Database

      db.delete(DBAdapter.TableName, "Id=? AND field1=? AND field2=?",
      new String[] { Id.toString(), value1, value2 });

      Delete
  14. in this error has been occured so can u plz give the exact code.......
    thicha are error less in same project

    ReplyDelete
  15. Thanks a lot. Very good tutorial....

    ReplyDelete
  16. hello.. i used this code for my dictionary but the problem is that when there are too many words in the databse when u load the listview it really takes a lot of time.. can u solve that problem? thanks.. :)

    ReplyDelete
  17. hai,,, i am having 4 edittext (no,name,email,mobile) and a button .when i enter data in edittext and clicks on button values should store in database . Can u please help me for this

    ReplyDelete
  18. hi, i use this code:

    -----------------------------------------------------------------
    ListView listView = (ListView) findViewById(R.id.listView1);
    // Assign adapter to ListView
    listView.setAdapter(dataAdapter);


    listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView listView, View view,
    int position, long id) {
    // Get the cursor, positioned to the corresponding row in the result set
    Cursor cursor = (Cursor) listView.getItemAtPosition(position);

    // Get the state's capital from this row in the database.
    String countryCode =
    cursor.getString(cursor.getColumnIndexOrThrow("code"));
    Toast.makeText(getApplicationContext(),
    countryCode, Toast.LENGTH_SHORT).show();

    }
    });
    -----------------------------------------------------------


    but i have error, how to fix it ?

    here my code:
    -----------------------------------------------------------
    lv = (ListView) findViewById(R.id.SelectOrChangeOwnerListView);
    ArrayList mylv = new ArrayList();
    // Δημιουργία listadapter για τα στοιχεία
    listAdapter = new ArrayAdapter(this, R.layout.simplerow, mylv);

    //emfanise olous tous idioktites
    String sql = "SELECT name,surname,afm FROM owners ORDER BY surname ASC";
    c = myDatabase.rawQuery(sql, null);

    // Ελέγχει αν επιστρέψει null το ερώτημα που εκτελέστηκε στην ΒΔ
    if ( c != null )
    {
    if ( c.moveToFirst() )
    {
    do {

    OwnerName = c.getString(c.getColumnIndex("name"));
    OwnerSurname = c.getString(c.getColumnIndex("surname"));
    OwnerAfm = c.getLong(c.getColumnIndex("afm"));

    listAdapter.add("Ον/μο: \t"+OwnerSurname +" "+OwnerName+"\n"+
    "ΑΦΜ: \t\t"+OwnerAfm);

    } while (c.moveToNext());
    }
    }
    lv.setAdapter( listAdapter );
    lv.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView lv, View view,
    int position, long id) {
    // Get the cursor, positioned to the corresponding row in the result set
    Cursor c = (Cursor) lv.getItemAtPosition(position);

    // Get the state's capital from this row in the database.
    String afmOwner = c.getString(c.getColumnIndexOrThrow("afm"));

    Toast.makeText(getApplicationContext(),
    afmOwner, Toast.LENGTH_SHORT).show();

    }
    });
    ------------------------------------------------------------------------------

    ReplyDelete
    Replies
    1. the problem is the Cursor line

      Delete
  19. Instead of using Toast, how can I make the onItemClick direct the user to another activity that will display more information about the country, information that will be retrieved from the database?
    I have this code from the dictionary sample android provides, but I'm not really sure how to add a uri in the code you provided. Or can I do it another way?

    // Define the on-click listener for the list items
    mListView.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView parent, View view, int position, long id) {

    // Build the Intent used to open WordActivity with a specific word Uri
    Intent wordIntent = new Intent(getApplicationContext(), WordActivity.class);
    Uri data = Uri.withAppendedPath(DictionaryProvider.CONTENT_URI, String.valueOf(id));

    wordIntent.setData(data);
    startActivity(wordIntent);
    }
    });

    ReplyDelete
  20. when i change minSdkVersion to 15, works great but is it possible with minSdkVersion 8?

    ReplyDelete
    Replies
    1. ok , i found my mistake :) i should use
      import android.support.v4.widget.SimpleCursorAdapter;

      Delete
  21. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
  22. hi first of all thanks for your great tutorial
    i have a question suppose you have another edittext below the input edittext and in this your program searches for country codefor example you want to list countries starting with a and their code starts with D
    programmatically i want to know how can wee do a query on a returned cursor is it possible or not?
    and if yes how?

    ReplyDelete
  23. Hi! It's possible download the project?

    ReplyDelete
  24. I'm very new and Thank a lot, very for usefull project..
    i used eclipsed Juno (android:minSdkVersion="8") and tried step by step copy the script into the file ,
    first i got error..and thanks .. solved..
    below (for somebody who got error)
    at // the XML defined views which the data will be bound to
    solve then by define them inside R.java. (class id)
    public static final int code=0x7f080007;
    public static final int continent=0x7f080004;
    public static final int name=0x7f080006;
    public static final int region=0x7f080005;
    class layout
    public static final int country_info=0x7f030000;

    last i follow Anonymous posting onMarch 21, 2013 at 5:54 AM by repalcing
    import android.widget.SimpleCursorAdapter; import android.support.v4.widget.SimpleCursorAdapter;

    ReplyDelete
  25. Please how do i download this code. Better still can you mail it to me, please. bebefille6@yahoo.co.uk

    ReplyDelete
  26. Nice Tutorial! :)
    I'm pretty new to Android Developing and i wanted to add and delete items from the list. I'm confused on how to modify items and update the adapter.
    Please help.

    ReplyDelete
  27. Error here

    // the XML defined views which the data will be bound to
    int[] to = new int[] {
    R.id.code,
    R.id.name,
    R.id.continent,
    R.id.region,
    };

    ReplyDelete
  28. [2013-05-01 19:03:11 - as400samplecode] W/ResourceType( 3852): Bad XML block: header size 92 or total size 6112280 is larger than data size 0
    [2013-05-01 19:03:11 - as400samplecode] C:\Users\Roshan\workspace\as400samplecode\res\layout\activity_main.xml:11: error: Error: No resource found that matches the given name (at 'text' with value '@string/hello_world').
    [2013-05-01 19:03:11 - as400samplecode] C:\Users\Roshan\workspace\as400samplecode\res\menu\main.xml:3: error: Error: No resource found that matches the given name (at 'title' with value '@string/action_settings').
    [2013-05-01 19:03:44 - as400samplecode] W/ResourceType( 4708): Bad XML block: header size 93 or total size 6095040 is larger than data size 0
    [2013-05-01 19:03:44 - as400samplecode] C:\Users\Roshan\workspace\as400samplecode\res\layout\activity_main.xml:11: error: Error: No resource found that matches the given name (at 'text' with value '@string/hello_world').
    [2013-05-01 19:03:44 - as400samplecode] C:\Users\Roshan\workspace\as400samplecode\res\menu\main.xml:3: error: Error: No resource found that matches the given name (at 'title' with value '@string/action_settings').
    [2013-05-01 19:05:27 - as400samplecode] W/ResourceType( 3520): Bad XML block: header size 93 or total size 0 is larger than data size 0
    [2013-05-01 19:05:27 - as400samplecode] C:\Users\Roshan\workspace\as400samplecode\res\layout\activity_main.xml:11: error: Error: No resource found that matches the given name (at 'text' with value '@string/hello_world').
    [2013-05-01 19:05:27 - as400samplecode] C:\Users\Roshan\workspace\as400samplecode\res\menu\main.xml:3: error: Error: No resource found that matches the given name (at 'title' with value '@string/action_settings').
    [2013-05-01 19:05:55 - as400samplecode] W/ResourceType( 732): Bad XML block: header size 93 or total size 6095040 is larger than data size 0
    [2013-05-01 19:05:55 - as400samplecode] C:\Users\Roshan\workspace\as400samplecode\res\layout\activity_main.xml:11: error: Error: No resource found that matches the given name (at 'text' with value '@string/hello_world').
    [2013-05-01 19:05:55 - as400samplecode] C:\Users\Roshan\workspace\as400samplecode\res\menu\main.xml:3: error: Error: No resource found that matches the given name (at 'title' with value '@string/action_settings').

    ReplyDelete
  29. hi i have a project and i am furiously trying to view(list) the data i have added to the sqlite database but until now i haven't figured it out yet. will you help me fix my problem?

    ReplyDelete
    Replies
    1. btw if you are interested to help me, please do contact me here demafeliz.pam@gmail.com otherwise ... thanks then.

      Delete
    2. You can use tools like sqlLite manager to view your data. Or other way round you can write a simple page that displays the table data as it is. Let me know if you need any help on this. vimalp015{at}gmail{dot}com

      Delete
  30. when i have used above code than i got error like :"main cannot be resolved or is not a field" so how to fix this error

    ReplyDelete
  31. Hello!

    I am new to android and eclipse, so thanks for your tutorial. I got it to build, compile and run on my emulator. I can see a list of countries as you show in the images above and I can type text in the text box, however, I can not get the app to do anything. Does it do anything?

    Thanks!

    ReplyDelete
  32. Good learning for Sqlite...
    but what POJO Country created for??

    thanks

    ReplyDelete
  33. i have created my own method: visit - http://stackoverflow.com/a/16911148/1318946

    ReplyDelete
  34. how this filter works actually
    i mean it search in list view or database ??

    ReplyDelete
  35. Thanks for the information. I am trying to add data to a list view on tab. I am getting a null pointer exception when I try to set the list. The code and XML is below. Any help would be greatly appreciated.

    Code

    private void displayListView()
    {

    Cursor cursor = memDbHelper.fetchAllMembers();

    // The desired columns to be bound
    String[] columns = new String[]
    {
    memDbHelper.KEY_NAME,
    memDbHelper.KEY_CITY,
    memDbHelper.KEY_STATE
    };

    // the XML defined views which the data will be bound to
    int[] to = new int[]
    {
    R.id.name,
    R.id.city,
    R.id.state,
    };

    // create the adapter using the cursor pointing to the desired data
    //as well as the layout information
    memcusorAdapter = new SimpleCursorAdapter(this, R.layout.member_info,cursor,columns,to,0);
    System.out.println("After cursor Adapter");
    ListView listView = (ListView) findViewById(R.id.dirView);
    System.out.println("After Listview");
    // Assign adapter to ListView
    listView.setAdapter(memcusorAdapter);
    System.out.println("After setAdapter");



    }

    List view XML








    View XML





    ReplyDelete
    Replies
    1. First thing please use Android Log.d("Tag", "message") for debugging instead of System.out.println("");

      You need to provide an id to uniquely identify each row in your cursor (this is like the key of each database row). Use KEY_ROWID for this. Your problem should go away.

      Delete
  36. Any reason you chose to go this route instead of using a LoaderManager for managing your Cursor?

    ReplyDelete
  37. seems a good tutorial. I have to query 3 tables to show data and only save on 1 table, can tell me what changes I have to do to adapt this example? thanks

    ReplyDelete
  38. Useful tutorial, thank you very much.

    ReplyDelete
  39. thanks for the tuto! i have no errors but it doesn't work ( the application blocs )

    ReplyDelete
  40. i got this error on my logcat in the runtime

    03-11 20:11:24.650: E/AndroidRuntime(887): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.NIRR.redistributionsystem/com.NIRR.redistributionsystem.SearchCustomer}: java.lang.IllegalArgumentException: column '_id' does not exist



    Here is my cord

    Cursor cursor = dbHelper.fetchallcustomerdata();
    String[] columns = new String[] {
    DBCreater.Key_customer_Name,
    DBCreater.Key_customer_Shop,
    DBCreater.Key_customer_Location,
    DBCreater.Key_customer_Phon,
    DBCreater.Key_customer_Email,
    DBCreater.Key_customer_Address
    };

    int[] to = new int[]{
    R.id.tv_I_name_demo,
    R.id.tv_I_shop_demo,
    R.id.tv_I_location_demo,
    R.id.tv_I_phone_demo,
    R.id.tv_I_email_demo,
    R.id.tv_I_address_demo
    };
    //dataAdapter = new SimpleCursorAdapter(this, R.layout.demosearch, cursor, columns, to,0);
    final ListView listView = (ListView)findViewById(R.id.lv_I_listofcustomer_searchCustomer);
    dataAdapter = new SimpleCursorAdapter(this, R.layout.demosearch, cursor, columns, to,0);
    listView.setAdapter(dataAdapter);

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    i think the error occur on this line
    dataAdapter = new SimpleCursorAdapter(this, R.layout.demosearch, cursor, columns, to,0);

    please help me
    thank you

    ReplyDelete
  41. i get the point i have to make a column call _id in my db, now its work

    http://stackoverflow.com/questions/22340020/runtime-error-when-using-simplecursoradapter/22340148?noredirect=1#22340148

    ReplyDelete
  42. Nice tutorial, but it seems that when the record is big enough, what i mean is that when there's a lot of data inserted in the listview it takes time to load the records.

    ReplyDelete
    Replies
    1. Implement it in an AsyncTask or run a separate thread or use LoaderCallback

      Delete
  43. thanks a lot, i was really looking for this thing.

    ReplyDelete
  44. I have some problems in AndroidListViewCursorAdaptorActivity.java file.

    setContentView(R.layout.main);//main is not recognized

    int[] to = new int[] {
    R.id.code,
    R.id.name,
    R.id.continent,
    R.id.region,
    }; // the same problem with code, continent, region etc..

    this, R.layout.country_info, // same with country_info

    EditText myFilter = (EditText) findViewById(R.id.myFilter); // same with myFilter

    Can somebody help me or send me a working project?



    ReplyDelete
    Replies
    1. you can set int[] to = new int[] { android.R.id.text1,android.R.id.text2 };

      Delete
  45. Thank you excellent tutorial...

    ReplyDelete
  46. This comment has been removed by the author.

    ReplyDelete
  47. Doesn't it throw an ANR alert window on your phone? you are executing a db query a in the UI thread.

    ReplyDelete
  48. Nice Post Thanks

    www.androidspot1995.com

    ReplyDelete
  49. Great work.

    if i add a menu option button type on main.xml.

    When i presses it (just like a switch), the fetchCountriesByName(KEY_NAME + " like '%" + inputText + "%'") will be change to fetchCountriesByAddress(KEY_ADDRESS + " like '%" + inputText+ "%'")

    how can i do it?

    ReplyDelete
  50. Great code and example - can you please send to tonywright@rogers.com

    ReplyDelete
  51. how about update data ?

    ReplyDelete