我正在尝试使用两个 SharedPreferences,第一个有效,但第二个无效
这是我的 Java 代码
public class JogoActivity extends AppCompatActivity implements View.OnClickListener {
//OTHERS VARIABLES
public TextView txtViewResult,txtCoins, txtTentativas;
private static final String PREF_NAME = "JogoActivityPreferences";
int resulFinalCache,coinsFinalCache;
int count1, count2 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Configuration config = getResources().getConfiguration();
//methods...
//MY PROBLEMS START HERE
txtCoins = (TextView) findViewById(R.id.txtCoins);
txtViewResult = (TextView) findViewById(R.id.textViewResultado);
SharedPreferences sp1 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
count1 = sp1.getInt("count1", 0);
txtViewResult.setText(String.valueOf(formatter.format(count1).toString()));//THIS IS WORKING
SharedPreferences sp2 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
count2 = sp2.getInt("count2", 0);
txtCoins.setText(String.valueOf(formatter.format(count2).toString()));////THIS ISN'T
}
//Creating methods...
@Override
protected void onStop(){
super.onStop();
SharedPreferences sp1 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);//THIS IS WORKING
count1 = sp1.getInt("count1", 0);
SharedPreferences.Editor editor = sp1.edit();
editor.putInt("count1", resulFinalCache);
editor.commit();
SharedPreferences sp2 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);//THIS ISN'T
count2 = sp2.getInt("count2", 0);
editor = sp1.edit();
editor.putInt("count2", coinsFinalCache);
editor.commit();
}
@Override
public void onDestroy() {
super.onDestroy();
SharedPreferences sp1= getSharedPreferences(PREF_NAME, MODE_PRIVATE);//THIS IS WORKING
SharedPreferences.Editor editor = sp1.edit();
editor.putInt("count1", resulFinalCache);
editor.commit();
SharedPreferences sp2= getSharedPreferences(PREF_NAME, MODE_PRIVATE);//THIS ISN'T
editor = sp2.edit();
editor.putInt("count2", coinsFinalCache);
editor.commit();
}
每次我启动应用程序时,我都会使用,关闭应用程序并再次打开,TextView txtViewResult 工作正常,但 txtCoins 不是
我尝试只使用 getPreferences 而不是 getSharedPreferences,但它也不起作用
我尝试创建其他编辑器,但它也不起作用
我是不是做错了什么?
非常感谢!
最佳答案
无需调用 getsharedpreferences 两次。
只需调用一次,它应该可以正常工作。
例如,您的 onstop 将是
SharedPreferences sp1 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);//THIS IS WORKING
count1 = sp1.getInt("count1", 0);
SharedPreferences.Editor editor = sp1.edit();
editor.putInt("count1", resulFinalCache);
count2 = sp1.getInt("count2", 0);
editor.putInt("count2", coinsFinalCache);
editor.commit();
关于java - 两个 SharedPreferences 不工作-java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35925528/