user6798766 user6798766 - 2 months ago 18
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;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);

submit = (Button) findViewById(R.id.btn_login);

ImageView i1 = (ImageView) findViewById(R.id.imgLogo);

String checkBoxText = "I agree to all the";
final CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
checkBox.setText(Html.fromHtml(checkBoxText));
checkBox.setMovementMethod(LinkMovementMethod.getInstance());
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText e1 = (EditText) findViewById(R.id.input_email);
EditText p1 = (EditText) findViewById(R.id.input_password);
String e = e1.getText().toString();
final String password = p1.getText().toString();

SharedPreferences.Editor editor = sharedpreferences.edit();

editor.putString(email, e);

editor.commit();


Here is my code for another activity:

String e,email;

@Override

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.internshipsdetails);
SharedPreferences sharedpreferences = getSharedPreferences(main.MyPREFERENCES, Context.MODE_PRIVATE);

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

@Override

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() + "");

}

Answer

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(main.email,"");
    String url = "url?COMP_REQ_ID=" + title + "&StuEmail=" + e;

Happy coding !!!

Comments