Reputation: 393
I am getting NullPointerException at SharedPreferences. Here is my code:
public void onClick(View v) {
phone = (EditText) findViewById(R.id.phoneno);
final String number = phone.getText().toString();
new AlertDialog.Builder(MainActivity.this)
.setMessage("Confirm your number:+91-" + number)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Phone, number);
editor.commit();
Intent intent = new Intent(MainActivity.this, Navigationfarmer.class);
startActivity(intent);
finish();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
Logcat:
java.lang.NullPointerException
at wolverine.example.com.btp_farmer.MainActivity$1$2.onClick(MainActivity.java:43)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage (AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137) (MainActivity.java:43):SharedPreferences.Editor editor = sharedpreferences.edit();
Upvotes: 0
Views: 65
Reputation: 247
Try this:
SharedPreferences.Editor editor = getSharedPreferences(NAME,
Context.MODE_PRIVATE).edit();
editor.putString("name", "ABC");
editor.commit();
Upvotes: 1
Reputation: 10829
You have not assigned the sharedpreferences variable hence its null. First assign the sharedpreferences then call the edit() method.
Use the below code:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedpreferences.edit();
Upvotes: 1