从数据库中获取文件名并使用它来填充ImageView

时间:2014-04-09 11:58:13

标签: java android database sqlite

我正在创建一个应用程序,此时需要从sqlite数据库获取文件名,获取具有该文件名的图像并将其插入ImageView,我现在已经创建了此代码,但我想我我在这里做错了什么......

Database db = new Database(getApplicationContext());
SQLiteDatabase readableDatabase = db.getReadableDatabase();
final Cursor curFileName = readableDatabase.rawQuery("select filename from data order by id asc", null);
image = (ImageView) findViewById(R.id.image);
int filename = curFileName.getColumnIndex("filename");
String filenameString = curFileName.getString(filename);
d = Drawable.createFromPath(Environment.getExternalStorageDirectory().toString()+filenameString);
Toast.makeText(getApplicationContext(), filenameString, Toast.LENGTH_SHORT).show();
handleDrawable(d);

对不起,这是例外:

04-09 13:48:16.950: E/AndroidRuntime(30802): FATAL EXCEPTION: main
04-09 13:48:16.950: E/AndroidRuntime(30802): java.lang.RuntimeException: Unable to start activity ComponentInfo{g.d.filer/g.d.filer.Favorites}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 33

3 个答案:

答案 0 :(得分:1)

您必须先定位光标才能阅读

 int filename = curFileName.getColumnIndex("filename");
 if (cur.moveToFirst()) { // position cursor to first item. false: empty resultset
     String filenameString = curFileName.getString(filename);
     d = Drawable.createFromPath(Environment.getExternalStorageDirectory().toString()+filenameString);
     Toast.makeText(getApplicationContext(), filenameString, Toast.LENGTH_SHORT).show();
     handleDrawable(d);
     ...
 }

答案 1 :(得分:0)

我编辑了我的答案。我希望这会对你有所帮助。 :d

if (cursor.moveToFirst()){
   do{
      String data = cursor.getString(cursor.getColumnIndex("filename"));
      // here you have to generate Image view and add bitmap to imageview
   }while(cursor.moveToNext());
}
cursor.close()

答案 2 :(得分:0)

你添加了

吗?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
清单文件中的

。 因为,从Android 4.4开始,如果您只读取或写入应用程序专用的文件,则不需要这些权限。有关更多信息,请参阅

http://developer.android.com/guide/topics/data/data-storage.html#filesExternal