我正在尝试保存到共享首选项。我希望能够从共享首选项加载,但是当我保存或加载时,我的应用程序崩溃了。
我还希望能够在我的应用启动时获得处理程序/可运行的简历。我怎么能这样做?
这是我的代码:
public class MainActivity extends ActionBarActivity {
public void save(){
Editor editor = pref.edit();
editor.putInt("countertest", counter);
editor.commit();
}//end of save
public void read(){
counter = pref.getInt("countertest", counter);
}//end of read
Handler testHandler = new Handler();
int counter;
TextView testView;
Button testButton;
Runnable Runnable0;
SharedPreferences pref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testView = (TextView) findViewById(R.id.testView);
testButton = (Button) this.findViewById(R.id.testButton);
// read();
testView.setText(Integer.toString(counter));
}
@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;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
//read();
final Runnable Runnable0 = new Runnable() {
@Override
public void run() {
counter += 1;
testView.setText(Integer.toString(counter));
testHandler.postDelayed(this, 1000);
// save();
}// end of if
};
/* button click */
testButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
/* Start runnable */
testButton.setEnabled(false);
counter -= 5;
//save();
testView.setText(Integer.toString(counter));
testHandler.post(Runnable0);
}// end of onClick
});// end of blingButton onClickListener
super.onResume();
}//end of onResume
@Override
protected void onPause() {
//save();
testHandler.removeCallbacks(Runnable0);
super.onPause();
}//end of onPause
}
答案 0 :(得分:4)
您尚未初始化pref
对象。你刚宣布它。所以你需要在onCreate()
上通过
pref = getSharedPreferences("MySP", 0);
OR
pref = PreferenceManager.getDefaultSharedPreferences(this);