Issue
I sent my app to another activity if isLoggedIn is true from SharedPreferences but when i restart my app it goes to main activity perfectly fine but when i press back button then it stops working why??
SharedPreferences=getSharedPreferences(getString(R.string.Prefereces_file_name), Context.MODE_PRIVATE)
val isloggedIn=SharedPreferences.getBoolean("isLoggedIn",false)
if (isloggedIn){
val intent=Intent(this@LoginActivity,MainActivity::class.java)
startActivity(intent)
finish()
}else{
setContentView(R.layout.activity_login)
}
Solution
You can freely call finish()
in onCreate
without calling some extra methods, for example:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); //REQUIRED
val isloggedIn=SharedPreferences.getBoolean("isLoggedIn",false)
if (isloggedIn){
val intent=Intent(this@LoginActivity,MainActivity::class.java)
startActivity(intent)
finish()
}else{
setContentView(R.layout.activity_login)
}
}
And when you call finish It will not stop executing the method, so make sure nothing is below the finish()
line.
And you should not call setContentView
If you will call finish in onCreate to save memory/speed.
I have tested this approach and it works fine.
Back Button Click :
override the
onBackPressed()
method into your Activity like this way
public void onBackPressed(){
// do something here and don't write super.onBackPressed()
}
override the onKeyDown() method
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch(keyCode){
case KeyEvent.KEYCODE_BACK:
// do something here
return true;
}
return super.onKeyDown(keyCode, event);
}
Answered By - S_i_l_e_n_t C_o_d_e_r
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.