简体   繁体   English

共享偏好不起作用,默认值

[英]Sharedpreferences aren't working, default values

My app has a lot of checkboxes in it, a spinner, edittext and a button. 我的应用程序中有很多复选框,一个微调器,一个edittext和一个按钮。 When I choose an item from the spinner and then enter a certain value and hit a button, a certain checkbox text changes. 当我从微调器中选择一个项目然后输入某个值并点击一个按钮时,某个复选框文本会发生变化。 Now I added shared preferences and I have two problems. 现在我添加了共享首选项,我有两个问题。

First problem is that when I try to use sharedpreferences the app crashes (as soon as I start the activity containing these sharedpreferences). 第一个问题是,当我尝试使用共享偏好时,应用程序崩溃(一旦我启动包含这些共享偏好的活动)。

private String getItemQuantity(String key){
    SharedPreferences itemQuantitySP = getApplicationContext().getSharedPreferences("bifrostPrefs", android.content.Context.MODE_PRIVATE);
    String sp1 = "sp1";
    return itemQuantitySP.getString(key, sp1);
}
private void saveItemQuantity(String key, String value){
    SharedPreferences itemQuantitySP = getApplicationContext().getSharedPreferences("bifrostPrefs", android.content.Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = itemQuantitySP.edit();
    editor.putString(key, value);
    editor.commit();
}

Saving sharedpreferences: 保存共享偏好:

if (Integer.parseInt(quantityEditText.getText().toString()) == 250)
{
    cb4.setText("Elaborate Totem (" + item1 + "/250)");
    saveItemQuantity("cb4", cb4.getText().toString());
    cb4.setChecked(true);
}
... //REST OF THE CODE

Getting sharedpreferences: 获得共享偏好:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bifrost);

    getItemQuantity("cb4");
... //REST OF THE CODE

Second problem is that I have a lot of checkboxes and setting default value for every single one of them would be very time consuming. 第二个问题是我有很多复选框,为每一个复选框设置默认值会非常耗时。 So is there a way to simply read the default value from XML? 那么有没有办法简单地从XML中读取默认值? As you can see, for now, I created a new variable called sp1 and set it as the default value, but ofcourse I want to get rid of that. 正如你所看到的,现在,我创建了一个名为sp1的新变量并将其设置为默认值,但当然我想摆脱它。

Logcat file: Logcat文件:

06-27 16:31:44.782: E/AndroidRuntime(13139): FATAL EXCEPTION: main
06-27 16:31:44.782: E/AndroidRuntime(13139): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.matthewstudios.gw2legendary/com.example.gw2legendary.Bifrost}: java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String
06-27 16:31:44.782: E/AndroidRuntime(13139):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
06-27 16:31:44.782: E/AndroidRuntime(13139):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-27 16:31:44.782: E/AndroidRuntime(13139):    at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-27 16:31:44.782: E/AndroidRuntime(13139):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-27 16:31:44.782: E/AndroidRuntime(13139):    at android.os.Handler.dispatchMessage(Handler.java:99)
06-27 16:31:44.782: E/AndroidRuntime(13139):    at android.os.Looper.loop(Looper.java:137)
06-27 16:31:44.782: E/AndroidRuntime(13139):    at android.app.ActivityThread.main(ActivityThread.java:5041)
06-27 16:31:44.782: E/AndroidRuntime(13139):    at java.lang.reflect.Method.invokeNative(Native Method)
06-27 16:31:44.782: E/AndroidRuntime(13139):    at java.lang.reflect.Method.invoke(Method.java:511)
06-27 16:31:44.782: E/AndroidRuntime(13139):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-27 16:31:44.782: E/AndroidRuntime(13139):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-27 16:31:44.782: E/AndroidRuntime(13139):    at dalvik.system.NativeStart.main(Native Method)
06-27 16:31:44.782: E/AndroidRuntime(13139): Caused by: java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String
06-27 16:31:44.782: E/AndroidRuntime(13139):    at android.app.SharedPreferencesImpl.getString(SharedPreferencesImpl.java:224)
06-27 16:31:44.782: E/AndroidRuntime(13139):    at com.example.gw2legendary.Bifrost.getItemQuantity(Bifrost.java:849)
06-27 16:31:44.782: E/AndroidRuntime(13139):    at com.example.gw2legendary.Bifrost.onCreate(Bifrost.java:152)
06-27 16:31:44.782: E/AndroidRuntime(13139):    at android.app.Activity.performCreate(Activity.java:5104)
06-27 16:31:44.782: E/AndroidRuntime(13139):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
06-27 16:31:44.782: E/AndroidRuntime(13139):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
06-27 16:31:44.782: E/AndroidRuntime(13139):    ... 11 more
06-27 16:31:49.391: E/fb4a(:<default>):MmsConfig(13225): MmsConfig.loadMmsSettings mms_config.xml missing uaProfUrl setting

Part of the code: 部分代码:

public void submitQuantityButton (View v){
    final Spinner sItems = (Spinner)findViewById(R.id.spinner1);
    final Context context = this;
    final CheckBox cb4 = (CheckBox) findViewById(R.id.checkBox4);
    final CheckBox cb5 = (CheckBox) findViewById(R.id.checkBox5);
    final CheckBox cb6 = (CheckBox) findViewById(R.id.checkBox6);
    final CheckBox cb7 = (CheckBox) findViewById(R.id.checkBox7);
    final CheckBox cb9 = (CheckBox) findViewById(R.id.checkBox9);
    final CheckBox cb10 = (CheckBox) findViewById(R.id.checkBox10);
    final CheckBox cb11 = (CheckBox) findViewById(R.id.checkBox11);
    final CheckBox cb12 = (CheckBox) findViewById(R.id.checkBox12);
    final CheckBox cb13 = (CheckBox) findViewById(R.id.checkBox13);
    final CheckBox cb15 = (CheckBox) findViewById(R.id.checkBox15);
    final CheckBox cb16 = (CheckBox) findViewById(R.id.checkBox16);
    final CheckBox cb17 = (CheckBox) findViewById(R.id.checkBox17);
    final CheckBox cb18 = (CheckBox) findViewById(R.id.checkBox18);
    final CheckBox cb25 = (CheckBox) findViewById(R.id.checkBox25);
    final CheckBox cb27 = (CheckBox) findViewById(R.id.checkBox27);
    final CheckBox cb28 = (CheckBox) findViewById(R.id.checkBox28);
    final CheckBox cb29 = (CheckBox) findViewById(R.id.checkBox29);
    final CheckBox cb30 = (CheckBox) findViewById(R.id.checkBox30);
    final CheckBox cb31 = (CheckBox) findViewById(R.id.checkBox31);
    final CheckBox cb33 = (CheckBox) findViewById(R.id.checkBox33);
    final CheckBox cb34 = (CheckBox) findViewById(R.id.checkBox34);
    final CheckBox cb35 = (CheckBox) findViewById(R.id.checkBox35);
    final CheckBox cb36 = (CheckBox) findViewById(R.id.checkBox36);
    final CheckBox cb37 = (CheckBox) findViewById(R.id.checkBox37);

    //WRONG VALUE ERROR
    final AlertDialog.Builder wrongValueBuilder = new AlertDialog.Builder(context);
    wrongValueBuilder.setTitle("Warning");
    wrongValueBuilder.setMessage("The value you entered is too high!");
    wrongValueBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    //EMPTY TEXT ERROR
    final AlertDialog.Builder emptyETextErrorBuilder = new AlertDialog.Builder(context);
    emptyETextErrorBuilder.setTitle("Warning");
    emptyETextErrorBuilder.setMessage("Please enter a value before pressing this button");
    emptyETextErrorBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

            final int position = sItems.getSelectedItemPosition();
            EditText quantityEditText = (EditText)findViewById(R.id.editText1);

            switch (position){
            case 0:
                AlertDialog.Builder spinnerErrorBuilder = new AlertDialog.Builder(context);
                spinnerErrorBuilder.setTitle("Warning");
                spinnerErrorBuilder.setMessage("Please choose an item from the list above and then enter a certain value");
                spinnerErrorBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
                AlertDialog spinnerError = spinnerErrorBuilder.create();
                spinnerError.show();
                break;
            case 1:
                String item1 = quantityEditText.getText().toString();
                if (item1.matches(""))
                {
                    AlertDialog emptyETextError = emptyETextErrorBuilder.create();
                    emptyETextError.show();
                }
                else
                {
                    if (Integer.parseInt(quantityEditText.getText().toString()) <= 250)
                    {
                        if (Integer.parseInt(quantityEditText.getText().toString()) == 250)
                        {
                            cb4.setText("Elaborate Totem (" + item1 + "/250)");
                            saveItemQuantity("cb4", cb4.getText().toString());
                            cb4.setChecked(true);
                        }
                        else
                        {
                            cb4.setText("Elaborate Totem (" + item1 + "/250)");
                            saveItemQuantity("cb4", cb4.getText().toString());
                            cb4.setChecked(false);
                        }
                    }

The stacktrace, and the 3 following lines, shows where is the problem: 堆栈跟踪和以下3行显示问题所在:

06-27 16:31:44.782: E/AndroidRuntime(13139): Caused by: java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String
06-27 16:31:44.782: E/AndroidRuntime(13139):    at android.app.SharedPreferencesImpl.getString(SharedPreferencesImpl.java:224)
06-27 16:31:44.782: E/AndroidRuntime(13139):    at com.example.gw2legendary.Bifrost.getItemQuantity(Bifrost.java:849)

So you have a problem in the file Bifrost.java, at line 849, in the getItemQuantity() method. 所以你在getItemQuantity()方法的第849行的文件Bifrost.java中遇到了问题。 And it corresponds to the call to getString() method. 它对应于对getString()方法的调用。 It's really interesting looking at the 3 lines and try to understand how you can get all these informations, because you'll have to do the same each time you have an exception in your code. 查看3行并尝试了解如何获取所有这些信息非常有趣,因为每次在代码中出现异常时都必须这样做。

What I can suppose is that the value you try to get from the SharedPreferences has been saved as Boolean , and you try to get it as a String , so you have this ClassCastException. 我可以假设您尝试从SharedPreferences获取的值已保存为Boolean ,并且您尝试将其作为String获取,因此您具有此ClassCastException。 Just revise the value you saved in the SharedPreferences with that key. 只需使用该键修改您在SharedPreferences中保存的值即可。

To have more information, try to learn how to debug your application and use breakpoints to check the values of the variables at a moment of the execution. 要获得更多信息,请尝试学习如何调试应用程序并使用断点在执行时检查变量的值。 Breakpoints allow you to stop the execution exactly where you want and look for the state and values of all the variables. 断点允许您在所需的位置停止执行,并查找所有变量的状态和值。 Debugging with an IDE like Eclipse or NetBeans is really easy and can help you in a lot of situations. 使用像Eclipse或NetBeans这样的IDE进行调试非常简单,可以在很多情况下为您提供帮助。

It should be obvious what the error is from reading the stacktrace: 应该很清楚读取堆栈跟踪的错误是什么:

java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String java.lang.ClassCastException:java.lang.Boolean不能强制转换为java.lang.String

And yes you can read default values from an XML file, read about arrays.xml and http://developer.android.com/guide/topics/resources/more-resources.html#TypedArray here 是的,您可以从XML文件中读取默认值,请阅读arrays.xml和http://developer.android.com/guide/topics/resources/more-resources.html#TypedArray此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM