My app stayed logged in even after restart - android

I am making simple login app for my homework project.I wanted to user stay loged in
after my app is destroyed.I managed that but now he is always loged in even without entering email and password.I wanted to be able to stay loged in until he press log out button,but even he press it he will go back to log in page but when app is restarted it is again loged in
i tried this: How to keep android applications always be logged in state?
log in page:
public class MainActivity extends AppCompatActivity {
private EditText email, password;
private SharedPreferences sharedPreferences;
public static final String PREF_NAME = "sp_name";
ConstraintLayout constraintLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email = findViewById(R.id.email_view);
password = findViewById(R.id.pass_view);
constraintLayout = findViewById(R.id.activity_main);
sharedPreferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
// //uzimam email vrednost iz sharedprefernce
String storedEmail = sharedPreferences.getString("EMAIL", null);
//uzimam password vrednosti
String storedPass = sharedPreferences.getString("PASSWORD", null);
if(storedEmail != null && storedPass != null){
// login automatically with username and password
goToPocetnaStranica();
}
Button loginButton = findViewById(R.id.login_button);
//kada je dugme za login stisnuto loguje se na pocetnu stanu i skladisti login informacije
//u sharedpreference tak da sledeci put moze da se autologuje bez ponovnog unosa login informacija
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//uzimam email i password
String getEmail = email.getText().toString();
String getPass = password.getText().toString();
//proveravam da li je neko polje prazno
if (TextUtils.isEmpty(getEmail) || TextUtils.isEmpty(getPass)) {
Toast.makeText(MainActivity.this, R.string.obavestenje_za_unos, Toast.LENGTH_SHORT).show();
} else {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("EMAIL", getEmail);
editor.putString("PASSWORD", getPass);
editor.apply();
email.setText("");
password.setText("");
goToPocetnaStranica();
}
}
});
}
private void goToPocetnaStranica(){
Toast.makeText(MainActivity.this, R.string.uspesno_logovanje, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, PocetnaStranica.class);
startActivity(intent);
}
}
and my page afer log in:
public class PocetnaStranica extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pocetna_stranica);
Button logoutButton = findViewById(R.id.logout_button);
logoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
editor.remove("PASSWORD");
editor.clear();
editor.apply();
finish();
}
});
}
}

#Sebastian makes a good point saying that you need to use the AND operator in the if statement instead of the OR operator. That's because it checks if the email exists or if the password exists. You as you posted only removed the password, so the email is still there. The program takes it as signed in. Also, instead of independently deleting the password and email, just use:
sharedPreferences.clear() //Clears every single value
That would also help with the removal of cache files and save memory space that is wasted.
Edit:
The error actually is in your second snippet of code. This code to get the shared preferences:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
This does get the default shared preferences, but instead of getting the preferences where you save your email and your password, it returns a whole different set of shared preferences. What you should do instead is this:
SharedPreferences pref = getApplicationContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
It's the same as you do in MainActivity.java and that was the error: it needed to be the same. Here String PREF_NAME = "sp_name";. The preference name/ids, they exist for this exact thing to identify shared preferences.
If you want to learn more about shared preferences and how they work look at the documentation: https://developer.android.com/reference/android/content/SharedPreferences

It seems like in your main activity you are using the OR ( || ) operator when it should be AND ( && ).
Don’t forget to also delete the email from the preferences.

Related

Shared Preferences Appearing On-Screen

I am creating an attendance tracker for a summer camp, where counsellors can input the time their camper signed in by typing into an editText and pressing the save button. This basic string should be saved into a textbox and loaded onto the screen every time the app is loaded. There are multiple boxes like this so the counsellors can track what times each student came in / left every day.
I have used sharedPreferences to save the input from the counsellor when a button is pressed, and then display it using another button. However, I CANNOT GET THE TEXT TO APPEAR ON THE SCREEN WHEN I CLOSE AND REOPEN THE APP. Is my code missing something??
public class AttendancePage extends AppCompatActivity {
EditText mondayMorn;
TextView displayMonMorn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance_page);
String counsellorName = getIntent().getStringExtra("Senior Counsellor Name");
TextView tv = (TextView)findViewById(R.id.counsellorName);
tv.setText(counsellorName + "'s");
mondayMorn = (EditText) findViewById(R.id.editText37);
displayMonMorn = (TextView) findViewById(R.id.displayMonMorn);
}
public void saveInput (View view) {
SharedPreferences checkInMon = getSharedPreferences("LoginTime", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = checkInMon.edit();
editor.putString("mondayIn", mondayMorn.getText().toString());
editor.apply();
Toast.makeText(this, "Saved", Toast.LENGTH_LONG).show();
}
public void updateSettings (View view){
SharedPreferences checkInMon = getSharedPreferences("LoginTime", Context.MODE_PRIVATE);
String time = checkInMon.getString("mondayIn", "");
displayMonMorn.setText(time);
}
Replace:
SharedPreferences.Editor editor = checkInMon.edit();
editor.putString("mondayIn", mondayMorn.getText().toString());
editor.apply();
with:
SharedPreferences.Editor editor = checkInMon.edit();
editor.putString("mondayIn", mondayMorn.getText().toString());
editor.commit();
that should at least save the data in preferences.

Android Log in with CheckBox

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), "")

how to pass extra intent to two activities

i have an app that on the first activity asks the persons name on the second page it displays the name in a sentence i want to use the name in the third fourth or 9th activity how do i properly declare it (public?) and call it when and where ever i need it? this is my code sending it
Main
public class MainActivity extends Activity {
Button ok;
EditText name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText)findViewById(R.id.editText);
Typeface font_a = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
name.setTypeface(font_a);
ok=(Button)findViewById(R.id.button);
Typefacefont_b=Typeface.createFromAsset(getAssets(),
"fonts/SignPaintersGothicShaded.ttf");
ok.setTypeface(font_b);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String nameStr = name.getText().toString();
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("NAMEDATA",nameStr);
startActivity(intent);
}
});
}
and this is activity 2 receiving it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t = (TextView)findViewById(R.id.textView3);
Typeface font_b = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
t.setTypeface(font_b);
String n = this.getIntent().getStringExtra("NAMEDATA");
t.setText(n);
so please how would i reuse this?
Use SharedPreferences to save the name or whatever variable you need, then read whenever you need it. First, create global in MainActivity which will be used as preference file name:
public static final String PREFS_NAME = "MyPrefsFile";
Then, to save:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", name);
editor.commit();
to load:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String name = settings.getString("name", "John");
Once saved, the prefs are accessible for every activity.
So in your case, save the name when ok button is pressed:
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String nameStr = name.getText().toString();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", nameStr);
editor.commit();
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
});
Then read it:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t = (TextView)findViewById(R.id.textView3);
Typeface font_b = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
t.setTypeface(font_b);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String n = settings.getString("name", "defaultName");
t.setText(n);
You can do similarly in every activity you need it. See docs here.
You have a number of different approaches to share data between activities. I would say which one you use depends on the ultimate source and destination of the data.
Pass through intents - This is the method you are currently using. To proceed, just keep passing the name to the next intent.
Save to SharedPreference - This method you save the information to the "preference" file of the application. This is useful if the the user is setting up a profile or other semi-fixed information.
Write it to a DB - Here you would create a a new SQLite table for user information and write new rows to it for the name, password, and other info. This has way more overhead and is really only useful if you have multiple users in the same application
Save to a singleton - In this case you create a static class with public properties that can be set. This would be least favorable all the information is lost on application close, but could be useful for temporary creation and retention across many activities. Be warned: bad programming can make singletons a nightmare
Create class extending from Application class.
Implement setter and getter inside that class like,
public class GlobalClass extends Application {
//create setters and getters here
public void setUserInfo(String userInfo) {
}
public void getUserInfo() {
return userInfo;
}
}
then you can use this from any activity like,
GlobalClass app = (GlobalClass ) getApplication();
app.getUserInfo();

Remember Users in android

I am developing an Android App. It has a login page.. what is the best way to save users' details so they do not have to fill in their credentials every time they use the app..
according to Link ? we can use account manager or oath2. I am still not sure of which methods i can use.. I simply want the user to enter a username and a password once.. I came across other methods but I am looking for the best method to be used.
You can use this function to save username and password
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences shared = getSharedPreferences("shared", MODE_PRIVATE);
if(shared.contains("username") && shared.contains("password")){
startingActivity();
} else {
saveInformation(userId,pass);
}
}
public void saveInformation(String username,String password) {
SharedPreferences shared = getSharedPreferences("shared", MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.commit();
}

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

Categories

Resources