我正在开发一个应用程序,我需要在其中管理用户会话,即当用户第一次登录时,他必须看到登录页面,一旦他通过身份验证,他就会被重定向到主屏幕,并且在 sharedpreferences 中设置了一个值。现在在主屏幕上,当用户单击注销按钮时,必须清除 shsredpreferences 中的值,并且下次用户打开应用程序时,他必须被定向到登录页面。除非并且直到用户单击注销,否则不得显示登录页面. 我能够将值存储在 sharedpreferences 中,但无法删除它们。
这是我的 loginpage.java 代码
package com.sess.eg;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class loginpage extends Activity {
/** Called when the activity is first created. */
EditText acc,user,pin;
Button login;
StringBuilder builder = new StringBuilder();
String UserName;
SharedPreferences.Editor prefs;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// SharedPreferences prefs1 = getPreferences(MODE_WORLD_READABLE);
// UserName= prefs1.getString("User", "Abcdef");
//
// System.out.println(UserName);
//
// if(UserName.equals("Ad"))
//
// {
// System.out.println(UserName);
// Intent i=new Intent(loginpage.this,homepage.class);
// startActivity(i);
// }
setContentView(R.layout.main);
acc = (EditText) findViewById(R.id.ed_login_acc);
user = (EditText) findViewById(R.id.ed_user_acc);
pin = (EditText) findViewById(R.id.ed_pin_acc);
login = (Button) findViewById(R.id.login_button);
SharedPreferences prefs1 = getPreferences(MODE_WORLD_READABLE);
login.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
prefs.putString("User", "Ad");
prefs.commit();
//System.out.println(sendJson1());
//startService(new Intent(Login.this, MyService.class));
Intent i = new Intent(loginpage.this, homepage.class);
startActivity(i);
finish();
//System.out.println(UserName);
}
});
}
@Override
protected void onStart() {
SharedPreferences prefs1 = getPreferences(MODE_WORLD_READABLE);
UserName= prefs1.getString("User", "Abcdef");
System.out.println(UserName);
if(UserName.equals("Ad"))
{
System.out.println(UserName);
Intent i=new Intent(loginpage.this,homepage.class);
startActivity(i);
finish();
}
super.onStart();
}
}
here is my code for homepage.java
package com.sess.eg;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class homepage extends Activity{
Button logout;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home3);
logout = (Button) findViewById(R.id.logout);
logout.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
SharedPreferences.Editor prefs = getPreferences(MODE_WORLD_WRITEABLE).edit();
prefs.clear();
// prefs.commit();
SharedPreferences prefs1 = getPreferences(MODE_WORLD_READABLE);
String UserName= prefs1.getString("User", "Abcdef");
System.out.println(UserName);
finish();
}
});
}
}