gpt4 book ai didi

java - 注销时清除 SharedPreferences 不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 12:33:22 25 4
gpt4 key购买 nike

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

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

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

登录 Activity :

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

然后是发生注销的 My 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);
}
}
}

最佳答案

尝试在获取共享首选项时添加上下文,并且清除它们会更简单,如下所示:

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

关于java - 注销时清除 SharedPreferences 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37599029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com