添加图像使用资产文件夹的图片

问题描述:

我在做Android应用程序具有此数据库从SQL一个ListView:添加图像使用资产文件夹的图片

public void onCreate(SQLiteDatabase db) { 
    String sql = "CREATE TABLE IF NOT EXISTS snacks (" + 
       "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + 
       "name TEXT, " + 
       "disc TEXT, " + 
       "photo TEXT, " + 
       "thumb TEXT, " + 
       "ingre TEXT, " + 
       "howto TEXT, " + 
       "info TEXT, " + 
       "snackId INTEGER)"; 
    db.execSQL(sql); 

    ContentValues values = new ContentValues(); 

    values.put("name", "Name 1"); 
    values.put("disc", "here is the description"); 
    values.put("photo", "stub.png"); 
    values.put("thumb", "stub.png"); 
    values.put("ingre", "the ingredients of the snack"); 
    values.put("howto", "how to make this thing"); 
    values.put("info", "basically its this much calorie and such and such"); 
    db.insert("snacks", "name", values);...............etc etc ......` 

在我的活动之一,我有一个可以查询数据库搜索栏。结果显示在列表视图中。当我点击列表中的一个项目时,我会得到它的详细信息,包括照片。 我的照片位于资源文件夹中。我想从资产文件夹中检索照片并显示它的缩略图。我尝试使用资产经理这样

public void search(View view) { 
    cursor = db.rawQuery("SELECT _id, name, disc, thumb FROM snacks WHERE name LIKE ?", new String[]{"%" + searchText.getText().toString() + "%"}); 

    adapter = new SimpleCursorAdapter(
    this, 
    R.layout.cook_tab_snackslist, 
    cursor, 
    new String[] {"name", "disc"},   
    new int[] {R.id.name, R.id.disc}); 

    Thumb = (ImageView) findViewById(R.id.thumb); 
    try { 
    InputStream bitmap=getAssets().open(cursor.getString(cursor.getColumnIndexOrThrow("thumb"))); 
    Bitmap bit=BitmapFactory.decodeStream(bitmap); 
    Thumb.setImageBitmap(bit); 
    } catch (IOException e1) { 
    e1.printStackTrace(); 
    } 
    setListAdapter(adapter); 
} 

我知道这是不正确的,我发现了以下错误:

android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 7 

我能做些什么?我甚至会以正确的方式去解决这个问题吗?

+0

答案从slukian是正确的。为了扩展它 - 查询返回的游标位置在第一条记录之前设置为'之前'。由于游标的第一条记录的'索引'为0,因此光标位置为-1是有意义的。正如slukian所说,你需要通过调用moveToFirst或简单的moveToNext来移动光标位置。 – Squonk 2012-02-16 19:59:15

+0

现在,当我搜索不存在的东西时,应用程序崩溃并出现此错误: .CursorIndexOutOfBoundsException:请求索引0,大小为0 ...任何想法? – FirstLaw 2012-02-19 18:05:24

你作出查询后,加入这一行(您也应该检查之前,为了确保光标不在):

cursor.moveToFirst(); 
+0

谢谢,它停止了我的错误,但没有任何反应,我似乎无法在列表视图中显示图像... – FirstLaw 2012-02-19 18:02:28

+0

现在,如果我查询的信件不在我的列表中,该应用程序崩溃错误报告,.CursorIndexOutOfBoundsException:请求的索引0,大小为0 – FirstLaw 2012-02-19 18:04:53

+0

好的,我在修正了新错误后读取: if(cursor.getCount()== 1) { \t cursor.moveToFirst(); 但仍然没有显示缩略图:(帮助! – FirstLaw 2012-02-19 18:27:14