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?
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.
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));
}
}
}
}
Related
I am creating a restaurant app for members & non-members. The home page consist of 3 buttons- menu, sign-in and sign-up. I want to let non-members auto login (default phoneId)into the system when they tap on the menu button and members will just sign-in or sign-up each time.
I tried to use sharedPreferences (default phoneId) for the non-member auto login but I don't know whether the default phoneId can be sync with firebase. I want to track the transaction orders for the non-members. Is there any way to only let the default phoneId to have auto login function?
p/s I am just a beginner and doing this app for my project. pls help thanks.
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button btnSignIn, btnSignUp, btnMenu;
public AppPreferences appPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appPreference = new AppPreferences(this);
btnMenu = (Button)findViewById(R.id.btnMenu);
btnSignUp = (Button)findViewById(R.id.btnSignUp);
btnSignIn = (Button)findViewById(R.id.btnSignIn);
btnMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent home = new Intent(MainActivity.this, Home.class);
//Here save user info to preferences
appPreference.setUserPhoneId(Constant.DEFAULT_PHONE_ID);
appPreference.setUserPassword(Constant.DEFAULT_PASSWORD);
startActivity(home);
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signUp = new Intent(MainActivity.this, SignUp.class);
startActivity(signUp);
}
});
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signIn = new Intent(MainActivity.this, SignIn.class);
startActivity(signIn);
}
});
}
}
AppPreferences.java
public class AppPreferences {
// Class variables
private Context context;
private static SharedPreferences sharedPreferences;
private static SharedPreferences.Editor editor;
public static final String PREF_NAME = "iMenuApp";
private int PRIVATE_MODE = 0;
// Define your preferences key
private static final String USER_PHONE = "9876543210";
private static final String USER_PASSWORD = "12345";
public AppPreferences(Context context)
{
this.context = context;
sharedPreferences = this.context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
if (sharedPreferences != null)
{
editor = sharedPreferences.edit();
}
}
//Store user PhoneId
public void setUserPhoneId(String userId){
String TAG = "AppPref:setUserId";
try
{
editor.putString(USER_PHONE, userId);
editor.commit();
} catch (Exception e) {
Log.e(TAG, String.valueOf(e));
}
}
// Get userPhoneId
public String getUserPhoneId(){
return sharedPreferences.getString(USER_PHONE,"default_phone");
}
//Store userPassword
public void setUserPassword(String userPassword){
String TAG = "AppPref:setUserPassword";
try
{
editor.putString(USER_PASSWORD, userPassword);
editor.commit();
} catch (Exception e) {
Log.e(TAG, String.valueOf(e));
}
}
// Get userPassword
public String getUserPassword(){
return sharedPreferences.getString(USER_PASSWORD,"default_password");
}
}
the whole approach is rather questionable, because there is an anonymous authentication provider, which should be used for those "non-members" (and it can also be used together with security rules). storing the state of the authentication to Preferences is prone to errors, because it does not consider the actual state of the authentication - which will result in access denied, once the token expired.
I've also seen your previous question, while nevertheless the whole business logic is flawed.
... better see AccountManager, for how to properly store accounts on Android.
You need to do something like this,
MainActivity -> SignIn -> if SignIn success -> Next time you launch the app land to Home Activity
Try this,
1.) First, you define a new boolean preferences key, USER_LOGGED_IN and create setUserLoggedIn() and getUserLoggedIn() methods in your AppPreferences class as below.
private static final boolean USER_LOGGED_IN = false;
public static void setUserLoggedIn(boolean value) {
String TAG = "AppPref:setUserLoggedIn";
try{
editor.putBoolean(USER_LOGGED_IN, value);
editor.commit();
} catch (Exception e) {
Log.e(TAG, String.valueOf(e));
}
}
public static boolean getUserLoggedIn() {
return sharedPreferences.getBoolean(USER_LOGGED_IN, false);
}
2.) Then, in your SignIn Activity, If login success, set UserLoggedIn as true in your sharedPreferences.
3.) Finally, In your MainActivity, override onResume() method as follows,
#Override
protected void onResume() {
super.onResume();
boolean userLoggedIn = AppPreferences.getUserLoggedIn();
if(userLoggedIn){
MainActivity.this.startActivity(new Intent(getApplicationContext(), Home.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK));
}
}
Try this and let me know your feedback.
Thanks!
I have a login screen with email and password fields. Once the user is validated, an access token is given to the user and updated appropriately.
However, when the app crashes and is restarted, the token is invalidated because the email and password are lost.
How can I recover the email and password in an onResume()?
private class UserLoginTask extends AsyncTask<Void, Void, String> {
private final String lurl;
private final String mEmail;
private final String mPassword;
UserLoginTask(String url, String email, String password) {
lurl = url;
mEmail = email;
mPassword = password;
}
#Override
protected String doInBackground(Void... params) {
try {
WebConnection conn = new WebConnection(lurl, getApplicationContext());
conn.addValuePair("username", mEmail);
Log.v("mEmail", mEmail);
conn.addValuePair("password", mPassword);
Log.v("mPassword", mPassword);
String response = conn.connect();
return response;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String response) {
mAuthTask = null;
showProgress(false);
if(response != null) {
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("email", mEmail);
editor.putString("password", mPassword);
editor.apply();
}
//NEED TO GET RESPONSE FROM SERVER IF LOGIN BASED ON PREFS WAS SUCCESSFUL
if (success) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
#Override
protected void onResume() {
super.onResume();
Context context = getApplicationContext();
SharedPreferences prefs;
prefs = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
String token = prefs.getString("token", null);
//NEED TO GET mEmail and mPassword values from other activity
if (mEmail == null) //Check if it isn't already set
mEmail = prefs.getString("email", null);
if (mPassword == null)
mPassword = prefs.getString("password", null);
if(token == null || token.isEmpty()){
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
Store it in SharedPreferences in your onPostExecute:
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("email", mEmail);
editor.putString("password", mPassword);
editor.apply();
Read it in your onResume:
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
if (mEmail == null) //Check if it isn't already set
mEmail = prefs.getString("email", null);
if (mPassword == null)
mPassword = prefs.getString("password", null);
//Do your stuff here, but check if the Strings are null before
The better way is of course to get rid of the crashes. It's not a good sign if you're sure that your app will crash, especially on the first screen.
If your application go crashed then all the data will be lost , but if you still want to persist you can either use sqlite or shared preferences with proper encryption scheme, since username and password sensitive data.
One way is to save the username and password in some SharedPreferences, before a login-try is made. Please see the documentation here: Google Devs. A simple saving would be:
SharedPreferences prefs = getSharedPreferences("MY_PREFERENCES", MODE_PRIVATE);
prefs.edit().putString("USERNAME", theUsername).commit();
prefs.edit().putString("PASSWORD", thePassword).commit();
Trying to display simple edit text dialog, requesting a string be provided before the rest of my application starts. Currently im trying to make it so the APIKEY of my app is request first thing, then once entered its saved a shared preference and then the dialog will not display. The current code is being reused from a old project of mine. If anybody can help point me in the right direct to making this simple dialog.
public void getapikey() {
AlertDialog.Builder adb = new AlertDialog.Builder(this);
LayoutInflater adbInflater = LayoutInflater.from(this);
View eulaLayout = adbInflater.inflate(R.layout.custom_dialog, null);
editText = (EditText) eulaLayout.findViewById(R.id.editText1);
adb.setView(eulaLayout);
adb.setTitle("Api Key");
adb.setMessage("Welcome to the app, Please input your APIkey below");
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
// CheckBox Confirm for Alert Dialog
public void onClick(DialogInterface dialog, int which) {
String value = editText.getText().toString();
if (editText !=null)
//Unsure about this part above and below
editText = "0"
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("apikey", value);
// Commit the edits!
editor.commit();
return;
}
});
// Preferences For Alert Dialog
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String apikey = settings.getString("apikey", "0");
if (apikey!=null )
adb.setIcon(R.drawable.ic_launcher);
adb.show();
}
}
RECOMMENDED CHANGES
public class Welcome extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
public EditText editText;
public String value;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getapikey();
}
public void getapikey() {
// Alert Dialog
AlertDialog.Builder adb = new AlertDialog.Builder(this);
LayoutInflater adbInflater = LayoutInflater.from(this);
View eulaLayout = adbInflater.inflate(R.layout.custom_dialog, null);
// dontShowAgain = (CheckBox) eulaLayout.findViewById(R.id.checkBox1);
editText = (EditText) eulaLayout.findViewById(R.id.editText1);
adb.setView(eulaLayout);
adb.setTitle("Api Key");
adb.setMessage("Welcome to the app, Please input your APIkey below");
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//String checkBoxResult = "NOT checked";
String value = editText.getText().toString();
// if (dontShowAgain.isChecked())
// checkBoxResult = "checked";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
//editor.putString("skipMessage", checkBoxResult);
editor.putString("apikey", value);
// Commit the edits!
editor.commit();
return;
}
});
// Preferences For Alert Dialog
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
//String skipMessage = settings.getString("skipMessage", "NOT checked");
String apikey = settings.getString("apikey", value);
if(!value.equals(""))
adb.setIcon(R.drawable.ic_launcher);
adb.show();
setContentView(R.layout.splash_screen);
Thread splashThread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
// changed from 5000 to 4000 11.29
while (waited < 3000) {
sleep(100);
waited += 100;
}
} catch (InterruptedException e) {
// do nothing
} finally {
Intent i = new Intent();
i.setClassName("com.example.app",
"com.example.app.CardsTesting");
startActivity(i);
finish();
}
}
};
splashThread.start();
}
}
Still doesnt save the preference after the first time then never displays
//try this one i think it may be work
SharedPreferences settings = PreferenceManager.getSharedPreferences(PREFS_NAME, 0);
I am trying to have SharedPreferences once and control it to different methods rather than having different SharedPreferences in different methods. I have SharedPreferences in the onCreate, LoadPreferences, SavePreferences and ClearTextViews methods. I want to make it so that I have preferences saved to the TextViews from entered text in the EditText and then be able to clear them all with a button. Please help me if you can. Here is the relevant code:
public class notesActivity extends Activity implements OnClickListener
{
Button saveNote;
Button clearText;
EditText note;
TextView textSavedNote1, textSavedNote2, textSavedNote3, textSavedNote4, textSavedNote5, textSavedNote6;
SharedPreferences spNote;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
saveNote = (Button)this.findViewById(R.id.saveNotes);
saveNote.setOnClickListener(this);
clearText = (Button)this.findViewById(R.id.clearAllText);
clearText.setOnClickListener(this);
textSavedNote1 = (TextView)findViewById(R.id.stringSavedNote1);
textSavedNote2 = (TextView)findViewById(R.id.stringSavedNote2);
textSavedNote3 = (TextView)findViewById(R.id.stringSavedNote3);
textSavedNote4 = (TextView)findViewById(R.id.stringSavedNote4);
textSavedNote5 = (TextView)findViewById(R.id.stringSavedNote5);
textSavedNote6 = (TextView)findViewById(R.id.stringSavedNote6);
note = (EditText)this.findViewById(R.id.notes);
spNote = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = spNote.edit();
edit.putString("note"+saveNote,note.getText().toString());
edit.commit();
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Goes back to the home screen
case R.id.item1: Intent i = new Intent(notesActivity.this, UserSettingActivity.class);
startActivity(i);
case R.id.item2:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
// Refreshes the page.
case R.id.item3:
finish();
startActivity(getIntent());
default:
return super.onOptionsItemSelected(item);
}
}
public void onClick (View v){
if(v==saveNote){
SavePreferences("NOTE1", note.getText().toString());
LoadPreferences();
note.setText("");
if(textSavedNote1.getText().toString().length()>0){
SavePreferences("NOTE2", note.getText().toString());
LoadPreferences();
note.setText("");
}
else{
}
}
else if(v==clearText){
ClearTextViews();
}
}
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedNote1 = sharedPreferences.getString("NOTE1", "");
String strSavedNote2 = sharedPreferences.getString("NOTE2", "");
String strSavedNote3 = sharedPreferences.getString("NOTE3", "");
String strSavedNote4 = sharedPreferences.getString("NOTE4", "");
String strSavedNote5 = sharedPreferences.getString("NOTE5", "");
String strSavedNote6 = sharedPreferences.getString("NOTE6", "");
textSavedNote1.setText(strSavedNote1);
textSavedNote2.setText(strSavedNote2);
textSavedNote3.setText(strSavedNote3);
textSavedNote4.setText(strSavedNote4);
textSavedNote5.setText(strSavedNote5);
textSavedNote6.setText(strSavedNote6);
}
private void ClearTextViews(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
}
There are some links that can be helpfull
How to use SharedPreferences in Android to store, fetch and edit values
http://developer.android.com/reference/android/content/SharedPreferences.html
Examples
How to use SharedPreferences
http://android-er.blogspot.com.br/2011/01/example-of-using-sharedpreferencesedito.html
Try the code below.
/*I have added one more button, on click on that button i have set call clearText function and set all text empty, each time before clicking on save button you click first clear button then next value will be inserted in next textview.*/
public class SharedPreferenceJustOneSetOfPreferencesActivity extends Activity implements OnClickListener{
private Button saveNote,clearText,ClearAll;
static TextView textSavedNote1, textSavedNote2, textSavedNote3, textSavedNote4, textSavedNote5, textSavedNote6;
private EditText note;
private SharedPreferences spNote;
private static final String TAG = SharedPreferenceJustOneSetOfPreferencesActivity.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
saveInPreference();
}
private void initView() {
textSavedNote1 = (TextView)findViewById(R.id.textSavedNote1);
textSavedNote2 = (TextView)findViewById(R.id.textSavedNote2);
textSavedNote3 = (TextView)findViewById(R.id.textSavedNote3);
textSavedNote4 = (TextView)findViewById(R.id.textSavedNote4);
textSavedNote5 = (TextView)findViewById(R.id.textSavedNote5);
textSavedNote6 = (TextView)findViewById(R.id.textSavedNote6);
note = (EditText)findViewById(R.id.note);
saveNote = (Button)findViewById(R.id.saveNote);
clearText = (Button)findViewById(R.id.clearText);
ClearAll = (Button)findViewById(R.id.ClearAll);
saveNote.setOnClickListener(this);
clearText.setOnClickListener(this);
ClearAll.setOnClickListener(this);
}
private void saveInPreference() {
spNote = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = spNote.edit();
edit.putString("note"+saveNote,note.getText().toString());
edit.commit();
}
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.item1: Intent i = new Intent(SharedPreferenceJustOneSetOfPreferencesActivity.this, UserSettingActivity.class);
startActivity(i);
case R.id.item2:
Intent intent = new Intent(SharedPreferenceJustOneSetOfPreferencesActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
case R.id.item3:
finish();
startActivity(getIntent());
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View view) {
if (view == saveNote) {
String textvedNote1 =textSavedNote1.getText().toString();
String textvedNote2= textSavedNote2.getText().toString();
String textvedNote3 =textSavedNote3.getText().toString();
String textvedNote4= textSavedNote4.getText().toString();
String textvedNote5 =textSavedNote5.getText().toString();
String textvedNote6= textSavedNote6.getText().toString();
if (textvedNote1.equals("")) {
SavePreferences("NOTE1", note.getText().toString());
Log.e(TAG,"textvedNote1: Inside "+textvedNote1.length());
LoadPreferences();
note.setText("");
}else if (textvedNote2.equals("")&& !textvedNote1.equals("")) {
SavePreferences("NOTE2", note.getText().toString());
Log.e(TAG,"textvedNote2: Inside "+textvedNote1.length());
LoadPreferences();
note.setText("");
} else if (textvedNote3.equals("")&& !textvedNote2.equals("")) {
Log.e(TAG,"textvedNote3: Inside "+textvedNote2.length());
SavePreferences("NOTE3", note.getText().toString());
LoadPreferences();
note.setText("");
} else if (textvedNote4.equals("")&& !textvedNote3.equals("")) {
Log.e(TAG,"textvedNote4: Inside "+textvedNote3.length());
SavePreferences("NOTE4", note.getText().toString());
LoadPreferences();
note.setText("");
} else if (textvedNote5.equals("")&& !textvedNote4.equals("")) {
Log.e(TAG,"textvedNote5: Inside "+textvedNote4.length());
SavePreferences("NOTE5", note.getText().toString());
LoadPreferences();
note.setText("");
} else if (textvedNote6.equals("")&& !textvedNote5.equals("")) {
SavePreferences("NOTE6", note.getText().toString());
Log.e(TAG,"textvedNote6: Inside "+textvedNote5.length());
LoadPreferences();
note.setText("");
}
} else if (view == clearText) {
ClearTextViews();
}else if (view == ClearAll){
ClearTextViews();
textSavedNote1.setText("");
textSavedNote2.setText("");
textSavedNote3.setText("");
textSavedNote4.setText("");
textSavedNote5.setText("");
textSavedNote6.setText("");
}
}
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedNote1 = sharedPreferences.getString("NOTE1", "");
String strSavedNote2 = sharedPreferences.getString("NOTE2", "");
String strSavedNote3 = sharedPreferences.getString("NOTE3", "");
String strSavedNote4 = sharedPreferences.getString("NOTE4", "");
String strSavedNote5 = sharedPreferences.getString("NOTE5", "");
String strSavedNote6 = sharedPreferences.getString("NOTE6", "");
if (!strSavedNote1.equals("")) {
Log.e(TAG,"LoadPreferences1: "+strSavedNote1);
textSavedNote1.setText(strSavedNote1);
} else if (!strSavedNote2.equals("")) {
Log.e(TAG,"LoadPreferences2: "+strSavedNote2);
textSavedNote2.setText(strSavedNote2);
} else if (!strSavedNote3.equals("")) {
Log.e(TAG,"LoadPreferences3: "+strSavedNote3);
textSavedNote3.setText(strSavedNote3);
} else if (!strSavedNote4.equals("")) {
textSavedNote4.setText(strSavedNote4);
} else if (!strSavedNote5.equals("")) {
textSavedNote5.setText(strSavedNote5);
} else if (!strSavedNote6.equals("")) {
textSavedNote6.setText(strSavedNote6);
}
}
private void ClearTextViews(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
}
i am validation of login page is done by server side.i create one checkbox for remember username and password.if check box is checked it remembers the username and password.But the problem is even if check box unchecked also it finds stored username and password. now i want if checkbox is unchecked means it cannot remember username and password
i try this code
public class Login extends Activity {
SharedPreferences app_preferences ;
CheckBox check;
private static final String UPDATE_URL = "serverurl";
public ProgressDialog progressDialog;
private EditText UserEditText;
private EditText PassEditText;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
UserEditText = (EditText) findViewById(R.id.username);
PassEditText = (EditText) findViewById(R.id.password);
check=(CheckBox) findViewById(R.id.checkbox);
String Str_user = app_preferences.getString("username","0" );
String Str_pass = app_preferences.getString("password", "0");
String Str_check = app_preferences.getString("checked", "no");
if(Str_check.equals("yes"))
{
UserEditText.setText(Str_user);
PassEditText.setText(Str_pass);
check.setChecked(true);
}
Button button = (Button) findViewById(R.id.okbutton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int usersize = UserEditText.getText().length();
int passsize = PassEditText.getText().length();
if(usersize > 0 && passsize > 0) {
progressDialog.show();
String user = UserEditText.getText().toString();
String pass = PassEditText.getText().toString();
String Str_check2 = app_preferences.getString("checked", "no");
if(Str_check2.equals("yes"))
{
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("username", user);
editor.putString("password", pass);
editor.commit();
}
doLogin(user, pass);
} else createDialog("Error","Please enter Username and Password");
}
});
check box
check.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// Perform action on clicks, depending on whether it's now checked
SharedPreferences.Editor editor = app_preferences.edit();
if (((CheckBox) v).isChecked())
{
editor.putString("checked", "yes");
editor.commit();
}
else
{
editor.putString("checked", "no");
editor.commit();
}
}
});
try
String Str_check = app_preferences.getString("checked", "no");
if(Str_check.equals("yes"))
{
String Str_user = app_preferences.getString("username","0" );
String Str_pass = app_preferences.getString("password", "0");
UserEditText.setText(Str_user);
PassEditText.setText(Str_pass);
check.setChecked(true);
}
else{
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("username", "");
editor.putString("password", "");
editor.commit();
}
When the user is unchecking the checkbox, you should remove the stored details. Here you are keeping the value stored even the user has unchecked the checkbox.
check box
check.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// Perform action on clicks, depending on whether it's now checked
SharedPreferences.Editor editor = app_preferences.edit();
if (((CheckBox) v).isChecked())
{
editor.putString("username", user);
editor.putString("password", pass);
editor.putString("checked", "yes");
editor.commit();
}
else
{
editor.putString("username", "");
editor.putString("password", "");
editor.putString("checked", "no");
editor.commit();
}
}
});