null对象引用

时间:2017-02-08 17:44:25

标签: java android nullpointerexception sharedpreferences android-sharedpreferences

这是我的错误

  

尝试调用虚拟方法'android.content.SharedPreferences   android.content.Context.getSharedPreferences(java.lang.String,int)'   在空对象引用上

偏好课程

public class SessionManager {

    public static final String PREF_NAME = "LoginPref";
    public static final String KEY_TOKEN = "token";


    public static void saveSetting(Context mContext, String mKey, String mValue) {
        SharedPreferences mSharedPreferences = mContext.getSharedPreferences(PREF_NAME,0);//Error on this line
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putString(mKey, mValue);
        editor.commit();
    }

    public static String getSetting(Context mContext, String mKey, String mDefValue) {
        SharedPreferences mSharedPreferences = mContext.getSharedPreferences(PREF_NAME,0);
        return mSharedPreferences.getString(mKey, mDefValue);
    }

    public static String getToken(Context mContext) {
        return getSetting(mContext, KEY_TOKEN, null);
    }

    public static void setToken(Context mContext, String mValue) {
        saveSetting(mContext, KEY_TOKEN, mValue); //Error on this line

    }
    public static void logoutUser(Context mContext){
        // Clearing all data from Shared Preferences
        SharedPreferences mSharedPreferences = mContext.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.clear();
        editor.commit();
    }


}

片段内部

public void onPageFinished(WebView view, String url) {

            if(getCookie()!= null){

                SessionManager.setToken(getContext(),getCookie()); // Error on this line
                Fragment fragment = new MinhasInfoFragment();
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.frame_content, fragment);
                fragmentTransaction.commit();


                Log.d(TAG, "Value " + getCookie());
            }
        }
 public static String getCookie(){

        String CookieValue = null;

        CookieManager cookieManager = CookieManager.getInstance();
        String cookies = cookieManager.getCookie(url);
        String[] temp = cookies.split(";");
        if (temp == null) {
            return CookieValue;

        }else if(temp != null){
            for (String ar1 : temp ){
                if(ar1.contains("xxxx")){
                    String[] temp1=ar1.split("=");
                    CookieValue = temp1[1];
                }
            }
        }

        return CookieValue;
    }

1 个答案:

答案 0 :(得分:1)

尝试替换此行

SessionManager.setToken(getContext(),getCookie());

SessionManager.setToken(getActivity(),getCookie());