【发布时间】:2014-10-11 16:40:50
【问题描述】:
从drawable 文件夹中检索图像的最佳方法是什么,而这些图像的名称存储在DB 中并在listView 中显示它们?
假设我在drawable 文件夹中有三张图片,它们的名称存储在数据库中:
pic1.jpeg
image2.jpeg
- another_image.jpeg
我还有一个名为getAllimages() 的方法,我在其中检索图像名称并将它们作为Cursor 从数据库返回:
public Cursor getAllImages(){
String sql = "SELECT iId as _id," + COLUMN_IMG_DESC + "," + COLUMN_IMG_NAME + " FROM " + TABLE_NAME";
Cursor cursor = db.rawQuery(sql, null);
if(cursor != null)
cursor.moveToFirst();
return cursor;
}
其中COLUMN_IMG_DESC 是image description,COLUMN_IMG_NAME 是存储在DB 中的name of the image
然后我有一个CursorAdapter,我尝试将图像及其描述映射到listView:
ListView customListView = (ListView)findViewById(R.id.lvCustom);
String[] from = { DatabaseHelper.COLUMN_IMG_DESC, DatabaseHelper.COLUMN_IMG_NAME};
int[] to = {R.id.ivImg, R.id.tvTitle};
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.custom_listview, cursor, from, to, 0);
cursorAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
ImageView imageImageView = (ImageView)findViewById(R.id.ivImg);
String imageValue = cursor.getString(1); //get image names
int[] imgResourceIds = new int[cursor.getColumnCount()]; //initialize array for resource Ids
String images[] = new String[cursor.getColumnCount()]; //initialize an array for image names
for(int i=0; i<cursor.getColumnCount(); i++){
images[i] = imageValue; //store image names to an initialized array
imgResourceIds[i] = getResources().getIdentifier(images[i], "drawable", packageName); //get image name
imageImageView.setImageResource(imgResourceIds[i]); //set image to imageView
}
return true;
}
});
customListView.setAdapter(cursorAdapter);
但我得到了这个结果:我如何解决这个问题?
提前致谢:)
【问题讨论】:
标签: android image sqlite listview android-listview