我有一个应用程序,它以 TextView 的形式显示 MainActivity 中明星的总收入。如果应用程序是第一次运行,我想做的是输入 0。然后,当我完成一个关卡并赢得一些星星(如 currentScore + 50 = newScore)时,它将被重定向到带有 newScore textView 的 MainActivity。
这是我的 MainActivity,其中 TextView 显示分数
public class MainActivity extends Activity {
private static TextView txt_stars;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updateStars();
}
public void updateStars() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("Stars", 0);
editor.commit();
txt_stars = (TextView) findViewById(R.id.txtStars);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//the key is "Stars" don't forget to type it as you created the Sp
String stars = String.valueOf(sharedPreferences.getInt("Stars", 0));
txt_stars.setText(stars);
}
}
对于我读取当前分数然后添加 50 然后更新的 Activity
public void onClick(DialogInterface dialog, int whichButton) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Integer newstars = sharedPreferences.getInt("Stars", 0);
Integer totalStars = newstars + 50;
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("Stars", totalStars);
editor.commit();
//please help me improve my code here
Intent nextForm = new Intent(.MainActivity");
startActivity(nextForm);
}
SharedPreferences 也可以用于不同的 Activity 吗?就像我只是从 ActivityOne 中保存分数并可以在 ActivityTwo 中读取一样?
非常感谢!
最佳答案
嗯,你应该先阅读 the SharedPreferences documentation
,然后按照我的步骤使用 SharedPreferences
您的 UpdateStars()
方法应如下所示:
public class updateStars() {
txt_stars = (TextView) findViewById(R.id.txtStars);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//the key is "Stars" don't forget to type it as you created the Sp
String stars = String.valueOf(sharedPreferences.getInt("Stars", 0));
txt_stars.setText(stars);
}
每次你想保持用户 Stars
时,你都必须使用 putInt()
:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("Stars", YOUR_INT_VALUE); //Here you save the stars of the user
editor.commit();
关于java - 如何将分数保存到 SharedPreferences 然后更新它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35069461/