使用SharedPreferences

时间:2017-04-02 17:45:05

标签: android sharedpreferences alertdialog

免责声明:我之前从未使用过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);
    }

我正在为AlertDialog

充气的XML文件
<?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 com.google.android.gms.internal.zzbnq@c77270d
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>

1 个答案:

答案 0 :(得分:0)

我能看到的至少一个错误是你在EditText内寻找onClick,但你正在查看内部活动,而不是在对话框视图中。因此,您将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);
    }

<强>更新

setPositiveButton,方法专家将字符串资源的id作为第一个参数,以便将其显示为标签,但是你传递的AlertDialog.BUTTON_POSITIVE首先没有任何意义,其次是崩溃你的应用程序。

因此,您可以在字符串资源上传递id,也可以只传递String,例如:

setPositiveButton("LABEL", ...