如何使用共享首选项维护会话

use*_*766 0 session android

我正在开发一个应用程序,因为我正在使用共享首选项维护会话.我在用户登录时,我正在使用他们的电子邮件ID进一步使用.但是当我尝试在另一个活动中使用该电子邮件时,它显示为空.在我的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();
Run Code Online (Sandbox Code Playgroud)

这是我的另一个活动的代码:

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

            }
Run Code Online (Sandbox Code Playgroud)

Kai*_*ade 6

您可以通过在执行注销操作后更改共享首选项值来管理会话,并在登录时再次检查首选项.您可以在登录和注销操作时将当前时间也保存在字符串中.确保使用私人共享偏好.