18

I am programming an android app that should use a database to store data and read from it. Using this tutorial (on archive.org) I got the app to create a database and I'm able to create new entries, however, I don't know, how to read the database to get the stored data in a ListView. I know there are many similar questions on this website but it seems none of them apply to the way, the database from the tutorial works.

Code:

import java.util.Calendar;

import maturarbeit.nicola_pfister.studenttools.database.DBAdapter;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;


public class Marks extends ListActivity {

DBAdapter db = new DBAdapter(this);

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

@Override
protected void onPause() {
    super.onPause();
    db.close();
}

@Override
protected void onResume() {
    super.onResume();
    db.open();

    getData();
}

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

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.marks, menu);
    return true;
}

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_add:
        Calendar cal = Calendar.getInstance();
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int month = cal.get(Calendar.MONTH);
        final String date = day + "." + month;
        Builder builder = new Builder(this);
        builder
            .setTitle(R.string.dialog_addmarks)
            .setItems(R.array.markslist, new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    @SuppressWarnings("unused")
                    long id;
                    String selection = getResources().getStringArray(R.array.markslist)[which];
                    id = db.insertMark(date, "Default", selection);
                    }
            })
            .show();
        getData();
        break;
    case R.id.menu_delete:
            //Deleting function yet to be implemented.
        break;
    }
    return super.onOptionsItemSelected(item);
}
}

Edit: The ListView ID was wrong since it had to be android:list.

Kev
  • 118,037
  • 53
  • 300
  • 385
NiPfi
  • 1,710
  • 3
  • 18
  • 28

2 Answers2

62

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.

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 });
    ...
}
starball
  • 20,030
  • 7
  • 43
  • 238
Sam
  • 86,580
  • 20
  • 181
  • 179
  • Thank you. I think I get, what you are trying to explain. I used your adapter but I still get an exception which crashes my app. I assume the error is somewhere else then? – NiPfi Aug 22 '12 at 18:10
  • Copy and paste the LogCat (use the edit link in the lower left of your question). I'll take a look. Tag me in a comment (with "@Sam") when you've done this. – Sam Aug 22 '12 at 18:13
  • I added the LogCat to my question. Thanks for helping me. – NiPfi Aug 22 '12 at 18:33
  • Hmm, I'm not sure what is happening. It looks like your debugger never connects to your apps and times out: `Launch timeout has expired, giving up wake lock!`. Have you tried running the app without the debugger? (In Eclipse, Ctrl+F11) – Sam Aug 22 '12 at 18:50
  • By running without debugging I get the error message which is probably the cause: 08-16 00:07:06.257: E/AndroidRuntime(2716): java.lang.RuntimeException: Unable to start activity ComponentInfo{maturarbeit.nicola_pfister.studenttools/maturarbeit.nicola_pfister.studenttools.Marks}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list' It's ID is marks_list right now but how do i change it to an android.R.* id? OK, I fixed it. ID had to be android:list – NiPfi Aug 22 '12 at 18:57
  • Perfect. You are extending a ListActivity which must have a ListView with the id element `android:id="@android:id/list"` in marks.xml. – Sam Aug 22 '12 at 19:04
  • Yes. That was the problem. Now the code works. One little question, how do I execute my getData Method after adding a new entry? by now, it only refreshes the ListView when I click the add button again. – NiPfi Aug 22 '12 at 19:08
  • Never mind, of course it had to be in the onClick. Sometimes I only need to thnk about it a second time to figure it out. Thank you very much for your help. – NiPfi Aug 22 '12 at 19:16
  • I added one why to do this anyway, since I had already written it. Good luck! – Sam Aug 22 '12 at 19:21
  • It must benoted that this is an excellent explanation. Got it after searching high and low for understanding. – carl Mar 27 '14 at 20:10
  • 1
    The method used here was deprecated in API level 11. https://developer.android.com/reference/android/widget/SimpleCursorAdapter.html#SimpleCursorAdapter(android.content.Context, int, android.database.Cursor, java.lang.String[], int[]) – matt.writes.code Apr 17 '15 at 23:43
0

An adapter isn't used on each item in the cursor, one adapter is created for the entire cursor.You can set this listview to use that cursor. Try some SimpleCursorAdapter tutorials like this

onkar
  • 4,427
  • 10
  • 52
  • 89
HannahMitt
  • 1,010
  • 11
  • 14