Android: URI-адрес sharedPreferences возвращает ноль при запуске приложения - PullRequest
0 голосов
/ 18 марта 2020

Идея состоит в том, чтобы сохранить изображение из внутреннего хранилища в общих настройках и загрузить в просмотр изображений. Когда приложение перезапустится, мне нужен просмотр изображений, чтобы показать сохраненное изображение. Я также оцениваю разрешения для URI.

Я пытаюсь что-то подобное.

 static int PICK_IMAGE_REQUEST=1;
 static SharedPreferences preferences;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        PROFILE_IMG = (ImageView)findViewById(R.id.profile_image);
        PHOTObutton = (Button)findViewById(R.id.photo_btn);


       // Get from the SharedPreferences
       preferences = PreferenceManager.getDefaultSharedPreferences(this);

        String mImageUri = preferences.getString("image", null);
        PROFILE_IMG.setImageURI(Uri.parse(mImageUri));

        //open gallery-- select profile photo
        PHOTObutton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                openGallery();
            }
        });

    }
    private void openGallery() {

        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
        } else {
            intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
        }
        intent.setType("image/*");
        startActivityForResult(Intent.createChooser(intent, "Select Picture"),
                PICK_IMAGE_REQUEST);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        // Check which request we're responding to
        if (requestCode == PICK_IMAGE_REQUEST) {
            // Make sure the request was successful
            if (resultCode == RESULT_OK) {
                // The user picked a image.
                // The Intent's data Uri identifies which item was selected.
                if (data != null) {

                    // This is the key line item, URI specifies the name of the data
                   imageUri = data.getData();

                    // Removes Uri Permission so that when you restart the device, it will be allowed to reload.
                    this.grantUriPermission(this.getPackageName(), imageUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    final int takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION;
                    this.getContentResolver().takePersistableUriPermission(imageUri, takeFlags);

                    // Saves image URI as string to Default Shared Preferences
                     preferences =
                            PreferenceManager.getDefaultSharedPreferences(this);
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putString("image", String.valueOf(imageUri));
                    editor.commit();

                    // Sets the ImageView with the Image URI
                    PROFILE_IMG.setImageURI(imageUri);
                    PROFILE_IMG.invalidate();
                }
            }
        }
    }


И я получаю следующее, когда пытаюсь начать действие.

java.lang.RuntimeException: Unable to start activity ComponentInfo{firebasesearch.activity_profile}: java.lang.NullPointerException: uriString

Как мне решить эту проблему?

PS: я попытался написать сообщение stackoverflow об исключении NullPointerException. Это не помогло мне. поэтому, пожалуйста, не упоминайте об этом.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...