2016-08-23 29 views
0

我想要做的是打開一個圖像,這個圖像uri應該存儲在我的本地數據庫,然後我重新打開應用程序後插入的最後一張圖片將出現,但我有一個問題,當我重新打開應用程序的圖像不是從數據庫中的uri加載的。無法查看圖像通過存儲在Uql Sqlite

我的代碼:

private static final int PICK_IMAGE = 100; 
private ImageView imageView; 
SQLiteDatabase DB; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    imageView = (ImageView) findViewById(R.id.image_view); 

    DB = this.openOrCreateDatabase("test",MODE_PRIVATE,null); 
    DB.execSQL("CREATE TABLE IF NOT EXISTS users (uri VARCHAR)"); 

    Cursor c = DB.rawQuery("SELECT * from users",null); 
    c.moveToLast(); 
    int UriIndex = c.getColumnIndex("uri"); 
    Uri image = Uri.parse(c.getString(UriIndex)); 

    imageView.setImageURI(image); 

    Button pickImageButton = (Button) findViewById(R.id.pick_image_button); 
    pickImageButton.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      openGallery(); 
     } 
    }); 
} 

private void openGallery() { 
    Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
    startActivityForResult(intent, PICK_IMAGE); 
} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) { 
     Uri imageUri = data.getData(); 
     DB.execSQL("INSERT INTO users (uri) VALUES ('"+imageUri.toString()+"')"); 
     imageView.setImageURI(imageUri); 
    } 
}} 

感謝。

回答

0

您從ACTION_PICK獲取的Uri將持續與活動一樣長的時間。您可以使用FLAG_GRANT_READ_URI_PERMISSION和/或FLAG_GRANT_WRITE_URI_PERMISSION來臨時訪問其他組件。但是the Uri will be useless once your process ends,如果它有一個content方案(和大多數)。

如果你期待有由Uri標識的內容長期訪問:

  • 使用ACTION_OPEN_DOCUMENTtakePersistableUriPermissions(),作爲the Storage Access Framework一部分,或者

  • 製作的本地副本將圖像插入到您應用程序的內部存儲器中

+0

非常感謝您,很棒的新信息^ _ ^ – SimpleProgramming