Search code examples
androidandroid-sharedpreferences

SharedPreference - How to toast only once when Activity recieves the data


how can i toast only once when my Activity 2 receive's data / value from my Activity 1 ? , I am trying to unlock a button when he receive the same value from the other activity. Below is my code

SharedPreferences sharedPreferences = getSharedPreferences("UnlockPreTestFour", Context.MODE_PRIVATE);
             final int scorePre = sharedPreferences.getInt("ScoreFour", 0);
               if(scorePre !=0){
            Toast.makeText(grade_four.this, "Button Unlock!", Toast.LENGTH_SHORT).show();
                      }

in my code after the Activity 2 receives the same value from Activity 1, it always toast because it already has a value , can someone help me, thanks


Solution

  • Boolean hasReceivedData = false
    
    SharedPreferences sharedPreferences = getSharedPreferences("UnlockPreTestFour", Context.MODE_PRIVATE);
             final int scorePre = sharedPreferences.getInt("ScoreFour", 0);
    
               //check to see if you have received the data
               if(scorePre !=0 && hasReceivedDate == false){
                    Toast.makeText(grade_four.this, "Button Unlock!", Toast.LENGTH_SHORT).show();
    
                    //set variable to ensure data is only loaded once
                    hasReceivedData = true;
                 }
    

    Here is a simple and kind of hacky answer. Your hasReceivedData variable will have to be passed onConfigurationChanged. I hope this helps!