如何在android中的另一个活动中检查共享首选项是否已更改?

时间:2013-12-20 05:17:19

标签: android sharedpreferences

大家好我在我的应用程序中使用共享首选项。我正在使用动作栏。在这个动作中,我有定制的微调器。我在主活动中的onNavigationItemSelected中将值存储到共享首选项中。这意味着标签为零。说谎。

      main_prefs = getSharedPreferences("final_city_id", MODE_PRIVATE);
               // detail is sharedpreference name
             SharedPreferences.Editor editor = main_prefs.edit();

            // to remove paricular value from detail 

            String spusername = main_prefs.getString("changed_city_id", "novalue");

            if(spusername!= null && !spusername.equals(""))
            {   
                System.out.println("inside if condition........");
                Log.e("Spusername != null","-->"+spusername);
                editor.remove("changed_city_id"); 
                Log.e("value removed","-->"+spusername);
                editor.putString("changed_city_id",spinner_city_id);
                editor.commit();
                String spusername1 = main_prefs.getString("changed_city_id", "novalue");

               System.out.println("spusername1```````````"+spusername1);

            }
           else
           {
               System.out.println("inside else condition........");
               editor.putString("changed_city_id",spinner_city_id);
               editor.commit();
               String spusername2 = main_prefs.getString("changed_city_id", "novalue");

               System.out.println("spusername2```````````"+spusername2);
           }

现在我转到标签2或3,然后再选择微调器。我的价值观必须改变。我的共享偏好值也是变化的。现在我想在我的2选项卡和第三个选项卡中检查共享首选项是否已更改。这意味着另一项活动。但是我的微调器的onNavigationItemSelected方法在我的零选项卡中。所以我使用的是OnSharedPreferenceChangeListener。在某些链接中建议这一个。因为当共享首选项更改时,会自动触发此覆盖方法。我搜索了很多东西并且厌倦了。但我无法明确表达。任何人都能清楚我吗?提前谢谢。

2 个答案:

答案 0 :(得分:1)

试试如下:

   public class myClass implements OnSharedPreferenceChangeListener
 {
  private SharedPreferences settings;

settings = PreferenceManager.getDefaultSharedPreferences(this);
settings.registerOnSharedPreferenceChangeListener(this);

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
   // Process it here
}
}

答案 1 :(得分:0)

prefs.registerOnSharedPreferenceChangeListener(
  new SharedPreferences.OnSharedPreferenceChangeListener() {
  public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
    // Implementation
  }
});

而不是

// Use instance field for listener
// It will not be gc'd as long as this instance is kept referenced
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
  public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
    // Implementation
  }
};
prefs.registerOnSharedPreferenceChangeListener(listener);