在 ListFragment 中实现 onListItemClick

Implement onListItemClick in ListFragment

我正在尝试一个赞美诗应用程序,我使用了 SQLiteAssetHelper 和 SimpleCursorAdapter。我已经能够使用 ListFragement 在 ListView 中加载赞美诗的标题。我坚持在 ListFragment 中实现 onListItemClick。有人可以帮我吗?谢谢。下面是我的代码;

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?
}
} 

还有我的数据库;

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;

}
}

感谢您的帮助

首先,您需要获取所选项目,然后通过 Cursor 对象检索其数据。以下内容应该会得到预期的行为:

@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...
}

无需再次请求,just use the existing Cursor