How to display SharedPreference stored data in Fragment?

后端 未结 2 1107
南旧
南旧 2020-12-22 13:41

I stored values in SharedPreference and now I want to access all that in Fragment. When I tried to run my App, it crashed.

public class Credentials extends F         


        
2条回答
  •  太阳男子
    2020-12-22 13:54

    There is problem with your receiving method.

    public abstract String getString (String key, String defValue)

    Retrieve a String value from the preferences.

    Parameters

    key : The name of the preference to retrieve.
    defValue : Value to return if this preference does not exist.

    Returns

    Returns the preference value if it exists, or defValue. Throws ClassCastException if there is a preference with this name that is not a String.

    So when you use pref.getString() method, you have to store return value to something.

    Try below example.

    String username = pref.getString("username", "EMPTY");
    Toast.makeText(getActivity(), "Value : "+username, Toast.LENGTH_SHORT).show();
    

提交回复
热议问题