SimpleProgramming SimpleProgramming - 3 months ago 6
Android Question

Can't view image via stored Uri in Sqlite

What i'm trying to do is to open a image and this image uri should be stored at my local database and then after i reopen the app the last image inserted will appear but i have a problem when i reopen the app the image not loaded from the uri in database.

My Code :

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);
}
}}


Thanks.

Answer

The Uri that you get back from ACTION_PICK will last as long as the activity does. You can use FLAG_GRANT_READ_URI_PERMISSION and/or FLAG_GRANT_WRITE_URI_PERMISSION to give temporary access to other components. But the Uri will be useless once your process ends, if it has a content scheme (and most will).

If you are expecting to have long-term access to the content identified by the Uri:

  • Use ACTION_OPEN_DOCUMENT and takePersistableUriPermissions(), as part of the Storage Access Framework, or

  • Make a local copy of the image into your app's internal storage