1

I created an image gallery app.

My requirment:When I click on buttoncut in a activity(PhotosActivity.java), buttonpaste should become visible and it should remain visible when I go back to another activity(ImageGallery.java) so that I can use it for moving pictures to another folder.Also buttonpaste should become visible only when I click on buttoncut and it should be invisible when I open first activity (Imagegallery.java) for the first time.

What is happening: buttonpaste is already visible when I open first activity (Imagegallery.java) for the first time.Everything else is working fine.

I tried some code but its not working. How can I fix it ?

PhotosActivity.java:

    SharedPreferences preferences = getSharedPreferences("sample",Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putBoolean("Name",true);
    editor.apply();
    Intent intent = new Intent(PhotosActivity.this,ImageGallery.class);
    startActivity(intent);

ImageGallery.java

 final ImageButton buttonpaste = (ImageButton) findViewById(R.id.buttonpaste);
        buttonpaste.setVisibility(View.GONE);

        SharedPreferences preferences = getSharedPreferences("sample",Context.MODE_PRIVATE);
        boolean Namestr=(preferences.getBoolean("Name",true));
        if(Namestr){
            buttonpaste.setVisibility(View.VISIBLE);
        }
red viper
  • 152
  • 14
  • Use [StartActivityForResult](https://developer.android.com/training/basics/intents/result.html) . And do some research before directly posting question here . Thx . – ADM Jan 06 '18 at 15:22
  • Possible duplicate of [How to set a button visible from another activity in android](https://stackoverflow.com/questions/34951270/how-to-set-a-button-visible-from-another-activity-in-android) – ADM Jan 06 '18 at 15:23
  • try editor.commit? – Liar Jan 06 '18 at 17:16

1 Answers1

1

Take a look at this line:

boolean Namestr=(preferences.getBoolean("Name",true)); 

So if you did not write anything with key "Name" to SharedPreferences, the default value is true. This means that buttonPaste is visible by default. To change this, you have to set falseas default value:

boolean Namestr=(preferences.getBoolean("Name",false)); 
Bö macht Blau
  • 12,820
  • 5
  • 40
  • 61