SQLite - 从数据库中检索图像并在ImageView中显示

时间:2018-05-14 17:05:17

标签: java android sqlite android-sqlite

我已将图像作为byteArrayblob存储到我的数据库中,但是当我再次尝试访问时,我无法在ImageView中显示该图像。我收到此消息

  

无法从CursorWindow读取第0行第4行。

这是我的代码:

Home.java

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    mDatabaseHelper = new DatabaseHelper(this);
    imageView = findViewById(R.id.imageView);
    Cursor data = mDatabaseHelper.getData2();
    if(data.moveToNext() && data.getCount() > 0){
        byte[] image = data.getBlob(4);
        Bitmap finalImage = BitmapFactory.decodeByteArray(image, 0, image.length);
        imageView.setImageBitmap(finalImage);
    }
 }

DatabaseHelper.java

public boolean addEntryImage(byte[] image) throws SQLiteException {
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues cv = new  ContentValues();
    cv.put(COL5,image);
    long result = database.insert( TABLE_NAME, null, cv );

    //if date as inserted incorrectly it will return -1
    if (result == -1) {
        return false;
    } else {
        return true;
    }
}
public Cursor getData2(){
    SQLiteDatabase db = this.getWritableDatabase();
    //String query = "SELECT " + COL5 + " FROM " + TABLE_NAME;
    Cursor data = db.rawQuery("select * from profile_table", null);
    return data;
}

所有帮助将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:0)

你会从if块中取出data.moveToNext()。然后再试一次