user6798766 user6798766 - 4 months ago 24
Android Question

how to maintain session using Shared Preferences

I am developing an app,in that i am maintaining Session using Shared Preferences.I that when user login,i am using their email id for further use.But when i tried to use that email in another activity, it is showing null.
Below in my code for mainActivity:

public class main extends AppCompatActivity {
public Button submit;

public static final String MyPREFERENCES = "MyPrefs" ;
public static final String email = "emailkey";
SharedPreferences sharedpreferences;

protected void onCreate(Bundle savedInstanceState) {

submit = (Button) findViewById(;

ImageView i1 = (ImageView) findViewById(;

String checkBoxText = "I agree to all the";
final CheckBox checkBox = (CheckBox) findViewById(;
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText e1 = (EditText) findViewById(;
EditText p1 = (EditText) findViewById(;
String e = e1.getText().toString();
final String password = p1.getText().toString();

SharedPreferences.Editor editor = sharedpreferences.edit();

editor.putString(email, e);


Here is my code for another activity:

String e,email;


public void onCreate(Bundle savedInstanceState) {
SharedPreferences sharedpreferences = getSharedPreferences(main.MyPREFERENCES, Context.MODE_PRIVATE);

String url = "url?COMP_REQ_ID=" + title + "&StuEmail=" + e;
AQuery mAQuery = new AQuery(InternShipsDetails.this);
mAQuery.ajax(url, String.class, new AjaxCallback<String>() {


public void callback(String url, String data, AjaxStatus status) {

super.callback(url, data, status);
if (BuildConfig.DEBUG) {
Log.d("###$Request URL", url + "");
Log.d("###$Response ", data + "");
Log.d("###$Status Message : ", status.getMessage() + "");
Log.d("###$Status Code : ", status.getCode() + "");



You are passing the wrong key to shared Pref because of that you are getting null.

Following is the updated code of yours which will give you the stored email address:

      SharedPreferences sharedpreferences = getSharedPreferences(main.MyPREFERENCES, Context.MODE_PRIVATE);

  e = sharedpreferences.getString(,"");
    String url = "url?COMP_REQ_ID=" + title + "&StuEmail=" + e;

Happy coding !!!