2017-04-02 70 views
-1

免責聲明:我以前從未使用過SharedPreferences,並且第一次嘗試的時間並不順利。使用SharedPreferences時的運行時異常

我想爲應用程序保存一個不變的值。我認爲SharedPreferences是要走的路,因爲我只想向用戶索取一次這個值,那是用戶第一次打開應用程序的時候。

這裏是我的代碼

SharedPreferences runCheck = getApplicationContext().getSharedPreferences("hasRunBefore", 0); //load the preferences 
    Boolean hasRun = runCheck.getBoolean("hasRun", false); //see if it's run before, default no 
    if (!hasRun) { 
//This code runs the first time the app is opened 
     SharedPreferences settings = getSharedPreferences("hasRunBefore", 0); 
     SharedPreferences.Editor edit = settings.edit(); 
     edit.putBoolean("hasRun", true); //set to has run 

     AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 
     LayoutInflater inflater = getLayoutInflater(); 
     builder.setView(inflater.inflate(R.layout.alertdialog,null)) 
     .setPositiveButton(AlertDialog.BUTTON_POSITIVE, new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialog, int which) { 
       EditText editText = (EditText)findViewById(R.id.alert_dialog_editText); 
       if(editText.getText().toString() != null) { 
        regNum = editText.getText().toString(); 
       } 
      } 
     }); 
     edit.putString("registerNumber",regNum); 
     builder.show(); 
     TextView textView = (TextView)findViewById(R.id.regNum_textView); 
     textView.setText(regNum); 
     edit.commit(); //apply 
    } 
    else 
    { 
     //code if the app HAS run before 
     TextView textView = (TextView)findViewById(R.id.regNum_textView); 
     textView.setText(regNum); 
    } 

而且,我膨脹的XML文件中的AlertDialog

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:id="@+id/alertDialog" 
> 

<TextView 
    android:id="@+id/alert_dialog_textview" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Enter Your Register Number" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="37dp" /> 

<EditText 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/alert_dialog_editText" 
    android:layout_below="@+id/alert_dialog_textview" 
    android:layout_centerHorizontal="true" /> 

</RelativeLayout> 

任何人都可以友好地告訴我什麼,我做錯了什麼? TIA!

編輯:用Logcat更新。

<code> 04-02 23:32:15.574 12826-12826/? I/art: Late-enabling -Xcheck:jni 
    04-02 23:32:15.609 12826-12826/teamfour.bluetoothtracker D/TidaProvider: TidaProvider() 
04-02 23:32:15.657 12826-12826/teamfour.bluetoothtracker W/System: ClassLoader referenced unknown path: /data/app/teamfour.bluetoothtracker-2/lib/arm64 
04-02 23:32:15.688 12826-12843/teamfour.bluetoothtracker W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found. 
04-02 23:32:15.696 12826-12843/teamfour.bluetoothtracker W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found. 
04-02 23:32:15.729 12826-12826/teamfour.bluetoothtracker I/DynamiteModule: Considering local module com.google.android.gms.flags:2 and remote module com.google.android.gms.flags:0 
04-02 23:32:15.729 12826-12826/teamfour.bluetoothtracker I/DynamiteModule: Selected local version of com.google.android.gms.flags 
04-02 23:32:15.739 12826-12826/teamfour.bluetoothtracker W/DynamiteModule: Local module descriptor class for com.google.android.gms.crash not found. 
04-02 23:32:15.742 12826-12826/teamfour.bluetoothtracker I/DynamiteModule: Considering local module com.google.android.gms.crash:0 and remote module com.google.android.gms.crash:4 
04-02 23:32:15.742 12826-12826/teamfour.bluetoothtracker I/DynamiteModule: Selected remote version of com.google.android.gms.crash, version >= 4 
04-02 23:32:15.751 12826-12826/teamfour.bluetoothtracker W/System: ClassLoader referenced unknown path: /data/user/0/com.google.android.gms/app_chimera/m/0000000f/n/arm64-v8a 
04-02 23:32:15.785 12826-12826/teamfour.bluetoothtracker I/FirebaseCrashApiImpl: FirebaseCrashApiImpl created by ClassLoader p[DexPathList[[zip file "/data/data/com.google.android.gms/app_chimera/m/0000000f/DynamiteModulesC_GmsCore_prodmnc_xxhdpi_release.apk"],nativeLibraryDirectories=[/data/user/0/com.google.android.gms/app_chimera/m/0000000f/n/arm64-v8a, /vendor/lib64, /system/lib64]]] 
04-02 23:32:15.806 12826-12826/teamfour.bluetoothtracker I/DynamiteModule: Considering local module com.google.android.gms.flags:2 and remote module com.google.android.gms.flags:0 
04-02 23:32:15.806 12826-12826/teamfour.bluetoothtracker I/DynamiteModule: Selected local version of com.google.android.gms.flags 
04-02 23:32:15.823 12826-12826/teamfour.bluetoothtracker W/DynamiteModule: Local module descriptor class for com.google.android.gms.crash not found. 
04-02 23:32:15.857 12826-12826/teamfour.bluetoothtracker I/FA: App measurement is starting up, version: 10298 
04-02 23:32:15.857 12826-12826/teamfour.bluetoothtracker I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE 
04-02 23:32:15.862 12826-12826/teamfour.bluetoothtracker V/FA: Collection enabled 
04-02 23:32:15.862 12826-12826/teamfour.bluetoothtracker V/FA: App package, google app id: teamfour.bluetoothtracker, 1:269251234897:android:6720288a2e1342a0 
04-02 23:32:15.862 12826-12826/teamfour.bluetoothtracker I/FA: To enable faster debug mode event logging run:  adb shell setprop debug.firebase.analytics.app teamfour.bluetoothtracker 
04-02 23:32:15.862 12826-12826/teamfour.bluetoothtracker D/FA: Debug-level message logging enabled 
04-02 23:32:15.868 12826-12826/teamfour.bluetoothtracker V/FA: Registered activity lifecycle callback 
04-02 23:32:15.869 12826-12826/teamfour.bluetoothtracker I/FirebaseCrash: FirebaseCrash reporting initialized [email protected] 
04-02 23:32:15.870 12826-12826/teamfour.bluetoothtracker I/FirebaseInitProvider: FirebaseApp initialization successful 
04-02 23:32:15.878 12826-12864/teamfour.bluetoothtracker V/FA: Using measurement service 
04-02 23:32:15.878 12826-12864/teamfour.bluetoothtracker V/FA: Connecting to remote service 
04-02 23:32:15.920 12826-12826/teamfour.bluetoothtracker W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable 
04-02 23:32:15.927 12826-12826/teamfour.bluetoothtracker V/FA: onActivityCreated 
04-02 23:32:15.986 12826-12826/teamfour.bluetoothtracker W/ResourceType: No known package when getting value for resource number 0xffffffff 
04-02 23:32:15.990 12826-12826/teamfour.bluetoothtracker D/AndroidRuntime: Shutting down VM 
04-02 23:32:15.996 12826-12826/teamfour.bluetoothtracker E/UncaughtException: java.lang.RuntimeException: Unable to start activity ComponentInfo{teamfour.bluetoothtracker/teamfour.bluetoothtracker.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0xffffffff 
                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2423) 
                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483) 
                        at android.app.ActivityThread.access$900(ActivityThread.java:153) 
                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349) 
                        at android.os.Handler.dispatchMessage(Handler.java:102) 
                        at android.os.Looper.loop(Looper.java:148) 
                        at android.app.ActivityThread.main(ActivityThread.java:5441) 
                        at java.lang.reflect.Method.invoke(Native Method) 
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738) 
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628) 
                       Caused by: android.content.res.Resources$NotFoundException: String resource ID #0xffffffff 
                        at android.content.res.Resources.getText(Resources.java:328) 
                        at android.content.res.MiuiResources.getText(MiuiResources.java:123) 
                        at android.content.Context.getText(Context.java:405) 
                        at android.support.v7.app.AlertDialog$Builder.setPositiveButton(AlertDialog.java:451) 
                        at teamfour.bluetoothtracker.MainActivity.onCreate(MainActivity.java:67) 
                        at android.app.Activity.performCreate(Activity.java:6303) 
                        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108) 
                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376) 
                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)  
                        at android.app.ActivityThread.access$900(ActivityThread.java:153)  
                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)  
                        at android.os.Handler.dispatchMessage(Handler.java:102)  
                        at android.os.Looper.loop(Looper.java:148)  
                        at android.app.ActivityThread.main(ActivityThread.java:5441)  
                        at java.lang.reflect.Method.invoke(Native Method)  
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)  
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)  
04-02 23:32:16.002 12826-12864/teamfour.bluetoothtracker I/DynamiteModule: Considering local module com.google.android.gms.tagmanager:9 and remote module com.google.android.gms.tagmanager:9 
04-02 23:32:16.002 12826-12864/teamfour.bluetoothtracker I/DynamiteModule: Selected remote version of com.google.android.gms.tagmanager, version >= 9  
[ 04-02 23:32:16.003 12883:12883 I/   ]       ARTPROXY OFFSET: method_entry_offset = 48 
[ 04-02 23:32:16.003 12883:12883 I/   ] 
ARTPROXY OFFSET: method_interpreter_entry_offset = 32 
[ 04-02 23:32:16.003 12883:12883 I/   ] 
ARTPROXY OFFSET: managed_stack_size = 24 
[ 04-02 23:32:16.003 12883:12883 I/   ] 
ARTPROXY OFFSET: thread_deliver_exception_entry_offset = 1088 
[ 04-02 23:32:16.003 12883:12883 I/   ] 
ARTPROXY OFFSET: thread_exception_offset = 136 
[ 04-02 23:32:16.003 12883:12883 I/   ] 
ARTPROXY OFFSET: method_code_size_offset = 4 
04-02 23:32:16.031 12826-12864/teamfour.bluetoothtracker W/GoogleTagManager: No container asset found in /assets/containers. Checking top level /assets directory for container assets. 
04-02 23:32:16.045 12826-12864/teamfour.bluetoothtracker W/GoogleTagManager: Tag Manager's event handler WILL NOT be installed (no container loaded) 
04-02 23:32:16.045 12826-12864/teamfour.bluetoothtracker I/GoogleTagManager: Tag Manager initilization took 31ms 
04-02 23:32:16.060 12826-12864/teamfour.bluetoothtracker V/FA: Using measurement service 
04-02 23:32:16.060 12826-12864/teamfour.bluetoothtracker V/FA: Connection attempt already in progress 
04-02 23:32:16.239 12826-12826/? E/AndroidRuntime: FATAL EXCEPTION: main 
                Process: teamfour.bluetoothtracker, PID: 12826 
                java.lang.RuntimeException: Unable to start activity ComponentInfo{teamfour.bluetoothtracker/teamfour.bluetoothtracker.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0xffffffff 
                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2423) 
                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483) 
                 at android.app.ActivityThread.access$900(ActivityThread.java:153) 
                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349) 
                 at android.os.Handler.dispatchMessage(Handler.java:102) 
                 at android.os.Looper.loop(Looper.java:148) 
                 at android.app.ActivityThread.main(ActivityThread.java:5441) 
                 at java.lang.reflect.Method.invoke(Native Method) 
                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738) 
                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628) 
                Caused by: android.content.res.Resources$NotFoundException: String resource ID #0xffffffff 
                 at android.content.res.Resources.getText(Resources.java:328) 
                 at android.content.res.MiuiResources.getText(MiuiResources.java:123) 
                 at android.content.Context.getText(Context.java:405) 
                 at android.support.v7.app.AlertDialog$Builder.setPositiveButton(AlertDialog.java:451) 
                 at teamfour.bluetoothtracker.MainActivity.onCreate(MainActivity.java:67) 
                 at android.app.Activity.performCreate(Activity.java:6303) 
                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108) 
                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376) 
                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)  
                 at android.app.ActivityThread.access$900(ActivityThread.java:153)  
                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)  
                 at android.os.Handler.dispatchMessage(Handler.java:102)  
                 at android.os.Looper.loop(Looper.java:148)  
                 at android.app.ActivityThread.main(ActivityThread.java:5441)  
                 at java.lang.reflect.Method.invoke(Native Method)  
                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)  
                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)  
04-02 23:32:16.243 12826-12826/? I/Process: Sending signal. PID: 12826 SIG: 9 </code> 
+2

請出示從logcat的堆棧跟蹤ID。 – Divers

+0

嗨,我想,但logcat似乎並沒有停止!它不斷用新的文字氾濫。 – thatrockbottomprogrammer

+0

點擊它並滾動到堆棧跟蹤位置。 – Divers

回答

0

至少1個錯誤,我可以看到的是,你正在尋找EditTextonClick,但你正在尋找的活動裏面,沒有對話的視圖中。結果你將有editText等於null。也不需要爲SharedPreferences設置2個變量。

SharedPreferences sharedPreferences = getSharedPreferences("hasRunBefore", 0); 
    boolean hasRun = sharedPreferences.getBoolean("hasRun", false); 
    if (!hasRun) { 
     SharedPreferences.Editor edit = sharedPreferences.edit(); 
     edit.putBoolean("hasRun", true); 

     AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 
     final View dialogView = getLayoutInflater().inflate(R.layout.alertdialog, null); 
     builder.setView(dialogView) 
       .setPositiveButton(AlertDialog.BUTTON_POSITIVE, new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int which) { 
         //Here important change, before you had NPE 
         EditText editText = (EditText) dialogView.findViewById(R.id.alert_dialog_editText); 
         if (editText.getText().toString() != null) { 
          regNum = editText.getText().toString(); 
         } 
        } 
       }); 
     edit.putString("registerNumber", regNum); 
     builder.show(); 
     TextView textView = (TextView) findViewById(R.id.regNum_textView); 
     textView.setText(regNum); 
     edit.commit(); //apply 
    } else { 
     //code if the app HAS run before 
     TextView textView = (TextView) findViewById(R.id.regNum_textView); 
     textView.setText(regNum); 
    } 

UPDATE:

setPositiveButton,字符串資源作爲以顯示它作爲標籤的第一個參數的方法的專家號,但你是路過AlertDialog.BUTTON_POSITIVE這首先是沒有任何意義,第二它崩潰你的應用程序。

所以,你可以傳遞字符串資源或只是字符串,例如:

setPositiveButton("LABEL", ...

+0

是的,確實如此。我刪除了額外的變量,並將視圖引用到對話框中的一個。我用logcat更新了我的答案! – thatrockbottomprogrammer

+0

如果我使用String替換AlertDialog.BUTTON_POSITIVE,代碼將運行。沒有空指針異常。 – thatrockbottomprogrammer

+0

但是,我無法輸入EditText字段。光標閃爍,但我無法在該字段中輸入任何內容。 – thatrockbottomprogrammer