0

我對Android開發非常陌生,目前正在研究一個應用程序,該應用程序應該按下按鈕時保存當前時間和日期,將其存儲到SharedPreferences,然後在按下不同按鈕時顯示字符串。我得到了它的工作,但今天做了一些修補,現在我得到了一個我無法解決的NullPointerException,即使在Google和Stackoverflow上花費了大約45分鐘後嘗試不同的代碼片段。誰能比我更好地告訴我我錯過了什麼?究竟是什麼導致了這個NullPointerException?

下面是相關代碼:

public class GetTimeStamp extends AppCompatActivity { 

    private String date; 
    public void setDate (View view){ 
     DateFormat df = new SimpleDateFormat("dd.MM.yyy 'om' HH:mm"); 
     date = df.format(Calendar.getInstance().getTime()); 
    } 
    public String getDate(){ 
     return date; 
    } 
     SharedPreferences prefs = this.getSharedPreferences("SharedPrefs",  Context.MODE_PRIVATE); 
    SharedPreferences.Editor editor = prefs.edit(); 
    protected void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_get_time_stamp); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fabSaveTimeStamp); 
     fab.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       setDate(view); 
       editor.putString("storedDate", date); 
       editor.commit(); 
       Toast.makeText(getBaseContext(), "blablabla", Toast.LENGTH_SHORT).show(); 
      } 
     }) 
FloatingActionButton fab3 = (FloatingActionButton) findViewById(R.id.fabShowTimeStamp); 
     fab3.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       //retrieve the date from SharedPreferences and store it to a local String 
       String retrievedDate = prefs.getString("storedDate", null); 
       if (retrievedDate!=null){ 
        AlertDialog alertDialog = new AlertDialog.Builder(GetTimeStamp.this).create(); //Read Update 
        alertDialog.setTitle(""); 
        alertDialog.setMessage("somemessage" + retrievedDate); 
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int which) { 
         } 
        }); 
        alertDialog.show(); 
       }else { 
        //create an alert dialog explaining to the user that no date has been saved yet 
        AlertDialog alertDialog = new AlertDialog.Builder(GetTimeStamp.this).create(); //Read Update 
        alertDialog.setTitle("Error"); 
        alertDialog.setMessage("errorexplanation"); 
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int which) { 
         } 
        }); 
        alertDialog.show(); 
       } 
      } 
     }); 

這裏是錯誤:

02-08 22:49:36.142 19735-19735/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41ed7ce0) 
02-08 22:49:36.152 19735-19735/? E/AndroidRuntime: FATAL EXCEPTION: main 
    Process: com.example.user.appname, PID: 19735 
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.user.appname/com.example.user.appname.GetTimeStamp}: java.lang.NullPointerException 
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2131) 
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2264) 
     at android.app.ActivityThread.access$800(ActivityThread.java:144) 
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205) 
     at android.os.Handler.dispatchMessage(Handler.java:102) 
     at android.os.Looper.loop(Looper.java:136) 
     at android.app.ActivityThread.main(ActivityThread.java:5139) 
     at java.lang.reflect.Method.invokeNative(Native Method) 
     at java.lang.reflect.Method.invoke(Method.java:515) 
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796) 
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612) 
     at dalvik.system.NativeStart.main(Native Method) 
    Caused by: java.lang.NullPointerException 
     at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:173) 
     at com.example.user.appname.GetTimeStamp.<init>(GetTimeStamp.java:36) 
     at java.lang.Class.newInstanceImpl(Native Method) 
     at java.lang.Class.newInstance(Class.java:1208) 
     at android.app.Instrumentation.newActivity(Instrumentation.java:1061) 
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2122) 
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2264)  
     at android.app.ActivityThread.access$800(ActivityThread.java:144)  
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)  
     at android.os.Handler.dispatchMessage(Handler.java:102)  
     at android.os.Looper.loop(Looper.java:136)  
     at android.app.ActivityThread.main(ActivityThread.java:5139)  
     at java.lang.reflect.Method.invokeNative(Native Method)  
     at java.lang.reflect.Method.invoke(Method.java:515)  
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)  
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)  
     at dalvik.system.NativeStart.main(Native Method)  
+0

@HrundiVBakshi即重複如'SharedPreferences首選項= this.getSharedPreferences( 「SharedPrefs」,Context.MODE_PRIVATE)的相當差勁的選擇;'看起來你正在分配一個有效的值。 –

+0

@GeorgeMulligan你在那裏! – njzk2

+0

@ njzk2我必須一直使用錯誤的搜索關鍵字或錯過了那一個。謝謝你的鏈接! – Wyhx

回答

1

您正在嘗試初始化下面的類領域你被允許之前:

SharedPreferences prefs = this.getSharedPreferences("SharedPrefs",  Context.MODE_PRIVATE); 

只聲明該字段:

SharedPreferences prefs; 

,然後分配在你onCreate()方法:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    prefs = getSharedPreferences("SharedPrefs", Context.MODE_PRIVATE); 
    ... 
} 
+0

@ cricket_007當然可以。 –

+0

@ cricket_007也許,我會說這是一個好習慣,因爲在這種情況下「這個」確實不是必要的。 –

+0

這加上我發現的編輯器的一些其他代碼解決了它,非常感謝! – Wyhx