SharedPreference - 当Activity收到数据时,如何只烘烤一次

时间:2016-02-10 15:15:23

标签: android android-sharedpreferences

Activity 2收到Activity 1的{​​{1}}数据/值时,我怎么能只举杯一次? ,当我从其他活动收到相同的button时,我正试图解锁value。 以下是我的代码

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();
                      }
Activity 2Activity 1收到相同的值后,在我的代码中

, 它总是toast,因为它已经有value,有人可以帮助我,谢谢

1 个答案:

答案 0 :(得分:1)

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

这是一个简单而又简单的hacky答案。您的hasReceivedData变量必须在onConfigurationChanged上传递。我希望这有帮助!