简体   繁体   中英

Android - SharedPreferences - can't get my value

I have a very strange problem.

I use key/value pairs to save my application data. And it works fine! I can save and get string-values and boolean-values.

The only type of value, I cant get is Integer

Let me describe the situation:

In one activity, I save my key/value pair this way:

addElement(getApplicationContext(), "all_tasks", Integer.parseInt(allTasks.getText().toString()));

I use this method from my KeyValueStorageHelper.java file:

/* Записать новую целочисленную пару */
public static void addElement(Context context, String key, int value) {
    ContextWrapper contextWrapper = new ContextWrapper(context);
    SharedPreferences.Editor sharedPreferences = contextWrapper.getSharedPreferences("MentalCalculationSaveData", ContextWrapper.MODE_PRIVATE).edit();
    sharedPreferences.putInt(key, value);
    sharedPreferences.apply();
}

After that, in another activity, I try to do this, and here the strange comes:

if (isKeyExists(getApplicationContext(), "all_tasks"))
        Toast.makeText(getApplicationContext(), getInt(getApplicationContext(), "all_tasks"),Toast.LENGTH_LONG).show();

This code throws an "ResouceNotFound Exception". Okey. But it is strange. If there is no such resource, why my if-else block returns true?

After that I suggested, that maybe this is not an Integer key/value pair.

I tried this:

Toast.makeText(getApplicationContext(), (int)getFloat(getApplicationContext(), "all_tasks"),Toast.LENGTH_LONG).show();

And it againg throws an exception:

java.lang.Integer cannot be cast to java.lang.Float

So what's wrong? How can my value be Integer and throws an exception, when I am trying to get it?

Are you retrieving the shared preferences from the same pref. In your addElement method, you use the " MentalCalculationSaveData " one. Make sure you use the same one to retrieve.

Also what is the implementation of your isKeyExists. You can try to use sharedPreferences's contains method to check if the key exist or not.

In addition, not sure what is your getInt() method. You can use sharedPreferences' getInt() , which you should put the key name as the first parameter, a default value as the second parameter. So you can do something like pref.getInt("all_tasks", 0), if no value exist, the 0 will return.

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