【问题标题】:java.lang.String cannot be cast to java.lang.Integer SharedPreferencesjava.lang.String 不能转换为 java.lang.Integer SharedPreferences
【发布时间】:2018-02-07 12:38:34
【问题描述】:

我一直在这里寻找答案,但我似乎找不到我的代码有什么问题。我有一个计算 Android 生命周期活动的程序。每次运行它时,当我尝试在 onCreate() 方法上检索数据时都会出现此错误。

private TextView numCreate;
private TextView numStart;
private TextView numResume;
private TextView numPause;
private TextView numStop;
private TextView numDestroy;

private int numc= 0;
private int nums= 0;
private int numr= 0;
private int nump= 0;
private int numst=0;
private int numd= 0;

private String pref  = "MYPREFERENCES";

private String CREATE_NUM_KEY  = "CREATE_NUM_KEY";
private String START_NUM_KEY   = "START_NUM_KEY";
private String RESUME_NUM_KEY  = "RESUME_NUM_KEY";
private String PAUSE_NUM_KEY   = "PAUSE_NUM_KEY";
private String STOP_NUM_KEY    = "STOP_NUM_KEY";
private String DESTROY_NUM_KEY = "DESTROY_NUM_KEY";



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

    numCreate= findViewById(R.id.ocreateview);
    logContainer= findViewById(R.id.logContainer);

    sharedPref= getSharedPreferences(pref,Context.MODE_PRIVATE);

    numc = sharedPref.getInt(CREATE_NUM_KEY,0);
    nums = sharedPref.getInt(START_NUM_KEY,0);
    numr = sharedPref.getInt(RESUME_NUM_KEY,0);
    nump = sharedPref.getInt(PAUSE_NUM_KEY,0);
    numst = sharedPref.getInt(STOP_NUM_KEY,0);
    numd = sharedPref.getInt(DESTROY_NUM_KEY,0);

    numStart.setText(getNum(nums));
    numResume.setText(getNum(numr));
    numPause.setText(getNum(nump));
    numStop.setText(getNum(numst));
    numDestroy.setText(getNum(numd));


    logContainer.append("Triggered onCreate()!");
    logContainer.append("\n\r");


    numc++;
    numCreate.setText(getNum(numc));
    String tstamp = timestamp();
    tCreate.setText(tstamp);

    SharedPreferences.Editor editor = sharedPref.edit();

    editor.putInt(CREATE_NUM_KEY, numc);

    editor.commit();
    editor.apply();
}

“numc = sharedPref.getInt(CREATE_NUM_KEY,0);”行上的错误点带有消息“java.lang.String 无法转换为 java.lang.Integer”。谢谢

【问题讨论】:

  • 该错误意味着您为密钥 CREATE_NUM_KEY 保存了一个 String,并且您正尝试将其检索为 int (Integer)
  • 检查getInt的声明。参数中可能需要 2 个整数,你给他 1 个字符串,1 个整数
  • 你有没有将它存储为字符串?如果是,请尝试重新安装。
  • 试试this解决方案。
  • int getInt (String key, int defValue) 这是 API 中的内容,这就是为什么我想知道为什么它会给我一个错误。

标签: java android android-studio sharedpreferences


【解决方案1】:

方法getSharedPreferences() 返回SharedPreferences,它基本上是MapMap 包含键和值,在SharedPreferences 的情况下,值可以是任何值,这意味着它不必是int。看起来键 CREATE_NUM_KEY 的值是 String 而不是 Integer。是什么让您认为它是Integer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    相关资源
    最近更新 更多