问题
I am creating an android app for which I have created login and signup pages. I want to implement the "keep me logged in" functionality in the login page. I think I know what to do but almost anything I try is giving an error.
I have to store the state of checkbox in a SharedPreference and then use it with an if else statement, if it is checked it will skip the login activity and start the main activity, otherwise the login activity.
It would be helpful if someone could provide a sample code.
ChechBox keeplog = (CheckBox)findBiewById(R.Id.checkbox1)
How can I store the check state in Shared Preference and how to fetch its state in the form of boolean or string so that it can be used with if-else statement?
回答1:
Try the following way, declare one boolean variable.
CheckBox keeplog = (CheckBox) findViewById(R.id.checkBox1);
boolean isChecked = false;
Then store the state of checkbox in shared preferences with CheckedChangeListener
.
keeplog.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("isChecked", isChecked);
editor.commit();
}
});
Then now get the state of checkbox from SharedPreferences
using following way.
SharedPreferences settings1 = getSharedPreferences("PREFS_NAME", 0);
isChecked = settings1.getBoolean("isChecked", false);
Now check with the if statement and start your activity like the following
if (isChecked) {
Intent i = new Intent(MainActivity.this, ThirdActivity.class);
startActivity(i);
} else {
Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivity(i);
}
Thank you.
回答2:
Try the following, I have pasted the code about how to connect & login to ejabberd server as without it the code was looking incomplete for Remember Me functionality. I have added comments for explaining how to store & retrieve values in SharedPrefernces.
public class Login extends Activity
{
private XMPPConnection connection;
private ProgressBar progressBar;
private EditText userId;
private EditText password;
private CheckBox rememberMe;
private SharedPreferences sharedPreferences;
private Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userId = (EditText) findViewById(R.id.user_id);
password = (EditText) findViewById(R.id.password);
rememberMe = (CheckBox) findViewById(R.id.remember_me);
progressBar = (ProgressBar) findViewById(R.id.login_progress);
//Retrieving SharedPreferences
sharedPreferences = this.getPreferences(Context.MODE_PRIVATE);
//Retrieving editor
editor = sharedPreferences.edit();
//Retrieving remember me checkbox's set value which if was stored in SharedPreferences
if(sharedPreferences.getBoolean(getString(R.string.remember_me), false))
{
String uId, pass;
uId = sharedPreferences.getString(getString(R.string.user_id), "");
pass = sharedPreferences.getString(getString(R.string.password), "");
userId.setText(uId);
password.setText(pass);
rememberMe.setChecked(sharedPreferences.getBoolean(getString(R.string.remember_me), false));
new Connection().execute(uId, pass);
}
}
public void login(View view)
{
new Connection().execute(userId.getText().toString(), password.getText().toString());
}
private class Connection extends AsyncTask<String, Void, Integer>
{
private static final int CONNECTION_FAILURE = 0;
private static final int LOGIN_FAILURE = 1;
private static final int SUCCESS = 2;
protected void onPreExecute()
{
progressBar.setVisibility(ProgressBar.VISIBLE);
}
protected Integer doInBackground(String... strings)
{
ConnectionConfiguration conConfig = new ConnectionConfiguration("192.168.1.66", 5222, "domain");
connection = new XMPPConnection(conConfig);
try
{
connection.connect();
Log.i("TESTING", "CONNECTED TO " + connection.getHost());
}
catch(Exception e)
{
Log.e("TESTING", e.getMessage());
return CONNECTION_FAILURE;
}
try
{
connection.login(strings[0], strings[1]);
Log.i("TESTING", "LOGGED IN AS " + connection.getUser());
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
}
catch(Exception e)
{
Log.e("TESTING", e.getMessage());
return LOGIN_FAILURE;
}
return SUCCESS;
}
protected void onPostExecute(Integer integer)
{
progressBar.setVisibility(ProgressBar.GONE);
switch(integer)
{
case CONNECTION_FAILURE:
Toast.makeText(getApplicationContext(), "Failed to connect to the server.", Toast.LENGTH_LONG).show();
break;
case LOGIN_FAILURE:
Toast.makeText(getApplicationContext(), "Please check your user id and or password.", Toast.LENGTH_LONG).show();
break;
case SUCCESS:
if(rememberMe.isChecked())
{
//Setting value in SharedPrefernces using editor.
editor.putBoolean(getString(R.string.remember_me), rememberMe.isChecked());
editor.putString(getString(R.string.user_id), userId.getText().toString());
editor.putString(getString(R.string.password), password.getText().toString());
//Committing the changes.
editor.commit();
}
else
//Clearing SharedPreferences.
sharedPreferences.edit().clear().commit();
startActivity(new Intent(getApplicationContext(), Home.class));
}
}
}
}
来源:https://stackoverflow.com/questions/17500265/keep-me-logged-in-checkbox-android