Android: Using Simplecursoradapter to Get Data from Database to Listview

Android: Using SimpleCursorAdapter to get Data from Database to ListView

Using the database format in the tutorial that you linked to, every row has an _id, isbn, title, and publisher. Now let's assume that you want to display every title in a ListView:

db = new DBAdapter(this);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
db.getAllTitles(),
new String[] { "title" },
new int[] { android.R.id.text1 });

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

(You don't need to loop through the Cursor yourself, an adapter does this work for you!)

The last two parameters in your SimpleCursorAdapter constructor are what you are missing. They are the "from" and "to" parameters:

  • We want to get the name of each book which is stored in the column name title, this is where we get the information "from".
  • Next we need to tell it where "to" go: android.R.id.text1 is a TextView in the android.R.layout.simple_list_item_1 layout. (You can dig through your SDK and see the simple_list_item_1.xml file yourself or just trust me for the moment.)

Now both the "from" and "to" parameters are arrays because we can pass more than one column of information, try this adapter as well:

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
android.R.layout.simple_list_item_2,
db.getAllTitles(),
new String[] { "title", "publisher" },
new int[] { android.R.id.text1, android.R.id.text2 });

With this adapter the books in their database will displayed by title, then publisher. All we had to do is use a layout android.R.layout.simple_list_item_2 that takes two fields and define which columns go to which TextViews.

I hope that helps a little. There's plenty more to learn but maybe this will give you some basics.


Last Comment

Off the top of my head, to refresh the ListView after adding new data try this:

public void onClick(DialogInterface dialog, int which) {
String selection = getResources().getStringArray(R.array.markslist)[which];
db.insertMark(date, "Default", selection);
cursor.requery();
adapter.notifyDataSetChanged();
}

You'll have to define adapter and create a variable for cursor but that's simple:

public class Marks extends ListActivity {
SimpleCursorAdapter adapter;
Cursor cursor;
DBAdapter db = new DBAdapter(this);
...

And change getData() accordingly:

private void getData() {
cursor = db.getAllMarks();
adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
cursor,
new String[] { "value" },
new int[] { android.R.id.text1 });
...
}

Good luck!

Populating a listView with SQLite database using simple cursor adapter

Problem solved. I found the answer in developer.android.com in Content Provider section:

Note: A provider isn't required to have a primary key, and it isn't required to use _ID as the column name of a primary key if one is present. However, if you want to bind data from a provider to a ListView, one of the column names has to be _ID. This requirement is explained in more detail in the section Displaying query results.

Hear is the Original link:

http://developer.android.com/guide/topics/providers/content-provider-basics.html

Data from Cursor added to ListView with SimpleCursorAdapter shows white text (how to make it black)

Like Egor said, if you could show some more code, that would be helpful.

In the meantime:
It looks like you are using list-view items that have a 'light' (holo) theme while your app (or just that activity() uses a 'dark' (holo) theme. The textviews' text-color is picked up from the app's dark theme (white font color) on top of white background.

To figure out why that happens, we need more code (AndroidManifest.xml, for example) from you.

Update after OP's comment:

public void displayWords(Cursor c){

// Creates a new SimpleCursorAdapter
SimpleCursorAdapter mCursorAdapter = new SimpleCursorAdapter(
getApplicationContext(), // The application's Context object
android.R.layout.simple_list_item_1, // A layout in XML for one row in the ListView
c, // The result from the query
new String[] {DatabaseTable.COL_WORD}, // A string array of column names in the cursor
new int[] { android.R.id.text1 }){
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View newView = super.newView(context, cursor, parent);
((TextView)newView.findViewById(android.R.id.text1)).setTextColor(Color.BLACK);
return newView;
}
}; // An integer array of view IDs in the row layout

// Sets the adapter for the ListView
setListAdapter(mCursorAdapter);

/* Using SimpleCursorAdapter to get Data from DB.
* stackoverflow.com/questions/12077955/android-using-simplecursoradapter-to-get-data-from-database-to-listview
*/
}

I added an override of the adapter's newView method to your code, which would allow you to set/change the text's color. Try it and see if it works.

SimpleCursorAdapter to populate ListView

I'm noticing a couple of issues here.

First,

final int[] to = { R.id.list_row_title, R.id.list_row_content };

should be

final int[] to = { R.id.list_row_type, R.id.list_row_title, R.id.list_row_content };

Secondly, you are setting the adapter incorrectly. Instead of getting the list view and setting the adapter, you can set the adapter directly:

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.history_list_row, cursor, from, to);
setListAdapter(adapter);

Third, you are closing the cursor after the loop.

//Closes the Cursor, releasing all of its resources and making it completely invalid.
cursor.close();

So by the time the list view is displaying items, the cursor no longer has the rows associated with it

Android SimpleCursorAdapter and CursorLoader

Briefly for now, the main points are:

  1. onCreateLoader gets the data from the SQLite database.
  2. This code adapter = new SimpleCursorAdapter, populates the adapter.
  3. This code listView.setAdapter(adapter); populates the ListView.

There is a nice Stackoverflow answer at Using SimpleCursorAdapter to get Data from Database to ListView

populate listView from a SimpleCursorAdapter

Typically when your app crashes you need to post the logcat to allow us to help you. However, here I'm pretty sure you are getting an error that says something like, "you need a ListView with the id android.R.id.list". You need to do just what it says when your Activity extends ListActivity. So the id of your ListView in your layout should be

<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

You can do this or just extends Activity instead of extends ListActivity. Using ListActivity basically gives you some convenience methods which I don't see you using so you can try just changing it to extends Activity. If this doesn't solve your problem then you *need to post your logcat from the crash.

Get selected item from ListView bound with SimpleCursorAdapter

So a couple of points: after you fetch the cursor, you want to call startManagingCursor. This ties the cursor's lifecycle with Activity's lifecycle (so when the Activity gets destroyed the cursor gets closed/cleaned up).

startManagingCursor(c);
ListAdapter adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
c,
new String[] {"name"},
new int[] {android.R.id.text1});
setListAdapter(adapter);

Also, the database isn't closed, the Cursor typically keeps a live connection to the DB (so the ListView can scroll and do things of that nature that may require future access to the Cursor's contents.

To your core question, the easiest way to do it in onListItemClick is this:

Cursor c = ((SimpleCursorAdapter)l.getAdapter()).getCursor();
c.moveToPosition(position);

You can then use the c.getLong(0) to get the id (assuming you fetched the id column as the first column which is generally the case). However, note that the id is passed in as part of the signature (see the last argument in public void onListItemClick(ListView l, View v, int position, long id)) so you really don't need to fetch it again (but you certainly can if you want to burn the cycles). For accessing other columns you can do the same thing, just change the column index.

Hope that helps.



Related Topics



Leave a reply



Submit