Android Simple Cursor adapter and Cursor

1.3k Views Asked by At

I have build an app that take data with different attribute, adds them in the database and then shows it through a ListView.

I have done the part where data are added, but I Can't figure out how to fetch it(for now I just want the name) from the database and populate it in the ListView.

Here is the part in the database class.

public Cursor getCursor() {
    Cursor c = null;
    sqLiteDatabase = this.getReadableDatabase();
    String query = "SELECT * FROM tbl_customer";
    String where = null;
    c = sqLiteDatabase.query("tbl_customer", new String[]{"Name"}, where, null, null, null, null);
    if (c != null) {
        c.moveToFirst();

    }
    return c;
}

here is the part of code in activity which I want to show the ListView in.

private void populateListView(){
    Cursor cursor = db.getCursor();
   String []From = new String[]{"Name"};

    int [] to = new int[R.id.textView];

    SimpleCursorAdapter adapter;
    adapter = new SimpleCursorAdapter(this,R.layout.listview_items,cursor,From,to,0);

    ListView listView = (ListView)findViewById(R.id.ShowDataListView);
    listView.setAdapter(adapter);
}

Please guide me, where I have gone wrong, and correct me.

2

There are 2 best solutions below

4
On

You've to specify the From and To params of the SimpleCursorAdapter.

adapter = new SimpleCursorAdapter(this,R.layout.listview_items,cursor,
new String[] { "Name" },to,0);

As for to, you need to put the id of your textview from R.layout.listview_items. Let's assume the id of your TextView is R.id.text1 then the adapter will look like following,

adapter = new SimpleCursorAdapter(this,R.layout.listview_items,cursor,
new String[] { "Name" },
new int[] { android.R.id.text1 },
0);

Here, have a look at the documentation to grasp it more clearly.

0
On

you are using R.id.textView as a size of array

int [] to = new int[R.id.textView];

it should be like this

int [] to = new int[]{R.id.textView};