在ListFragment中实现onListItemClick

时间:2016-01-10 19:03:59

标签: java android textview android-listfragment simplecursoradapter

我正在尝试使用赞美诗应用,我使用了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;

}
}

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

首先,您需要获取所选项目,然后通过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