请帮忙解决此问题我不会加载SharedPreferences
如果可以,请在回复中附上代码
它只是一个点击应用程序,我希望它保存点击的分数
每次从0加载时请帮我修复代码
import android.R.string;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
int counter;
Button add;
TextView display;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoadPrefs();
counter = 0;
add = (Button) findViewById(R.id.button1);
display = (TextView) findViewById(R.id.textView1);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("You Have " + counter);
SavePrefs("click", display.getText().toString());
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void LoadPrefs(){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("click", "You Have zero");
}
private void SavePrefs(String key, boolean value){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.putBoolean(key, value);
edit.commit();
}
private void SavePrefs(String key, String value){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.putString("click", "You Have zero");
edit.commit();
}
}
答案 0 :(得分:1)
您在致电counter
后将LoadPrefs
设为0。此外,您在加载首选项时未设置counter
。
为了保存实际的int
值(而不是显示字符串)并保持显示和保存的值同步,我会这样做:
public class MainActivity extends Activity {
int counter;
Button add;
TextView display;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add = (Button) findViewById(R.id.button1);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setCounter(counter + 1);
}
});
display = (TextView) findViewById(R.id.textView1);
loadCounter(); // must come after display is assigned
}
private void loadCounter(){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
setCounter(sp.getInt("click", 0));
}
private void setCounter(int value) {
counter = value;
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.put("click", counter);
edit.apply(); // apply() is better than commit()
display.setText("You Have " +
(counter > 0 ? String.valueOf(counter) : "zero");
}
}