java.lang.String无法强制转换为java.lang.Integer SharedPreferences

时间:2018-02-07 12:38:35

标签: java android android-studio sharedpreferences

我一直潜伏在这里寻求答案,但我似乎无法找到我的代码有什么问题。我有一个计算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"。谢谢

1 个答案:

答案 0 :(得分:0)

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