简体   繁体   中英

java.lang.String cannot be cast to java.lang.Integer SharedPreferences

I've been lurking here for answers but I can't seem to find what's wrong with my code. I have a program that counts the Lifecycle activities of Android. Every time I run it I get this error when I try to retrieve data on the onCreate() method.

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();
}

the error points on the line "numc = sharedPref.getInt(CREATE_NUM_KEY,0);" with the message "java.lang.String cannot be cast to java.lang.Integer". Thank you

Method getSharedPreferences() returns SharedPreferences which is basically a Map and a Map contains keys and values and in the case of SharedPreferences the value can be anything, meaning it doesn't have to be an int . Looks like the value for key CREATE_NUM_KEY is a String and not an Integer . What makes you think it is an Integer ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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