共享首选项上下文错误

时间:2017-04-10 17:22:51

标签: android sharedpreferences android-context

我一直在尝试创建一个小型登录应用程序,将登录的信息存储到共享首选项中。

我创建了一个名为Mysession的类来存储,获取和清除共享首选项数据, 该类采用上下文,当我将上下文从我的登录活动传递到登录类,然后将数据存储到共享首选项时,我收到错误。

错误表明我传递了一个空的上下文。

这些是我的课程和活动。

登录活动

public class LoginActivity extends AppCompatActivity {
EditText lemailtxt,lpasstxt;
Button loginbttn;
String lurl;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    lurl = "http://192.168.1.6/test/test.php";
    lemailtxt = (EditText) findViewById(R.id.emailtxt);
    lpasstxt = (EditText) findViewById(R.id.passtxt);
    loginbttn = (Button) findViewById(R.id.loginbttn);

    loginbttn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MLoginOnline login =  new MLoginOnline(getApplicationContext()
                    ,lurl,lemailtxt.getText().toString(),lpasstxt.getText().toString());
            login.execute();
        }
    });


}

登录类

public class MLoginOnline extends AsyncTask<Void,Void,String>{


Context mContext;
String Purl;
String Pemail,Ppass;
ProgressDialog progressDialog;



public MLoginOnline(Context mContext, String purl, String pemail, String ppass) {
    this.mContext = mContext;
    Purl = purl;
    Pemail = pemail;
    Ppass = ppass;
}

MySession session = new MySession(mContext);

@Override
protected void onPreExecute() {
    super.onPreExecute();
    progressDialog = new ProgressDialog(mContext);
    progressDialog.setTitle("Login");
    progressDialog.setMessage("Loging in please wait......");
    progressDialog.show();
}

@Override
protected String doInBackground(Void... params) {
    String data = Loginto();
  return data;
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    String id,name,sem;
    if (s ==null){

        Toast.makeText(mContext,"Error Login in",Toast.LENGTH_SHORT).show();
        progressDialog.hide();
    }else {
        progressDialog.hide();
        try {
            JSONObject object = new JSONObject(s);
            id = object.getString("id");
            name  = object.getString("name");
            sem  = object.getString("sem");
            session.InPutUser(id,name,Pemail,sem);
            Intent intent = new Intent(mContext, HomeActivity.class);
            mContext.startActivity(intent);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }


}


private String Loginto(){

    InputStream inputStream=null;
    String line = null;

    try {
        URL url = new URL(Purl+"?Email="+Pemail+"&Password="+Ppass);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        inputStream = new BufferedInputStream(con.getInputStream());

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        StringBuffer stringBuffer = new StringBuffer();

        if(bufferedReader != null){

            while ((line=bufferedReader.readLine()) != null){
                stringBuffer.append(line+"\n");
            }
        }else {
            return null;
        }
        return stringBuffer.toString();


    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}




}

**共享偏好类**

public class MySession {
Context mcontext;

SharedPreferences preferences;
SharedPreferences.Editor editor;

int PRIVATE_MODE = 0;

private static final String PREFER_NAME = "session";

private final String IS_USER_LOGED_IN = "IsUserLogedIn";

public final String KEY_ID = "id";

 public final String KEY_EMAIL = "email";

public static final String KEY_NAME = "name";


public static final String KEY_SEM = "sem";

public MySession(Context mcontext) {
    this.mcontext = mcontext;
    this.preferences = mcontext.getSharedPreferences(PREFER_NAME,PRIVATE_MODE);
    editor = preferences.edit();
}

public void InPutUser(String id,String name,String email,String sem){

    editor.putBoolean(IS_USER_LOGED_IN,true);

    editor.putString(KEY_ID,id);

    editor.putString(KEY_NAME,name);

    editor.putString(KEY_SEM,sem);

    editor.putString(KEY_EMAIL,email);

    editor.commit();


}


public void logoutUser(Context context,Class intent){

    // Clearing all user data from Shared Preferences
    editor.clear();
    editor.commit();

    // After logout redirect user to Login Activity
    Intent i = new Intent(context, intent);

    // Closing all the Activities
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    // Add new Flag to start new Activity
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    // Staring Login Activity
    context.startActivity(i);


}

public HashMap<String, String> getNameAndSem(){
    HashMap<String, String> user = new HashMap<String, String>();
    // user name
    user.put(KEY_NAME, preferences.getString(KEY_NAME, null));

    // user email id
    user.put(KEY_EMAIL, preferences.getString(KEY_SEM, null));

    // return user
    return user;
}

public HashMap<String, String> getIDandEMail() {
    HashMap<String, String> user = new HashMap<String, String>();
    // user name
    user.put(KEY_NAME, preferences.getString(KEY_ID, null));

    // user email id
    user.put(KEY_EMAIL, preferences.getString(KEY_EMAIL, null));

    // return user
    return user;
}

public boolean IsUserLoggedIn(){
    return preferences.getBoolean(IS_USER_LOGED_IN, false);
}

}

Cat log

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.zer0ll.demo.studentapp, PID: 20793
                  java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
                      at com.zer0ll.demo.studentapp.MySession.<init>(MySession.java:36)
                      at com.zer0ll.demo.studentapp.MLoginOnline.<init>(MLoginOnline.java:43)
                      at com.zer0ll.demo.studentapp.MainView.LoginActivity$1.onClick(LoginActivity.java:32)
                      at android.view.View.performClick(View.java:5156)
                      at android.view.View$PerformClick.run(View.java:20755)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:145)
                      at android.app.ActivityThread.main(ActivityThread.java:5835)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Application terminated.

4 个答案:

答案 0 :(得分:1)

您的session字段正在使用null Context进行初始化。

而不是:

MySession session = new MySession(mContext);

执行:

MySession session;

public MLoginOnline(Context mContext, String purl, String pemail, String ppass) {
    this.mContext = mContext;
    Purl = purl;
    Pemail = pemail;
    Ppass = ppass;
    session = new MySession(mContext);
}

答案 1 :(得分:1)

MLoginOnline班级

此处MySession session = new MySession(mContext);需要在导致mContext尚未初始化的方法下定义。

MySession session;  //declare globally

public MLoginOnline(Context mContext, String purl, String pemail, String ppass) {
    this.mContext = mContext;
    Purl = purl;
    Pemail = pemail;
    Ppass = ppass;
    session = new MySession(mContext);  //initialize here
}

答案 2 :(得分:1)

public MLoginOnline(Context mContext, String purl, String pemail, String ppass) {
    this.mContext = mContext;
    Purl = purl;
    Pemail = pemail;
    Ppass = ppass;
}

MySession session = new MySession(mContext);

把MySession session = new MySession(mContext);进入MLoginOnline

最终代码将是这样的

MySession session;
 public MLoginOnline(Context mContext, String purl, String pemail, String ppass) {
        this.mContext = mContext;
        Purl = purl;
        Pemail = pemail;
        Ppass = ppass;
        session = new MySession(mContext);
    }

答案 3 :(得分:0)

在创建MLoginOnline对象时使用getApplicationContext()。

我想在这里更好地使用'this'。

在这里你可以看到上下文类型

之间的差异

Difference between getContext() , getApplicationContext() , getBaseContext() and “this”

相关问题