有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓 Java。null对象引用上的lang.NullPointerException

这是我的错误

Attempt to invoke virtual method '安卓.content.SharedPreferences 安卓.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

首选项类

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) 个答案

  1. # 1 楼答案

    试着换掉这条线

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

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