Shared Preferences Appearing On-Screen - android

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.

Related

My app stayed logged in even after restart

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.

Using SharedPreference to save user details

I understand that the best way to save values is to use SharedPreferences e.g.
SharedPreferences Savesettings = getSharedPreferences("settingFile", MODE_PRIVATE);
SharedPreferences.Editor example = Savesettings.edit();
example.putString("Name", name)
.putInt("Age", age)
.putInt("Score", score)
example.apply();
But what if I want my program to remember a button being disabled or enabled after the user closes and opens the program? i have tried a RegisterOnChangePreferanceListener however i have no luck e.g.
SharedPreferences Preferences= PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.OnSharedPreferenceChangeListener Example =
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences preferance, String key) {
Name = name;//only an example not the main focus
Age = age;
Score = score;
enableBTN = false; //disables button
Name.setEnabled(false); //disables the edit text from further editing
}
};
Preferences.registerOnSharedPreferenceChangeListener(Example);
Is there a way to do this, both methods do not seem to be working for me.
You need to save it from within the button's OnClickListener. That way, everytime the button is clicked, you are guaranteed that the button's state is saved. button is a reference to a Button view object
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle bundle) {
Button button = (Button)findViewById("this_button_view_id");
EditText editText = (EditText)findViewById("this_edit_text_id");
SharedPreferences Savesettings = getSharedPreferences("settingFile", MODE_PRIVATE);
// If the Savesettings shared preferences above contains the "isButtonDisabled" key
// It means the user clicked and disabled the button before
// So we use that state instead
// If it does does not contain that key
// We set it to true so that the button is not disabled
// Same for the edit text
button.setEnabled(Savesettings.contains("isButtonDisabled") ? Savesettings.getBoolean("isButtonDisabled") : true);
editText.setEnabled(Savesettings.contains("isEditTextDisabled") ? Savesettings.getBoolean("isEditTextDisabled") : true);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// disable the edit text
editText.setEnabled(false);
// disable the button
button.setEnabled(false);
SharedPreferences.Editor example = Savesettings.edit();
// Save the button state to the shared preferences retrieved above
example.putBoolean("isButtonDisabled", true);
// Save the edit text state to the shared preferences retrieved above
example.putBoolean("isEditTextDisabled", true);
example.apply();
}
});
}
}

Save and Load strings

I used Menu onOptionsItemSelect(MENU) to save and load strings like this
public static String filename = "MySharedString";
SharedPreferences someData;
String s;
someData = getSharedPreferences(filename, 0);
case R.id.save:
Toast.makeText(getApplicationContext(), "Samples saved", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor1 = someData.edit();
editor1.putString("ourString1", s);
and load like this
case R.id.load:
s = someData.getString("ourString1", "Couldn't Load Data");
and it worked well...as android removed MENU button for many devices i made a new activity which extends MainActivity and I put in Save and Load button.
public void bSave (View v){
SharedPreferences.Editor editor1 = someData.edit();
editor1.putString("ourString1", s);
editor1.commit();
and load
public void bLoad (View v){
s = someData.getString("ourString1", "Couldn't Load Data");
For some reason it doesnt work, I repeat i made new activity ( public class Menu extends MainActivity{ ) which i start as Intent and it wont save or load strings from MainActivity
make sure you are using the button listener properly. check if you set android:onClick attreibute like
android:onClick="bSave"

How setup default value Shared Preferences in an android apk?

I make a setup class with shared preferences and in the first open apk the user use the default value and after edit if he want it with update value. My problem is when re open the apk and no create preference apk display default value else if there is old preference display this. I want update preferences onCreate with old save preferences if preferences exist(no with default value). How I create this? I want something if pref exist go to share preference...and read value...else use the default
String strValue ="http://www.power7.net/LEDstate.txt";//default value
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ioweb_bt);
/* SharedPreferences preferences = getSharedPreferences("dataioweb" , MODE_PRIVATE);
String strValue = preferences.getString("Url","");
text = (TextView) findViewById(R.id.textUrl);
text.setText(strValue);
*/
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
edittxtUrl.setText(strValue);
}
public void Save(View view) {
SharedPreferences preferences = getSharedPreferences("dataioweb" , MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit(); // Put the values from the UI
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
String strUrl = edittxtUrl.getText().toString();
editor.putString("Url", strUrl); // value to store
// Commit to storage
editor.commit();
Change your code as for setting default value in TextView when user start your Application or any value not exist in SharedPreferences
SharedPreferences preferences;
String strValue="";
TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ioweb_bt);
text = (TextView) findViewById(R.id.textUrl);
preferences = getSharedPreferences("dataioweb" , MODE_PRIVATE);
strValue = preferences.getString("Url","");
if(!strValue.equals("")){
text.setText(strValue);
}
else{
text.setText("Set Default value here");
}
// your code here
In this way, you can get default value from preference if no value is their corresponding to your preference key
SharedPreferences preferences=getSharedPreferences(preferencename, MODE_PRIVATE);
String str=preferences.getString(key, defaultValue);

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