使用SharedPreferences的ClassCastException

时间:2013-08-17 17:34:23

标签: java android string int classcastexception

编译器抛出ClassCastException:String无法转换为下面第96行的int。我不能为我的生活找出原因,任何帮助都会得到真正的体谅。

代码:

public class Progress extends Activity {

private TextView names, current, goal, start;
private EditText updateBox;
private ProgressBar progress;
private String currentWeight, goalS, startS;
private int currentWeightInt, weightUpdate;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_progress);
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    String name = preferences.getString("name", "You need to create a profile first!");
    names = (TextView) findViewById(R.id.noProf);
    names.setText("Welcome back " + name);
    start = (TextView) findViewById(R.id.start);
    startS = preferences.getString("start", "");
    start.setText("Start:" + startS);

    current = (TextView) findViewById(R.id.currently);
    currentWeight = preferences.getString("current", "");
    currentWeightInt = Integer.parseInt(currentWeight);
    current.setText("currently  " + currentWeight);

    goal = (TextView) findViewById(R.id.goal);
    goalS = preferences.getString("goal", " ");
    goal.setText("goal: " + goalS);

    progress = (ProgressBar) findViewById(R.id.progressBar1);

}

public void update(View view) {
    updateBox = (EditText) findViewById(R.id.updateWeight);
    if (updateBox.getText().toString().matches(" ")) {
        Toast.makeText(this, "Please enter a weight", Toast.LENGTH_LONG).show();
    }
    else {
        weightUpdate = Integer.parseInt(updateBox.getText().toString());

        if (weightUpdate > currentWeightInt) {
            weightGain();
            Toast.makeText(this, "weight gain", Toast.LENGTH_LONG).show();
        }

        else if (weightUpdate < currentWeightInt) {
            Toast.makeText(this, "weight loss", Toast.LENGTH_LONG).show();
            weightLoss();

        }

        else {
            Toast.makeText(this, "stayed the same", Toast.LENGTH_LONG).show();

        }
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.progress, menu);
    return true;
}

private void weightGain() {
    if (weightUpdate > currentWeightInt) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("current", Integer.toString(weightUpdate));
        editor.commit();

    }

}

private void weightLoss() {
    if (weightUpdate < currentWeightInt) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        int toSet = preferences.getInt("progress",0);
        progress.setProgress(toSet);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("current", Integer.toString(weightUpdate));
        editor.commit();
        double first = (Double.parseDouble(startS) - Double
                .parseDouble(currentWeight));
        double second = (Double.parseDouble(startS) - Double
                .parseDouble(goalS));
        double last = first / second;
        double result = last * 100;
        int resultInt = (int) result;
        progress.setProgress(resultInt);

        editor.putInt("progress", resultInt);
        editor.commit();
        Intent refresh = new Intent(this, Progress.class);

        startActivity(refresh);

        this.finish();

    }
}

}

堆栈追踪:

 08-17 18:44:25.565: D/qdmemalloc(11781): ion: Mapped buffer base:0x6c501000 size:8355840 offset:0 fd:56
08-17 18:44:25.565: D/qdmemalloc(11781): ion: Mapped buffer base:0x67680000 size:4096 offset:0 fd:57
08-17 18:44:28.418: D/qdmemalloc(11781): ion: Mapped buffer base:0x6cd09000 size:8355840 offset:0 fd:58
08-17 18:44:28.418: D/qdmemalloc(11781): ion: Mapped buffer base:0x67b33000 size:4096 offset:0 fd:59
08-17 18:44:29.459: I/InputMethodManager(11781): windowGainedFocus, mServedView=android.widget.EditText{4188f960 VFED..CL .F....ID 225,921-855,1039 #7f08001b app:id/updateWeight}, inputType=0x2, softInputMode=0x120, pid=11781
08-17 18:44:29.509: D/qdmemalloc(11781): ion: Mapped buffer base:0x6d668000 size:8355840 offset:0 fd:61
08-17 18:44:29.509: D/qdmemalloc(11781): ion: Mapped buffer base:0x67cca000 size:4096 offset:0 fd:62
08-17 18:44:29.529: D/qdmemalloc(11781): ion: Unmapping buffer  base:0x6bbe9000 size:8355840
08-17 18:44:29.529: D/qdmemalloc(11781): ion: Unmapping buffer  base:0x6720d000 size:4096
08-17 18:44:29.529: D/qdmemalloc(11781): ion: Unmapping buffer  base:0x6c501000 size:8355840
08-17 18:44:29.529: D/qdmemalloc(11781): ion: Unmapping buffer  base:0x67680000 size:4096
08-17 18:44:29.529: D/qdmemalloc(11781): ion: Unmapping buffer  base:0x6cd09000 size:8355840
08-17 18:44:29.529: D/qdmemalloc(11781): ion: Unmapping buffer  base:0x67b33000 size:4096
08-17 18:44:29.980: D/qdmemalloc(11781): ion: Mapped buffer base:0x6bbe9000 size:8355840 offset:0 fd:54
08-17 18:44:29.980: D/qdmemalloc(11781): ion: Mapped buffer base:0x6720d000 size:4096 offset:0 fd:56
08-17 18:44:30.270: D/qdmemalloc(11781): ion: Mapped buffer base:0x6c501000 size:8355840 offset:0 fd:57
08-17 18:44:30.270: D/qdmemalloc(11781): ion: Mapped buffer base:0x67680000 size:4096 offset:0 fd:58
08-17 18:44:35.976: W/dalvikvm(11781): threadid=1: thread exiting with uncaught exception (group=0x413feba0)
08-17 18:44:36.006: E/AndroidRuntime(11781): FATAL EXCEPTION: main
08-17 18:44:36.006: E/AndroidRuntime(11781): java.lang.IllegalStateException: Could not execute method of the activity
08-17 18:44:36.006: E/AndroidRuntime(11781):    at android.view.View$1.onClick(View.java:3626)
08-17 18:44:36.006: E/AndroidRuntime(11781):    at android.view.View.performClick(View.java:4231)
08-17 18:44:36.006: E/AndroidRuntime(11781):    at android.view.View$PerformClick.run(View.java:17537)
08-17 18:44:36.006: E/AndroidRuntime(11781):    at android.os.Handler.handleCallback(Handler.java:725)
08-17 18:44:36.006: E/AndroidRuntime(11781):    at android.os.Handler.dispatchMessage(Handler.java:92)
08-17 18:44:36.006: E/AndroidRuntime(11781):    at android.os.Looper.loop(Looper.java:158)
08-17 18:44:36.006: E/AndroidRuntime(11781):    at android.app.ActivityThread.main(ActivityThread.java:5777)
08-17 18:44:36.006: E/AndroidRuntime(11781):    at java.lang.reflect.Method.invokeNative(Native Method)
08-17 18:44:36.006: E/AndroidRuntime(11781):    at java.lang.reflect.Method.invoke(Method.java:511)
08-17 18:44:36.006: E/AndroidRuntime(11781):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083)
08-17 18:44:36.006: E/AndroidRuntime(11781):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
08-17 18:44:36.006: E/AndroidRuntime(11781):    at dalvik.system.NativeStart.main(Native Method)
08-17 18:44:36.006: E/AndroidRuntime(11781): Caused by: java.lang.reflect.InvocationTargetException
08-17 18:44:36.006: E/AndroidRuntime(11781):    at java.lang.reflect.Method.invokeNative(Native Method)
08-17 18:44:36.006: E/AndroidRuntime(11781):    at java.lang.reflect.Method.invoke(Method.java:511)
08-17 18:44:36.006: E/AndroidRuntime(11781):    at android.view.View$1.onClick(View.java:3621)
08-17 18:44:36.006: E/AndroidRuntime(11781):    ... 11 more
08-17 18:44:36.006: E/AndroidRuntime(11781): Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
08-17 18:44:36.006: E/AndroidRuntime(11781):    at android.app.SharedPreferencesImpl.getInt(SharedPreferencesImpl.java:240)
08-17 18:44:36.006: E/AndroidRuntime(11781):    at com.example.smallchangebigloss.Progress.weightLoss(Progress.java:96)
08-17 18:44:36.006: E/AndroidRuntime(11781):    at com.example.smallchangebigloss.Progress.update(Progress.java:63)
08-17 18:44:36.006: E/AndroidRuntime(11781):    ... 14 more

2 个答案:

答案 0 :(得分:0)

我认为在实际将“进度”保存到SharedPreferences的行中,您将意外地保存字符串而不是整数

然后,在尝试获取保存的值时,您会遇到ClassCastException,因为保存的值实际上是String而不是Integer。

<强>更新

尝试像这样获取SharedPreferences:

SharedPreferences sp = c.getSharedPreferences("MySharedPrefs", 0);

还要考虑清理项目

每次调用weightLoss()时,我也无法理解你重启活动的原因,你能解释一下吗?

Intent refresh = new Intent(this, Progress.class);

startActivity(refresh);
this.finish();

这是刷新UI组件的方法:

只需创建一个刷新方法,随时读取SharedPreferences中的值,并将它们设置为TextView。

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_progress);

    names = (TextView) findViewById(R.id.noProf);
    start = (TextView) findViewById(R.id.start);
    current = (TextView) findViewById(R.id.currently);
    goal = (TextView) findViewById(R.id.goal);

    progress = (ProgressBar) findViewById(R.id.progressBar1);

    refresh(); // call this method everytime you want to update the textviews and so on...
}

// CALL THIS METHOD EVERYTIME YOU WANT TO REFRESH INSTEAD OF RESTARTING YOUR ACTIVITY
public void refresh() {

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    String name = preferences.getString("name", "You need to create a profile first!");

    names.setText("Welcome back " + name);
    startS = preferences.getString("start", "");

    start.setText("Start:" + startS);

    currentWeight = preferences.getString("current", "");
    currentWeightInt = Integer.parseInt(currentWeight);
    current.setText("currently  " + currentWeight);

    goalS = preferences.getString("goal", " ");

    goal.setText("goal: " + goalS);
}

// your other methods...

private void weightLoss() {

    if (weightUpdate < currentWeightInt) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        int toSet = preferences.getInt("progress",0);
        progress.setProgress(toSet);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("current", Integer.toString(weightUpdate));
        editor.commit();
        double first = (Double.parseDouble(startS) - Double
            .parseDouble(currentWeight));
        double second = (Double.parseDouble(startS) - Double
            .parseDouble(goalS));
        double last = first / second;
        double result = last * 100;
        int resultInt = (int) result;
        progress.setProgress(resultInt);

        editor.putInt("progress", resultInt);
        editor.commit();

        refresh(); // DO THIS HERE INSTEAD OF RESTARTING THE ACTIVITY
    }
}

答案 1 :(得分:0)

修正了这一点 - 正如你所正确指出的那样,所有代码都是正确的。问题是我之前已将首选项的进度值从字符串更改为int。这意味着在第一次检索它时仍然是一个字符串。要纠正这个问题就像从手机上卸载应用程序并重新安装一样简单。现在遇到了一些新问题,但这部分代码没有。感谢大家的帮助。