正常に機能する資格情報を保存するために SharedPreferences を使用していますが、アプリケーションが強制終了されると、ユーザーは再度ログインするよう求められます。
資格情報が保存されると、アプリケーションが強制終了された場合にユーザーにログインを求められることはありません。どんな助けでも大歓迎です。
public class MyActivity extends Activity {
public static final String PREFS_NAME = "myFile";
private String user;
private String userName;
@Override
public void onRestart(){
super.onRestart();
userName = null;
user=null;
//Retrieve the preferences.
SharedPreferences credentials = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
user = credentials.getString(userName, null);
//Check for stored preferences.
if (user!=null) {
Intent j = new Intent(getApplicationContext(), MainActivity.class);
startActivity(j);
finish();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setting default screen to login.xml
setContentView(R.layout.layout_login_new);
//Initializing the fields from XML layout.
final Button login_btn = (Button) findViewById(R.id.btnLogin);
//Retrieve the preferences.
SharedPreferences credentials = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
final SharedPreferences.Editor editor = credentials.edit();
userName = null;
user=null;
//retrieve the stored values.
user = credentials.getString(userName, null);
//Check for stored preferences.
if (user!=null){
Intent j = new Intent(getApplicationContext(), MainActivity.class);
j.putExtra("user_name", user);
startActivity(j);
finish();
}
//Listener for the login button.
login_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent j = new Intent(getApplicationContext(), MainActivity.class);
// Verify the username and password.
if (
(username_login.getText().toString()).equals("test")&&(password_login.getText().toString()).equals("test")){
//Store the credentials in sharedPreferences.
user=username_login.getText().toString();
editor.putString(userName, username_login.getText().toString()).commit();
j.putExtra("user_name", user);
startActivity(j);
finish();
}
else{
Display_error_msg();
}
}
});