Search code examples
javaandroidtextviewandroid-listfragmentsimplecursoradapter

Implement onListItemClick in ListFragment


I am trying my hands on a hymnal app and I have used SQLiteAssetHelper and SimpleCursorAdapter. I have been able to load the title of the hymns in ListView using ListFragement. I am stuck with the implementation of onListItemClick in the ListFragment. Can someone, please, help me with it?. Thanks. Below is my code;

public class HymnsFragment extends ListFragment {

private Cursor hymns;
private DataBase db;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    db = new DataBase(getContext());
    hymns = db.getHymns();// you would not typically call this on the main thread

    ListAdapter adapter = new SimpleCursorAdapter(getContext(),
            android.R.layout.simple_list_item_2,
            hymns,
            new String[] {"_id","title"}, //table values
            new int[] {android.R.id.text1,android.R.id.text2});

    setListAdapter(adapter);
}

@Override
public void onDestroy() {
    super.onDestroy();
    hymns.close();
    db.close();
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    // WHAT TO DO HERE TO GET VALUE FROM DATABASE TO DISPLAY IN TEXTVIEW?
}
} 

And my database;

public class DataBase extends SQLiteAssetHelper {

private static final String DATABASE_NAME = "mydatabase";
private static final int DATABASE_VERSION = 1;

public DataBase(Context context) {

    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

public Cursor getHymns() {

    SQLiteDatabase db = getReadableDatabase();
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    String [] sqlSelect = {"0 _id","_id","title"};
    String sqlTables = "hymns";

    qb.setTables(sqlTables);
    Cursor c = qb.query(db, sqlSelect, null, null,
            null, null, null);

    c.moveToFirst();
    return c;

}
}

Thanks for helping


Solution

  • First, you need to get the selected item, then retrieve its datas by the Cursor object. Something as follows should get the expected behaviour:

    @Override
    public void onListItemClick(ListView listview, View view, int position, long id) {
        super.onListItemClick(listview, view, position, id);
    
        // get the item selected directly here
        Cursor c = (Cursor) listview.getAdapter().getItem(position);
    
        // get specific hymn text from database item result
        String hymnText = c.getString(c.getColumnIndex("hymn_text"));
        // or whatever you want to retrieve from database: authors, songs...
        String hymnAuthor = c.getString(c.getColumnIndex("hymn_author"));
    
        // do some stuff with the previous values as updating a TextView...
    }
    

    No need to do a request again, just use the existing Cursor.