Mohamed Osman
Mohamed Osman

Reputation: 138

Shared preferences Context error

I been trying to create a small login app that stores the logged in information to shared preferences.

i created a class called Mysession to store,get and clear shared preferences data, the class takes a context and when i pass the context from my login activity to login class and then store the data to shared preferences i get an error.

the error indicates that i passed an empty context.

these are my classes and activities.

Login Activity

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();
        }
    });


}

Login Class

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;
}




}

**Shared preferences class **

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.

Upvotes: 0

Views: 794

Answers (4)

S G
S G

Reputation: 802

You are using getApplicationContext() while creating MLoginOnline object.

I would say better use 'this' here.

here you could see the differences between context type

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

Upvotes: 0

rafsanahmad007
rafsanahmad007

Reputation: 23881

In your MLoginOnline class

Here MySession session = new MySession(mContext); needs to be defined under a method cause mContext is not initialized yet.

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
}

Upvotes: 1

Umut Aksun
Umut Aksun

Reputation: 179

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

MySession session = new MySession(mContext);

put MySession session = new MySession(mContext); into MLoginOnline

final code will be like this

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);
    }

Upvotes: 1

azizbekian
azizbekian

Reputation: 62199

Your session field is being initialized with null Context.

Instead of:

MySession session = new MySession(mContext);

Do:

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);
}

Upvotes: 1

Related Questions