Reputation: 415
We have seen in almost every app that the user logs in for the first time and the next time he opens the app, he goes straight inside the app without authentication. So I am trying to create exact same feature into my app, I followed documentation and coded into my app. Build is successful but it's not working, it keeps asking for authentication after closing app.
Code
package abc.xyz;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button b;
SharedPreferences sp;
EditText username,password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button)findViewById(R.id.button);
username = (EditText)findViewById(R.id.editText);
password = (EditText)findViewById(R.id.editText2);
sp = getSharedPreferences("b", MODE_PRIVATE);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
login();
if(sp.getBoolean("Logged",false)){
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}
}
});
}
public void login(){
String user=username.getText().toString().trim();
String pass=password.getText().toString().trim();
if(user.equals("admin")&& pass.equals("admin"))
{
sp.edit().putBoolean("Logged", true).apply();
Toast.makeText(this,"Success!",Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}else {
Toast.makeText(this,"username and password do not matched!",Toast.LENGTH_LONG).show();
}
}
}
Can anyone help me out here?
Upvotes: 2
Views: 148
Reputation: 37404
Your are saving the state as true
then every time executing the login method instead you need to move to MainActivity2
when the value is true
so use
// move to next activity if user is authenticated
if(sp.getBoolean("Logged",false)){
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
login();
}
});
Note : as mentioned by @shb , case sensitivity matter
Upvotes: 2
Reputation: 6277
You are saving
sp.edit().putBoolean("Logged", true).apply();
with an uppercase 'L' //Logged
but while retrieving you're using a lowercase 'l' //logged
if(sp.getBoolean("logged",false)){
//...
}
use either "logged" or "Logged" in both of the places.
Upvotes: 1