某些设备上的java.lang.ClassCastException

时间:2017-08-11 11:36:24

标签: java android

Google Developer Console指出我的应用在同一通道上的2个不同设备(java.lang.ClassCastExceptionP10 (HWVTR)-Android 7.0)上出现LG G3 (g3) - Android 6.0错误。我不知道是什么问题,我已经在Samsung Galaxy A3 2014 & 2017 and Huawei P9 Lite上测试了它并且效果很好。

以下是代码:

SharedPreferences prefs = this.getSharedPreferences(
            "toast", Context.MODE_PRIVATE);

    final int hasVisited = prefs.getInt("HAS_VISISTED_BEFORE", 0);

    if(hasVisited == 0) {
        AlertDialog.Builder builder;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
        } else {
            builder = new AlertDialog.Builder(this);
        }
        builder.setTitle("My Text")
                .setMessage("My Text, dsajh jghjsahjhsda dsa dsa")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // do nothing
                    }
                })
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // do nothing
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_info)
                .show();
        prefs.edit().putInt("HAS_VISISTED_BEFORE", 1).apply();
    }

错误在于final int hasVisited = prefs.getInt("HAS_VISISTED_BEFORE", 0);

如果第一次运行该应用,我只想显示此AlertDialog一次。

错误日志:

Caused by: java.lang.ClassCastException: 
  at android.app.SharedPreferencesImpl.getInt (SharedPreferencesImpl.java:242)
  at com.doggedness_dev.pubgcratessimulator.MenuActivity.onCreate (MenuActivity.java:40)
  at android.app.Activity.performCreate (Activity.java:6272)
  at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1108)
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2387)

我的带有密钥HAS_VISISTED_BEFORE的SharedPreferences可能会干扰另一个具有相同密钥的应用程序?

2 个答案:

答案 0 :(得分:2)

每个应用程序都有自己的共享首选项位置,因此无法干扰具有相同密钥的其他应用程序。

如果您的应用程序的旧版本与HAS_VISISTED_BEFORE具有相同的密钥且其值不是整数,则会出现此问题。因为您已经拥有此键的值,所以类型也不同。

对于此异常,您可以使用如下所示的try-catch。

try {

}catch (ClassCastException ex){
    ex.printStackTrace();
}

答案 1 :(得分:0)

删除它:

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
    } else {
        builder = new AlertDialog.Builder(this);
    }

并写下以下行;

builder = new AlertDialog.Builder(MainActivity.this);
相关问题