简体   繁体   English

重新加载SharedPreferences

[英]Reload SharedPreferences

I'm quite new to Android Prorgramming and have a problem understandig SharedPreferences. 我是Android Prorgramming的新手,在理解ig SharedPreferences时遇到问题。 I have a Main Activity and a Settings Activity. 我有一个主要活动和一个设置活动。 I want to be able to change a SharedPreference (here called firstWaitTime) in the Settings Activity and work with it in the Main Activity. 我希望能够在“设置”活动中更改SharedPreference(在此称为firstWaitTime),并在“主要活动”中使用它。 I can Set the new value in the settings, but in the Main Activity i only see the new value when i close and reopen the app. 我可以在设置中设置新值,但是在“主活动”中,只有在我关闭并重新打开应用程序后,才能看到新值。

I Think i would need a OnPrefrenceChanged Listender but i have no idea how to implement it... 我想我需要一个OnPrefrenceChanged Listender,但我不知道如何实现它。

The Main one looks like this: 主要的看起来像这样:

 public class MainActivity extends ActionBarActivity { //Radio Button private int stufe; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SharedPreferences settings = this.getSharedPreferences("settings", Context.MODE_PRIVATE); int firstWaitTime = settings.getInt("firstWaitTime", 12); int secondWaitTime = settings.getInt("secondWaitTime", 8); int thirdWaitTime = settings.getInt("thirdWaitTime", 6); //TEST final TextView test = (TextView) findViewById(R.id.test); test.setText("" + firstWaitTime); } 

The Settings Activity looks like this: 设置活动如下所示:

  @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); final SharedPreferences settings = this.getSharedPreferences("settings", MODE_PRIVATE); //BUTTON final EditText edit1 = (EditText) findViewById(R.id.edit1); Button save=(Button) findViewById(R.id.savebtn); save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //prefs = getSharedPreferences(prefName, MODE_PRIVATE); //SharedPreferences.Editor editor = prefs.edit(); SharedPreferences.Editor editor = settings.edit(); //---save the values in the EditText view to preferences--- editor.putInt("firstWaitTime", Integer.parseInt(edit1.getText().toString())); //---saves the values--- editor.commit(); Toast.makeText(getBaseContext(), "Saved", Toast.LENGTH_SHORT).show(); } }); } 

What is the best way to achieve this? 实现此目标的最佳方法是什么?

onCreate() will not be called as Android hasn't killed the Activity. 由于Android尚未杀死Activity,因此不会调用onCreate() Try putting your code in onResume() instead. 尝试将代码放入onResume() For more info read up on the Android Activity lifecycle . 有关更多信息,请阅读Android Activity生命周期

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM