在注销时清除SharedPreferences不起作用

时间:2016-06-02 17:59:01

标签: java android android-studio

我有两个活动,一个是LoginActivity,另一个是ProfileActivity。当用户成功登录时,ProfileActivity会在存储SharedPreferences时启动。因此,当用户重新启动应用程序时,他会再次自动登录。

但问题是当用户注销SharedPreferences时不清楚。尝试之后登录的任何用户都将使用存储的SharedPreferences自动登录。

正确登录,正确注销但不清除SharedPreferences。

LoginActivity:

public class LoginActivity extends AppCompatActivity implements    View.OnClickListener {

//Defining views
private EditText editTextEmail;
private EditText editTextPassword;
private AppCompatButton buttonLogin;

//boolean variable to check user is logged in or not
//initially it is false
private boolean loggedIn = false;

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

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);


    //Initializing views
    editTextEmail = (EditText) findViewById(R.id.editTextEmail);
    editTextPassword = (EditText) findViewById(R.id.editTextPassword);

    buttonLogin = (AppCompatButton) findViewById(R.id.buttonLogin);

    //Adding click listener
    buttonLogin.setOnClickListener(this);
}

@Override
protected void onResume() {
    super.onResume();
    //In onresume fetching value from sharedpreference
    SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);

    //Fetching the boolean value form sharedpreferences
    loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);

    //If we will get true
    if(loggedIn){
        //We will start the Profile Activity
        Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
        startActivity(intent);
    }
}

//Add back button to go back
@Override
public void onBackPressed() {
    super.onBackPressed();
    overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
}

public boolean onSupportNavigateUp(){
    finish();
    overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
    return true;
}

private void login(){
    //Getting values from edit texts
    final String email = editTextEmail.getText().toString().trim();
    final String password = editTextPassword.getText().toString().trim();

    //Creating a string request
    StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.LOGIN_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {
                        JSONObject obj = new JSONObject(response);
                        if(!obj.getBoolean("error")){
                            Toast.makeText(getApplicationContext(),"Login success",Toast.LENGTH_SHORT).show();
                            //Handle login here

                            SharedPreferences sharedPreferences = LoginActivity.this.getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);

                            //Creating editor to store values to shared preferences
                            SharedPreferences.Editor editor = sharedPreferences.edit();

                            //Adding values to editor
                           editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, true);
                           editor.putString(Config.EMAIL_SHARED_PREF, email);

                            //Saving values to editor
                            editor.commit();

                            Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
                            startActivity(intent);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    Toast.makeText(getApplicationContext(),"Invalid username or password",Toast.LENGTH_SHORT).show();;
                    //Toast.makeText(getApplicationContext(),response,Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //You can handle error here if you want
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> params = new HashMap<>();
            //Adding parameters to request
            params.put(Config.KEY_EMAIL, email);
            params.put(Config.KEY_PASSWORD, password);

            //returning parameter
            return params;
        }
    };

    //Adding the string request to the queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

@Override
public void onClick(View v) {
    //Calling the login function
    login();
}
}

然后发生注销的我的ProfileActivity:

public class ProfileActivity extends AppCompatActivity {

//Textview to show currently logged in user
private TextView textView;

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

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);


    //Initializing textview
    textView = (TextView) findViewById(R.id.textView);

    //Fetching email from shared preferences
    SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
    String email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "Not Available");

    //Showing the current logged in email to textview
    textView.setText("Welcome " + email);
}


//Add transitions and override back button activity
@Override
public void onBackPressed() {
    super.onBackPressed();
    startActivity(new Intent(ProfileActivity.this, MainActivity.class));
    finish();
    overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
}

public boolean onSupportNavigateUp() {
    finish();
    overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
    return true;
}

//Logout function
private void logout() {
    //Creating an alert dialog to confirm logout
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setMessage("Are you sure you want to logout?");
    alertDialogBuilder.setPositiveButton("Yes",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {

                    //Getting out sharedpreferences
                    SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
                    //Getting editor
                    SharedPreferences.Editor editor = sharedPreferences.edit();

                    //Puting the value false for loggedin
                    editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, false);

                    //Putting blank value to email
                    editor.putString(Config.EMAIL_SHARED_PREF, "");

                    //Saving the sharedpreferences
                    editor.commit();

                    //Starting login activity
                    Intent intent = new Intent(ProfileActivity.this, MainActivity.class);
                    startActivity(intent);
                }
            });

    alertDialogBuilder.setNegativeButton("No",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {

                }
            });

    //Showing the alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    //Adding our menu to toolbar
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.menuLogout) {
        //calling logout method when the logout button is clicked
        logout();
    }
    {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
}

1 个答案:

答案 0 :(得分:0)

尝试在获取共享偏好设置时添加上下文,同时清除它们会更简单,如下所示:

alertDialogBuilder.setPositiveButton("Yes",
        new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {

                //Getting out sharedpreferences
                SharedPreferences sharedPreferences = ProfileActivity.this.getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
                //Getting editor
                SharedPreferences.Editor editor = sharedPreferences.edit();

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

                //Saving the sharedpreferences
                editor.commit();

                //Starting login activity
                Intent intent = new Intent(ProfileActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });