简体   繁体   English

使用 SharedPreferences 保存变量使我的应用程序崩溃

[英]Using SharedPreferences to save variable makes my app crash

I am using the SharedPreferences to save and get my variables to my app when the app closes or starts.当应用程序关闭或启动时,我正在使用SharedPreferences来保存和获取我的变量到我的应用程序。

I am using the same type of method/code for all my variables and it works, except for one variable.我对所有变量使用相同类型的方法/代码并且它有效,除了一个变量。

I think maybe the problem might be that this variable also is programmed to reset to = 0 at a specific time each day.我想问题可能在于这个变量也被编程为在每天的特定时间重置为 = 0。 (I am using BroadcastReceiver for this). (我为此使用 BroadcastReceiver)。

Since this is the only variable that I reset at a specific time, and the same variable crashes when I try to save it with SharedPreferences, there might be something about those two things that make my app angry.由于这是我在特定时间重置的唯一变量,并且当我尝试使用 SharedPreferences 保存它时,同一个变量会崩溃,因此这两件事可能会让我的应用程序生气。

  SharedPreferences settings2= getSharedPreferences(PREFS_NAME,0); 

Specifically this line of code below seems to crash the app特别是下面这行代码似乎使应用程序崩溃

dosesTaken = settings2.getInt("dosesTaken",dosesTaken);

This is the class for the "BroadcastReciver"这是“BroadcastReciver”的类

import ...

public class AlarmResetTaken extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        MainActivity.dosesTaken = 0;
        MainActivity.setDosage();
        Activity2.takenDoseText.setText (Integer.toString(MainActivity.dosesTaken));
    }
}

This is the method in MainActivity for the "BroadcastReciver"这是 MainActivity 中“BroadcastReciver”的方法

private void setAlarmResetDose(long timeInMillis) {
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, AlarmResetTaken.class);    
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,0);    
    alarmManager.setRepeating(AlarmManager.RTC, timeInMillis, AlarmManager.INTERVAL_DAY, pendingIntent);
}

And the method for setting the specific time to reset.以及设置具体复位时间的方法。

public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    timeDoseResetHour = hourOfDay;
    timeDoseResetMin = minute;    
    timeDoseResetText.setText( String.format("%02d",hourOfDay) +" : " + String.format("%02d",minute));

        Calendar calendar = Calendar.getInstance();
        calendar.set(
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH),
                hourOfDay,
                minute,
                0
        );
        setAlarmResetDose(calendar.getTimeInMillis()); }

This is the error i get:这是我得到的错误:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.dex, PID: 28325
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dex/com.example.dex.MainActivity}: java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer
        at android.app.SharedPreferencesImpl.getInt(SharedPreferencesImpl.java:302)
        at com.example.dex.MainActivity.onCreate(MainActivity.java:92)
        at android.app.Activity.performCreate(Activity.java:7136)
        at android.app.Activity.performCreate(Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:193) 
        at android.app.ActivityThread.main(ActivityThread.java:6669) 

 

From the error that you have posted,从您发布的错误来看,

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer

it seems that, the type of dosesTaken is Long and not int .似乎, dosesTaken的类型是Long而不是int Thus, when you try to get an Integer with the name dosesTaken , it will throw an error.因此,当您尝试获取名称为dosesTaken的 Integer 时,它会抛出错误。

Thus, to solve the error, either you change因此,要解决错误,要么更改

settings2.getInt("dosesTaken",dosesTaken);

to

settings2.getLong("dosesTaken",dosesTaken);

OR或者

change the type of dosesTaken to int .dosesTaken的类型dosesTakenint

Change this -:改变这个 - :

settings2.getInt("dosesTaken",dosesTaken);

to-:到-:

settings2.getLong("dosesTaken",dosesTaken);

Was the type of dosesTaken of type long?服用的剂量类型是否长? If it was, chances are it is saved as a long and now you're trying to retrieve it as an int, which results in the ClassCastException.如果是,很可能它被保存为 long,现在您试图将它作为 int 检索,这会导致 ClassCastException。 Try and clear your shared preferences and rerun the app.尝试清除您的共享首选项并重新运行该应用程序。

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

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