将listview链接到sqlite数据库

时间:2012-08-11 22:07:40

标签: android sqlite listview

以下是我想要做的事情,并希望就最佳方法提出一些建议:

  • 有一个包含单词的数据库,以及与该单词关联的图像文件的名称。
  • 数据库中的单词将显示在listview中
  • 选择单词后,新活动将开始在图像视图中显示单词和图像。

最好将这些术语存储在一个数组中,并从该数组填充列表视图,然后从数据库中取出onitemclick?或者可以使用数据库中的术语填充列表视图吗?

如果文件名存储在db?

中,android能否显示图像

1 个答案:

答案 0 :(得分:0)

实现所需内容的最佳方法是将术语和图像路径存储在数据库中,然后使用该路径从您放入的任何位置获取图像。

图像可以存储在数据库中,但普遍的共识是,最好将图像存储在数据库外部,并在数据库中存储所述图像的路径。

您的数据库可以像三列一样简单......“_ id”,“term”和“term_image”。

你可以做一个简单的查询来一次获取所有信息(因此只需要查询一次数据库)。

然后使用该查询返回的光标填充您的术语列表,并使用onListItemClick开始一个新活动,以使用列表中与该术语位于同一记录中的路径显示关联的图像清单。

查询以获取数据:

public Cursor fetchAllTerms() {
    return mDb.query(TERMS_TABLE, new String[] { "_id", "term", "term_img" }, null, null, null, null, null);
}

在列表中使用它:

    mTermCursor = mDbHelper.fetchAllTerms();
    getActivity().startManagingCursor(mTermCursor);

    String[] from = new String[] { YourDBClass.term };
    int[] to = new int[] { android.R.id.Text1 };
    SimpleCursorAdapter ranks = new SimpleCursorAdapter(getActivity(),
            android.R.layout.simple_list_item_1, mRankCursor, from, to);
    setListAdapter(ranks);

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
     String imagePath = mTermCursor.getString(mTermCursor.getColumnIndexOrThrow("term");
     // code to start your new activity and put the image path into the bundle to be passed
}