Using SharedPreference to save user details - android

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();
}
});
}
}

Related

How can I store values from an activity so that I can use them later?

I would like to store a few values from an Activity so that when I navigate away from the activity, they still appear there.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
Button AddButton = (Button) findViewById(R.id.AddButton);
AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText firstNumEditText = (EditText) findViewById(R.id.firstNumEditText);
EditText secondNumEditText = (EditText) findViewById(R.id.secondNumEditText);
TextView ResultTxtView = (TextView) findViewById(R.id.ResultTxtView);
int num1 = Integer.parseInt(firstNumEditText.getText().toString());
int num2 = Integer.parseInt(secondNumEditText.getText().toString());
int result = num1 + num2;
ResultTxtView.setText(result + "");
}
});
In this case, I only want to save the values of num1, num2 and result. I would like it so that if I navigate back to the main menu, or if I go and do some other app and come back tomorrow, that the values would still be there.
You can store these values by using SharedPreferences.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
Button AddButton = (Button) findViewById(R.id.AddButton);
AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText firstNumEditText = (EditText) findViewById(R.id.firstNumEditText);
EditText secondNumEditText = (EditText) findViewById(R.id.secondNumEditText);
TextView ResultTxtView = (TextView) findViewById(R.id.ResultTxtView);
int num1 = Integer.parseInt(firstNumEditText.getText().toString());
int num2 = Integer.parseInt(secondNumEditText.getText().toString());
int result = num1 + num2;
ResultTxtView.setText(result + "");
// You can store these values here
// ...
}
});
protected void onResume() {
// And read these values here and set to your ResultTxtView.
// ...
}
You can use shared preferences in your app for saving the data and for using the same data later as mentioned below:
SharedPreferences sp = getSharedPreferences("Data",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name", "Alex");
editor.putString("Email", "alex#gmail.com");
editor.commit();
And then if you want to get the same data in another activity you do this as mentioned below:
SharedPreferences sp= ActvivityA.this.getSharedPreferences("Data",Context.MODE_PRIVATE);
String name = sp.getString("Name");
String email = sp.getString("Email");
This data will be saved till you will not clear the cache of the application or you will not install a new update of the app so in this way you can use this data anywhere in the app.
In this case, I only want to save the values of num1, num2 and result. I would like it so that if I navigate back to the main menu, or if I go and do some other app and come back tomorrow, that the values would still be there.
When you need the values to be persisted across app launches, then Shared Preferences or a data store like SQLite/Room would be the way to go.
Shared Preferences : If the values stored are key value pairs and are limited in size and does not have to scale, then Shared Preference would suit your need.
SqLite : If the data that you store would scale and would become larger in time, then you need to look at a data store like SQLite where you can do Async operations.
create on class which extends Application and create variable to hold specific value and register that class in manifest
in manifest in application tag specify your application class name
public class MyApplication extends Application {
private MyApplication sInstance;
int result;
//write getter setter for result variable same for num1 and num2
#Override
public void onCreate() {
super.onCreate();
sInstance = this;
}
public static MyApplication getInstance() {
return sInstance;
}
}
in onClick set that variable value like MyApplication.getInstnce().setResult();
and in onCreate of set textview value with MyApplication.getInstance().getResult();
Use Following methods for save/retrieve string using SharedPreferences
public static int getIntPreferences(Context context,String key) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
int savedPref = sharedPreferences.getInt(key, null);
return savedPref;
}
public static void saveIntPreferences(Context context,String key, int value) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
Save num1,num2 and result using saveIntPreferences when you leave 1st Activity.
After getting back on 1st Activity, you can get saved value using getIntPreferences

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: how to restore android listview state on app launch

how does one save a clicked state in android listview after exiting the app and restore state on app launch.The app should be able to listen to click event on listview and save the state and when the app is closed it saves the clicked state and then restore it on relaunch.
i have tried using getView but it doesnt seem to work as expected. please help
What you have to do is, you have to override the below method in your Activity,
#Override
public void onBackPressed() {
super.onBackPressed();
}
And save the state of your Button using SharedPrefrence, and next time when you enter your Activity get the value from the Sharedpreference and set the enabled state of your button accordingly.
Example,
private void SavePreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("state", button.isEnabled());
editor.commit(); // I missed to save the data to preference here,.
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Boolean state = sharedPreferences.getBoolean("state", false);
button.setEnabled(state);
}
#Override
public void onBackPressed() {
SavePreferences();
super.onBackPressed();
}
onCreate(Bundle savedInstanceState){
LoadPreferences();
//just a rough sketch of where you should load the data
}

disable buttons permanently throughout the aplication in android

Actually i have 3 buttons.User should click on any one button then all the 3 buttons should disable permanently throughout the app(when we close and open the app, buttons should be in disable state).How can i achieve this?
Thanks in advance.
define the behavior in SharePreferences:
for example use this in onResume:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
boolean enabled = pref.getBoolean("isEnabled",true);
myButton.setEnabled(enabled);
in onClick event of the button do this:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
pref.edit().putBoolean("isEnabled",false).commit();
myButton.setEnabled(false);
Use shared preference to store the clicked state of button.And check the preference value each time in activity/ fragment and disable or enable as per preference value.
you need to save your button state in sharedpreferences and based on your condition you need to enable / disable it in your activity code.
if(stateofbuttonfromprefs) {
button.setEnabled(false);
} else {
button.setEnabled(true);
}
You can use SharedPreference for your purpose. For more information refer this
declare SharedPreference before onCreate method
SharedPreferences stateButton;
SharedPreferences.Editor bEditor;
initialize this on onCreate()
stateButton= getApplicationContext().getSharedPreferences("Button_State", 0);
bEditor = stateButton.edit();
add these two methods on your activity
public void setBState(boolean e) {
bEditor.putBoolean("btn_state", e);
bEditor.commit();
}
public boolean getButState(){
return stateButton.getBoolean("btn_state", true);
}
call this to know your button state call
but.setEnabled(getBState());
when you need to disable the button, use
setBState(false);
On Button click
button_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences();
prefs.edit().putBoolean("btn_click", true).commit();
}
});
In Activity OnCreate method
Boolean btnClick= prefs.getBoolean("btn_click", false);
if(btnClick){
//Disable Button
}else{
//Enable Button
}

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