Search code examples
androidsqlitecursor

How to read more than one column in database by cursor and fill into a list?


I have a table called tbl_homework. There are 3 columns called "_id", "hw" and "hwdate". Now I like to read out "hw" AND "hwdate". So I like it on the same line in this listview. I have to say that it is working without crash or error. It just don't show the date... Following picture will tell you what I mean:

enter image description here

Here are the code snippets to tell you how I tried this:

    private Button.OnClickListener add_hw = new Button.OnClickListener(){
    public void onClick(View arg0) {
        mDbHelper.open_database_rw();
        String txt_insert_hw = insert_hw.getText().toString(); 

        if(txt_insert_hw.equals("")){
            doMessage("Keine Eingabe!");
        }else{
            String date_picker_message= date_pick.getDayOfMonth() + "/" + (date_pick.getMonth()+1) + "/" + date_pick.getYear();
            final String INSERT_HW = "INSERT INTO tbl_homework ('hw', 'hwdate') VALUES ('"+txt_insert_hw+"', '"+date_picker_message+"')";
            db.execSQL(INSERT_HW);
            insert_hw.setText("");
            fillData();
        }
    }
};


    private void fillData() {
    // Get all of the notes from the database and create the item list

    Cursor c = mDbHelper.fetchAllNotes();

    startManagingCursor(c);

    String[] from = new String[] { dbHelper.KEY_TITLE, dbHelper.KEY_DATE};
    int[] to = new int[] {R.id.txt_notes_row};

    // Now create an array adapter and set it to display using our row
    SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
        setListAdapter(notes);
    }

And in mDbHelper:

    public Cursor fetchAllNotes() {
    return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_DATE}, null, null, null, null, null);
}

Soulution of this problem: (Received from Jury)

    String[] from = new String[] { dbHelper.KEY_TITLE, dbHelper.KEY_DATE};
    int[] to = new int[] {R.id.txt_notes_row, R.id.txt_notes_row2};

I had to add a new TextView. dbHelper.KEY_TITLE AND dbHelper.KEY_DATE coudn't be handle by one TextView. So I had to add a new TextView to handle the second part of my String "from".


Solution

  • I think the problem is that you try to match two columns (from) to only one container (to) here:

    String[] from = new String[] { dbHelper.KEY_TITLE, dbHelper.KEY_DATE};
    int[] to = new int[] {R.id.txt_notes_row};
    

    You should specify two fields in the list row where you store your values. I.e. your R.id.txt_notes_row should contain two widgets (for instance, R.id.txtview1 and R.id.txtview2) where you can store your values from db.