Getting null pointer exception in shared preferences android
My code is something like this
// To save my form data
private final OnClickListener mFinishListener = new OnClickListener() {
public void onClick(View v) {
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putString("txtName",mName.getText().toString());
servState = 1;
editor.putInt("AppState", servState);
editor.commit();
}
// To Retrieve my form data
protected void onResume() {
super.onResume();
开发者_Go百科 SharedPreferences prefs = getPreferences(0);
int restoreServState = prefs.getInt("AppState", 0);
if(restoreServState == 0){
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.btnFinish);
button.setOnClickListener(mFinishListener);
}
else {
setContentView(R.layout.pwd);
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);
if (selectionStart != -1 && selectionEnd != -1) {
//mSaved.setSelection(selectionStart, selectionEnd);
}
}
}
I get NullPointerException at the point of saving the data in the OnClick event in the above code. The exact line I got problem is
editor.putString("txtName",mName.getText().toString());
Please suggest what is the wrong here? Do I need to change anything in the manifest file to use shared preferences?
you may have two problem for getting this error
Actually when Activity starts it call onCreate() first
onResume() is called after activity is created so may be your control may not getting the resource
1)so had setContentView(R.layout.main) in onCreate?
2)had you initialize EditText mName=(EditText) findViewById(R.id.label);?
check this things, may works
精彩评论