[]我有一个使用SQLite Manager创建的本地数据库,我想要从数据(项目名称,价格和图像)中检索数据数据库并显示在列表视图中。我将图像存储在可绘制文件夹(kids.jpg)中,并在数据库中将图像名称存储为字符串(小孩)。如何从本地数据库检索图像并在ListView中显示(Android)
基于查询条件,listview的内容会不断变化。
我现在面临的问题是我可以检索名称,价格,甚至是图像的名称,并在列表视图中列出,但我不知道如何在列表视图中显示图像。
我知道下面的代码可以用来从字符串中调用可绘制的图像,但我该如何将代码插入到listview中?
int Image = getResources().getIdentifier("com.example.user.birthdaygiftpredictor:drawable/" + Gimage, null, null);
gift_image.setImageResource(Image);
下面是我对SimpleCursorAdapter
Cursor cursor = db.rawQuery("SELECT * FROM gift WHERE "+strValue+" OR hobby LIKE '%"+hobby+"%' OR gift_price<='"+budget+"' ORDER BY gift_price ASC ;",null);
String[] from = new String[] {
cursor.getColumnName(0),
cursor.getColumnName(1),
cursor.getColumnName(2),
cursor.getColumnName(4),
cursor.getColumnName(4),
cursor.getColumnName(5),
cursor.getColumnName(10)
};
int[] to = new int[] {
R.id.gift_id,
R.id.gift_name,
R.id.gift_price,
R.id.gift_image,
R.id.image,
R.id.gift_description,
R.id.link
};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
Result_1_match.this, R.layout.view_gift_list, cursor, from, to);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder(){
public boolean setViewValue(View view, Cursor cursor, int columnIndex){
if(view.getId() == R.id.gift_image){ // your ImageView id in xml
DbHelper2 connect = new DbHelper2(Result_1_match.this);
connect.openDataBase();
SQLiteDatabase db = connect.getWritableDatabase();
List<String> a = new ArrayList<>();
Cursor c = db.rawQuery("your query;", null);
int i=0;
while (c.moveToNext()) {
a.add(i,c.getString(0));
i++;
}
ImageView imageView=(ImageView) view.findViewById(R.id.gift_image);
int resID = getApplicationContext().getResources().getIdentifier(cursor.getString(columnIndex), "drawable", getApplicationContext().getPackageName());
imageView.setImageResource(resID);
return true; //true because the data was bound to the view
}
return false;
}
});
list.setEmptyView(findViewById(R.id.imageView3));
list.setAdapter(adapter);
更新代码:最后,我解决了这个问题,并成功上市了使用穆克什拉纳的概念形象。以上是正确的代码。非常感谢你:)
我已经更新了问题中的代码,插入了您提供的代码。不幸的是,图像仍然无法显示。我在调试模式下运行,并为resID获得0。你能否再次检查我的代码并纠正我,如果我错了。感谢您的帮助。 – user5648749
这个游标的价值是什么。调试时getString(columnIndex),它是正确的图像名称? –
我得到的值是4而不是图像名称 – user5648749