Android Log in with CheckBox - android

My first application in android studio and i want to do this:
Description:
username:username (TextBox)
password:password (TextBox)
Keep me logged in -->CheckBox
LOGIN -->BUTTON
The first time where the user enters your username and password and click to Keep me logged in the application must be remember the username and password without the user writes again in the second time.
Could anyone give me some idea how this implement in android, I found many examples but nothing work.

You could use SharedPreferences to remember the user preference. Here it is a boolean.
SharedPreferences prefs = getDefaultSharedPreferences(this);
boolean keepLoggedIn = prefs.getBoolean(KEY_KEEP_LOGGED_IN, false);
//After user makes the selection on the checkbox,
SharedPreferences.Editor editor = getDefaultSharedPreferences(this).edit();
editor.putBoolean(KEY_KEEP_LOGGED_IN, true);
editor.commit();

I did something very similar to this recently
First, make sure to initialize your fields in question
AutoCompleteTextView mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
EditText mPasswordView = (EditText) findViewById(R.id.password);
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
Set your onClick event:
mEmailSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
In order for the user password to be remembered, you have to save them somewhere. I stored them in shared preferences, but you can use a more secure method depending on your application or even encrypt before storing them http://developer.android.com/guide/topics/data/data-storage.html#pref
//Initialize the shared preferences, set in private mode
SharedPreferences sharedPref = getSharedPreferences("userDetails", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
//Put the strings in the editor
editor.putString(getString(R.string.userAccount), email);
editor.putString(getString(R.string.password), password);
Now in onCreate or your other favorite android start method (depending on if you're using a fragment or activity), retrieve them
//Initialize the shared preferences, set in private mode
SharedPreferences sharedPref = getSharedPreferences("userDetails", MODE_PRIVATE);
//Retrive the values
sharedPref.getString(getString(R.string.userAccount), "")
sharedPref.getString(getString(R.string.password), "")

Related

How to save and get SharedPreferences in different activities?

I've been having issues understanding how to save and read SharedPreferences. I'm trying to save four separate SharedPreferences but as I couldn't figure out how to do it, I decided to try with a simple String.
In this code I'm trying to create and save a string in SharedPreferences
Button enrollNewStudent = (Button) findViewById(R.id.enrollStudentButton) ;
enrollNewStudent.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
SharedPreferences prefs = getSharedPreferences(getString(R.string.testing), MODE_PRIVATE);
SharedPreferences.Editor editor = getSharedPreferences(getString(R.string.testing), MODE_PRIVATE).edit();
editor.putString("name", "Dave");
editor.commit();
startActivity(new Intent(MainActivity.this, AddNewStudent.class));
}
});
And in this next part I'm trying to read the SharedPreferences and have a TextView set to it in a second activity.
Context context = this;
SharedPreferences sharedPref = getSharedPreferences(getString(R.string.testing),MODE_PRIVATE);
String toPutInTextView = sharedPref.getString(getString(R.string.testing), null);
TextView textView = findViewById(R.id.exampleTextView);
textView.setText(toPutInTextView);
When I run this app and click the button to switch to the second activity the TextView on the second activity is blank.
Does anybody see a problem with this? I've been trying to piece together what I need to do from the android developers website and from other questions here but I just cannot get this working. This is for a university project.
The problem is: sharedPref.getString(getString(R.string.testing), null) is pulling using the string getString(R.string.testing) as the key. However, the key you used when you called "putString()" was "name". So you need to use "name" as your key for your getString() call.
Try:
String toPutInTextView = sharedPref.getString("name", "<default_value>");

How to keep information about an app in Android?

I want to know if its possible to keep information about an app in a while for example.
I have an app that access this file and get information about the choices that the user have made. For example:
I have a button for many events (event is a model), and i want to know if the user clicked in the button even after the application restarts.
I know that it is possible to keep information about login and password. Is possible to do something like this with other information?
Use Shared Preferences. Like so:
Create these methods for use, or just use the content inside of the methods whenever you want:
public String getPrefValue()
{
SharedPreferences sp = getSharedPreferences("preferenceName", 0);
String str = sp.getString("myStore","TheDefaultValueIfNoValueFoundOfThisKey");
return str;
}
public void writeToPref(String thePreference)
{
SharedPreferences.Editor pref =getSharedPreferences("preferenceName",0).edit();
pref.putString("myStore", thePreference);
pref.commit();
}
You could call them like this:
// when they click the button:
writeToPref("theyClickedTheButton");
if (getPrefValue().equals("theyClickedTheButton"))
{
// they have clicked the button
}
else if (getPrefValue().equals("TheDefaultValueIfNoValueFoundOfThisKey"))
{
// this preference has not been created (have not clicked the button)
}
else
{
// this preference has been created, but they have not clicked the button
}
Explanation of the code:
"preferenceName" is the name of the preference you're referring to and therefore has to be the same every time you access that specific preference. eg: "password", "theirSettings"
"myStore" refers to a specific String stored in that preference and their can be multiple.
eg: you have preference "theirSettings", well then "myStore" could be "soundPrefs", "colourPrefs", "language", etc.
Note: you can do this with boolean, integer, etc.
All you have to do is change the String storing and reading to boolean, or whatever type you want.
You can use SharedPreference to save your data in Android.
To write your information
SharedPreferences preferences = getSharedPreferences("PREF", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_Id",userid.getText().toString());
editor.putString("user_Password",password.getText().toString());
editor.commit();
To read above information
SharedPreferences prfs = getSharedPreferences("PREF", Context.MODE_PRIVATE);
String username = prfs.getString("user_Id", "");
In iOS NSUserDefaults is used to do the same
//For saving
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:your_username forKey:#"user_Id"];
[defaults synchronize];
//For retrieving
NSString *username = [defaults objectForKey:#"user_Id"];
Hope it helps.

Saving information after closing the app

I've been trying to create a user profile section for my app where the user enters his information (Name, DoB, height, weight etc) and clicks submit. After this he's taken to the main menu of the app.
The problem I have is that if I close the app and run it again, this will obviously result in the app displaying the user profile section again and asks the user to enter his information.
I've been trying to look for a way in which the app saves the information that the user enters and remembers it. So for example when the user first uses the app, he gets the user profile section and enters his information. When the user closes the app and opens it again it should take him straight away to the main menu.
I know I could achieve this slightly with Preferences, but I'd rather use a normal layout(LinearLayout) so that it gives me more options such as TextView etc.
Is there a way where I could achieve this using just LinearLayout instead of Preferences?
I've also been looking at creating custom Preferences, but none of the things I found was particularly useful.
Thanks in advance.
Use SharedPreferences.
Check the application for First Run and display layout which you want to enter user's profile.
After store boolean flag for first Run in shared Preference which will prevent your Profile Screen to display again.
Look at Check if application is on its first run
Update:
Put this FirstRun() code in your onCreate() of Main Activity.
private void FirstRun()
{
SharedPreferences settings = this.getSharedPreferences(MainActivity.PREFS_NAME, 0);
boolean firstrun = settings.getBoolean("firstrun", true);
if (firstrun)
{
// Checks to see if we've ran the application b4
SharedPreferences.Editor e = settings.edit();
e.putBoolean("firstrun", false);
e.commit();
// Display User Profile Screen
}
}
use sharedPreference to store information by this way..
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
SharedPreferences.Editor editor = pref1.edit();
editor.putString("userid", "success");
editor.commit();
and to get the value from it use below code..
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
String str1= pref2.getString("userid", null);
or try to use SqliteDatabase or may be Application Class..this will store the information as you want.
#Override
public boolean saveUserData(UserModel userModel, Context context) {
email = userModel.getEmail();
firstName = userModel.getFirstName();
lastName = userModel.getLastName();
twitterId = userModel.getTwitterId();
SharedPreferences userData = context.getSharedPreferences(APP_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor setUserDataPreference = userData.edit();
setUserDataPreference.putString(EMAIL, email);
setUserDataPreference.putString(FIRST_NAME, firstName);
setUserDataPreference.putString(LAST_NAME, lastName);
setUserDataPreference.putString(TWITTER_ID, twitterId);
setUserDataPreference.commit();
return true;
}
#Override
public UserModel getUserData(Context context) {
UserModel userModel = new UserModel();
SharedPreferences userData = context.getSharedPreferences(APP_NAME,
Context.MODE_PRIVATE);
email = userData.getString(EMAIL, "");
firstName = userData.getString(FIRST_NAME, "");
lastName = userData.getString(LAST_NAME, "");
twitterId = userData.getString(TWITTER_ID, "");
userModel.setEmail(email);
userModel.setFirstName(firstName);
userModel.setLastName(lastName);
userModel.setTwitterId(twitterId);
return userModel;
}

Android login remeber me checkbox

I have created a login for an application. I got it that if you type in the username and password then click on the checkbox it remembers the username and password. However, if you make any changes after you click the checkbox the they are not saved. I am wondering if there is a way to fix this and how would I got about doing this. What I am thinking is when click on the edittext it continually saves what is in the editext. Basically, something that would dynamically saves while the user changes the password or username while the checkbox is clicked.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_log_in);
SharedPreferences.Editor editor;
name = (EditText) findViewById(R.id.userName);
password = (EditText) findViewById(R.id.password);
button = (Button) findViewById(R.id.Button01);
error = (TextView) findViewById(R.id.invalid);
error.setVisibility(View.INVISIBLE);
checkbox = (CheckBox) findViewById(R.id.remember);
LoadPreferences();
LoadPreferences1();
}
public void rememberInfo(View view) {
SavePrefernces("MEM1", name.getText().toString());
SavePrefernces("MEM2", password.getText().toString());
}
private void LoadPreferences1() {
SharedPreferences shardPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem2 = shardPreferences.getString("MEM2", "");
password.setText(strSavedMem2);
}
private void LoadPreferences() {
SharedPreferences shardPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem1 = shardPreferences.getString("MEM1", "");
name.setText(strSavedMem1);
}
private void SavePrefernces(String key, String value) {
SharedPreferences shardPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = shardPreferences.edit();
editor.putString(key, value);
editor.commit();
}
The simplest solution I think would be to do the saving of the login details at the time of pressing the login (or whatever) button. So when the button is pressed, get the values from both the EditTexts and store them in the SharedPreferences.
I believe you are calling Saveprefernces when the checkBox is checked. Instead you should do it once you know that your sign In is success, so that only a valid pair of username:password is saved

Remember me function between sessions

When I click on the 'remember me' checkbox, based on the codes it will save the username and password by sharepreferences. However, when I exit my application and go back, the username and password will disappear.
How do I save the username and password between sessions?
// Remember me function
CheckBox cbRemember = (CheckBox) findViewById(R.id.chkRememberPassword);
if (cbRemember.isChecked()) {
// save username & password
SharedPreferences mySharedPreferences = getSharedPreferences(
"PREFS", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = mySharedPreferences
.edit();
editor.putString("UserName",
String.valueOf(txtLogin.getText().toString()));
editor.putString("Password",
String.valueOf(txtPassword.getText().toString()));
editor.commit();
}
Same as you have put username and password strings inside the shared preference, you can retrieve the same by doing as below:
SharedPreferences settings = getSharedPreferences("PREFS",0);
settings.getString("UserName", "");
settings.getString("user", "");
But i think for implementing remember me functionality, just put a boolean flag whenever the login is successful:
editor.putBoolean("login",true);
and retrieve whenever app is re-started next time:
settings.getBoolean("login", false);
When you exit the app and go back, the onResume() method will be called. It's the place where you should put Paresh Mayani's codes to retrieve the username and password. Check here to understand the lifecycle of an activity in Android.
I think the problem is with the Activity.MODE_PRIVATE flag use instead getSharedPreferences("PREFS", MODE_WORLD_WRITEABLE) flag.

Categories

Resources