Skip to content

Instantly share code, notes, and snippets.

@kursatsaim
Created May 9, 2024 07:40
Show Gist options
  • Save kursatsaim/e3643b71d16a104bc2c75278b2dd2f39 to your computer and use it in GitHub Desktop.
Save kursatsaim/e3643b71d16a104bc2c75278b2dd2f39 to your computer and use it in GitHub Desktop.
Trying to pick images using Uri but getting endless Security Exceptions.
public class SetBackgroundsAct extends AppCompatActivity {
private static final String SHARED_PREF_BACK = "imageURI";
private static final String KEY_SHARED_PREF_BACK = "imageURI";
private Button changeBackground;
private static final int RESULT_LOAD_IMAGE = 1;
private ImageView imageView;
private Uri imageUri;
private String path;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_backgrounds);
LoadSharePrefs();
changeBackground = findViewById(R.id.setBackgroundButton);
imageView = findViewById(R.id.backgroundImageview);
imageView.setImageURI(imageUri);
changeBackground.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent gallery = new Intent(Intent.ACTION_GET_CONTENT);
gallery.setType("image/*");
startActivityForResult(gallery, RESULT_LOAD_IMAGE);
}
});
};
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK){
imageUri = data.getData();
imageView.setImageURI(imageUri);
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_BACK,Context.MODE_PRIVATE);
SharedPreferences.Editor editor =sharedPreferences.edit();
path = imageUri.toString();
editor.putString(KEY_SHARED_PREF_BACK, path);
editor.apply();
}
}
private void LoadSharePrefs()
{
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_BACK,Context.MODE_PRIVATE);
String imagePath = sharedPreferences.getString(KEY_SHARED_PREF_BACK, "");
if (!imagePath.isEmpty()) {
imageUri = Uri.parse(imagePath);
}
}
}
//Also on the Manifest file I think Im asking the current permissions but Im not sure anymore so posting the related ones here as well
<uses-permission
android:name="android.permission.READ_MEDIA_IMAGES"
tools:ignore="SelectedPhotoAccess" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment