2015-07-11 30 views
0

我在SharedPreferences得到的NullPointerException獲得NullPointerException異常。這裏是我的代碼:在SharedPreferences

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
在wolverine.example.com.btp_farmer.MainActivity $ 1 $ 2.onClick(MainActivity.java:43)
在android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper的.java:137) (MainActi vity.java:43):SharedPreferences.Editor編輯= sharedpreferences.edit();

+0

凡sharedpreferences變量分配要在其上調用編輯方法....'sharedpreferences.edit()'。郵政的代碼太 – Psypher

+0

@ɥʇᴉɾuɐɹ,HTTP://justpaste.it/maam – adafrwefsefr

+1

把你的'MainActivity'代碼 – Rustam

回答

1

試試這個:

SharedPreferences.Editor editor = getSharedPreferences(NAME, 
Context.MODE_PRIVATE).edit(); 
editor.putString("name", "ABC"); 
editor.commit(); 
+0

感謝....它幫助 – adafrwefsefr

+0

大多數Welcomeeee –

1

你還沒有指定的sharedpreferences變量,因此其空。 首先分配sharedpreferences然後調用編輯()方法。

使用下面的代碼:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); 
SharedPreferences.Editor editor = sharedpreferences.edit();