In my app, I am trying to save a key value as zero or one depending on whether a checkbox is checked. I retrieve these values in a different activity. However, when I attempt to retrieve the value, I am getting an empty string:
Saving key values in Activity 1(ScienceCoursesCheck):
public void setDefaults(String key, String value) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(key, value);
editor.commit();
}
public void onCheckboxClicked(View view) {
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.checkBox_APBio:
if (checked) {
setDefaults("APBio", "1");
}
else {
setDefaults("APBio", "0");
break;
}
}}
Retrieving key values in activity 2(MyHome):
public static String getDefaults(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
public void myMethod() {
SharedPreferences myPrefs = getSharedPreferences("ScienceCoursesCheck", MODE_PRIVATE);
String APBio = myPrefs.getString("APBio","");
if (APBio.equals("1")){
Button myButton = new Button(this);
myButton.setText(APBio);
RelativeLayout ll = (RelativeLayout)findViewById(R.id.activity_my_home);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
}
}
Is the second activity accessing the correct SharedPreferences file?
Use the following code for sharedpreference. Call
Util.saveInfo(activityContext,_key,_value)
when you want to save the info. Then call
Util.getInfo(getApplicationContext(),_key)
to get the info.
public class Util{
public static void saveInfo(Context context, String key, String value )
{
try
{
PreferenceManager.getDefaultSharedPreferences(context).edit().putString(key, value).apply();
}
catch (Exception ex)
{
Log.e(TAG," saveInfo "+ex+"");
}
}
public static String getInfo(Context context, String key)
{
try {
return PreferenceManager.getDefaultSharedPreferences(context).getString(key,"");
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
The issue is because when you store the items in SharedPreferences you are using
PreferenceManager.getDefaultSharedPreferences
but when you retrieve them you are using
getSharedPreferences("ScienceCoursesCheck", MODE_PRIVATE);
These are two different SharedPreferences files. Try using getSharedPreferences("ScienceCoursesCheck", MODE_PRIVATE); for your setting method as well. Or perhaps you meant to use your getDefaults() method in activity 2 instead of myPrefs
That is because you are saving in the DefaultSharedPreferences file
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
and retrieving from another file named "ScienceCoursesCheck"
SharedPreferences myPrefs = getSharedPreferences("ScienceCoursesCheck", MODE_PRIVATE);
and they are not the same file!
See the difference between getSharedPreferences and getDefaultSharedPreferences in this answer
====
Solution is either to always use DefaultSharedPreferences OR always use the file named "ScienceCoursesCheck" .
The problem is you're saving the values in the DefaultSharedPreference and trying to retrieve the values from the ScienceCoursesCheck preference file.
Try below code for setDefaults method.The getDefaultSharedPreference and getSharedPreference methods are different.
See this link for the difference.
public void setDefaults(String key, String value) {
SharedPreferences sharedPref = getApplicationContext().getDefaultSharedPreferences("ScienceCoursesCheck", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(key, value);
editor.commit();
}
Hope this helps you...
Related
I want to clear the data I am getting from SharedPreference, I try the following answer but didn't make my task:
1) how to delete sharedpreferences ,Quit and launch application from first actvity in android
2) clear the value of sharedpreferences
3) Remove Shared preferences key/value pairs
4) SharedPreferences Clear/Save
they are all removing value, after they write data into SharedPreference, like editor.remove and .clear...
I have write data into SharedPreference in Notification Activity Like this:
public static final String PREFS_NAME = "com.example.sociapp";
NotificationAdapter notificationAdapter1 = new NotificationAdapter(NotificationsActivity.this, NotificationList, NKeyList);
RnotificationList.setAdapter(notificationAdapter1);
isthereItem = notificationAdapter1.getItemCount();
Toast.makeText(NotificationsActivity.this, ""+isthereItem, Toast.LENGTH_SHORT).show();
//writing data into SharedPreference
SharedPreferences.Editor editor = settings.edit();
editor.putInt("changingicon",isthereItem);
//editor.commit();
editor.clear();
editor.apply();
And I am getting this int value in MainActivity Like this:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
// Reading from SharedPreferen
try {
//all I want to refresh below line everytime I start MainActivity.
int ChangeIcon = settings.getInt("changingicon", 0);
if (ChangeIcon == 0)
{
int valuebecomes = 0;
notificationIconSetting(valuebecomes);
}
else
{
int valuebecomes = 1;
notificationIconSetting(valuebecomes);
}
Toast.makeText(MainActivity.this, ""+ChangeIcon, Toast.LENGTH_SHORT).show();
}
catch (ClassCastException e){e.printStackTrace();}
The method I call, when I get int value from SharedPreference:
private void notificationIconSetting(int IconTochange)
{
if (IconTochange == 0) {
navigationView.getMenu().getItem(2).setIcon(R.drawable.notification);
}
else
{
navigationView.getMenu().getItem(2).setIcon(R.drawable.notificationalert);
navigationView.setItemIconTintList(null);
}
}
Actually I am getting an int value greater than 0 when there is a notification in the adapter, and when there is no notification in the adapter the int value is equal to 0, then I am using this value to change the notification icon.
When there is notification:
When there is no notification:
Now the problem is whenever I get a value, it remains the same until I clear app cache or Uninstall and then install again.
All I want to refresh the SharedPreference value every time I start MainActivity.
You want to remove one key/value from shared preference
here's how i do it.
public void clearSpecificKey(String key){
sharedPreferences.edit().remove(key).apply();
}
Few things to note :
You should create a generic class of Shared Preference Like below
public class SharedPrefs {
private static final String MY_PREFS_NAME = "YOUR-PREFERENCE-NAME";
private static SharedPreferences sharedPreferences;
private String masterKeyAlias;
public SharedPrefs(Context context) {
{
try {
masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
} catch (GeneralSecurityException | IOException e) {
e.printStackTrace();
}
}
try {
sharedPreferences = EncryptedSharedPreferences.create(MY_PREFS_NAME,masterKeyAlias,context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM);
} catch (GeneralSecurityException | IOException e) {
e.printStackTrace();
}
}
public String getStrings(Context mContext, String key){
return sharedPreferences.getString(key, null);
}
public void putString(Context mContext, String key, String value ){
sharedPreferences.edit().putString(key, value).apply();
}
public boolean getBoolean(Context mContext, String key){
return sharedPreferences.getBoolean(key, false);
}
public void putBoolean(Context mContext, String key, boolean value ){
sharedPreferences.edit().putBoolean(key, value).apply();
}
public static void clear(Context mContext){
sharedPreferences.edit().remove("user").apply();
}
public void clearSpecificKey(String key){
sharedPreferences.edit().remove(key).apply();
}
}
Here how to use it
Declaration :
SharedPrefs sharedPrefs;
Initialization :
sharedPrefs = new SharedPrefs(context);
just call the methods you want to use to store value in shared preference like
sharedPrefs.putString(context,key,value)
masterKeyAlias is to secure my Shared preferences.
Add this your app gradle
implementation "androidx.security:security-crypto:1.0.0-beta01"
you can read more about it here Best Practices
I use SharedPreferences in my app to save small Integer data . But I get ClassCastException in this line .
int number = mySharedPref.getInt("numberOne",0);
Here is my code .
To store data .
mySharedPref=getSharedPreferences("MyPref",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mySharedPref.edit();
editor.putInt("numberOne",myInteger);
To get data
mySharedPref = getSharedPreferences("MyPref",Context.MODE_PRIVATE);
int number= mySharedPref.getInt("numberOne",0);
display(number);
I think the problem is that you have not committed the data stored in SharedPreferences.
So you should do a
editor.commit();
while storing the data.
Try this
To Store data
public static void setInteger(Context context, String key, Integer Value) {
sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences.Editor sEdit = sharedPreferences.edit();
sEdit.putInt(key, Value);
sEdit.commit();
}
To get data
public static Integer getInteger(Context context, String key) {
sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
Integer value = sharedPreferences.getInt(key, 0);
return value;
}
You have to call commit() method to save data changes in SharedPreferences.
Here is the get data method
private void showData() {
SharedPreferences sharedPreferences = getSharedPreferences("MyFile", Context.MODE_PRIVATE);
int number = sharedPreferences.getInt("numberOne", 0);
display(number);
}
Here is get savemethod
private void saveData(int value) {
SharedPreferences sharedPreferences = getSharedPreferences("MyFile", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("numberOne", value);
editor.commit();
}
Help please, I'm a bit lost, new to all this and trying to learn.
I want to store 3 names and phone numbers in SharedPreferences and display them in individual textviews so a user can edit the name and phone number and also press the number to call the number.
What I have so far is:
public void setWardenName(Context context, String key, String value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(getString(R.string.), Name);
editor.apply();
}
public void getWardenName(Context context, String prefKey) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name", "");
if(!name.equalsIgnoreCase(""))
{
name = name;
}
}
And on the activity screen I have the first texview called:
android:id="#+id/textView2" which was going to be the first name.
So I'm lost, any help is appreciated.
I will set the Warden as your key name and it depends on you if you want to change that. And, I will assume that it is in the same class since you are using 'this' in
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
So here it is..
private void setWarden(String value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = sharedPref.edit();
editor.putString("Warden", value);
editor.commit();
}
private String getWarden() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = sharedPref.getString("Warden", "");
if(!name.equalsIgnoreCase(""))
{
return name;
}
return "";
}
And in your textview you can get it like:
TextView tv = (TextView) findViewById(R.id.textView2);
tv.setText(getWarden());
I have an app that basically looks like the design in the attached picture.
As you can see, there are 4 activities, and some of the activities have fragments.
I want to get the answer of a test back to the user's profile.
Up to now, I've been uploading the result to the server and having the app update the user's profile every time they go back to the ProfileActivity, but that seems like a waste of resources.
Is there a pattern or way to do this in the app?
I looked at this: which seems doable if I can somehow link two startActivityForResult()s.
I looked into using the delegate pattern described in this question but I can't get the instance of the UserFragment to the TestActivity.
I hope someone can point me in the direction of the correct way of doing this.
One approach is use startActivityForResult() don't finish any Activity
start all activities by startActivityForResult() then depending on your condition you can finish activity
pass result back to the previous activity using onActivityResult()
Then for fragment you can store fragment object in ProfileActivity .
In Fragment write method for updating UI
So you can access that method using fragment object
class ProfileActivity extends ......
{
#override
public void onActivityResult(....)
{
.....
frgamnetObject.updateUI();
....
}
}
Assuming that you are getting one int value from last page:
create class :
public class GenericUtility {
public static int getIntFromSharedPrefsForKey(String key, Context context)
{
int selectedValue = 0;
SharedPreferences prefs = context.getSharedPreferences("com.your.packagename", Context.MODE_PRIVATE);
selectedValue = prefs.getInt(key, 0);
return selectedValue;
}
public static boolean setIntToSharedPrefsForKey(String key, int value, Context context)
{
boolean savedSuccessfully = false;
SharedPreferences prefs = context.getSharedPreferences("com.your.packagename", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
try
{
editor.putInt(key, value);
editor.apply();
savedSuccessfully = true;
}
catch (Exception e)
{
savedSuccessfully = false;
}
return savedSuccessfully;
}
public static String getStringFromSharedPrefsForKey(String key, Context context)
{
String selectedValue = "";
SharedPreferences prefs = context.getSharedPreferences("com.your.packagename", Context.MODE_PRIVATE);
selectedValue = prefs.getString(key, "");
return selectedValue;
}
public static boolean setStringToSharedPrefsForKey(String key, String value, Context context)
{
boolean savedSuccessfully = false;
SharedPreferences prefs = context.getSharedPreferences("com.your.packagename", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
try
{
editor.putString(key, value);
editor.apply();
savedSuccessfully = true;
}
catch (Exception e)
{
savedSuccessfully = false;
}
return savedSuccessfully;
}
}
than to set int value to it:
GenericUtility.setIntToSharedPrefsForKey("selected_theme", 1, getApplicationContext());
or
GenericUtility.setIntToSharedPrefsForKey("selected_theme", 1, MyActivity.this))
and in your very first activity where you want result:
int selectedValue = GenericUtility.getIntFromSharedPrefsForKey("selected_theme", getApplicationContext());
or
int selectedValue = GenericUtility.getIntFromSharedPrefsForKey("selected_theme", MyActivity.this);
selectedValue will return default value if there is no value in it.
PS change int to String in class to get and set result accordingly.
I have try to set and store the password for my apps, but it is not working at all. The password should be setted first time then return the home page, then when the user open it again the password should be stored but somehow it didn't store it.
PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences passfile = getSharedPreferences("ans",0);
String pass = passfile.getString("ans", null);
check.setOnClickListener(new OnClickListener () {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String answer1 = answer.getText().toString();
//Check that user typed in an answer
if(answer1.length()<8){
Toast.makeText(CheckPwActivity.this, "Answer must be 8 characters long", Toast.LENGTH_SHORT).show();
answer.setText("");
answer.requestFocus();
return;
}
answer.getEditableText().toString();
//check if the answer is valid
if (answer1.equals("ans")) {
Intent intent2 = new Intent(CheckPwActivity.this,MainActivity.class);
startActivity(intent2);
}else{
return;
}
}});
}
public void setPassword(String key, String value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
Editor preferenceEditor = context.getSharedPreferences("password", 8).edit();
preferenceEditor.putString(key, value);
preferenceEditor.commit();
}
public static String getPassword(String filename) {
return context.getSharedPreferences("password", 2).getString(filename,"");
}
you are using shared preferences wrong, in your set password you get shared preferences but then you get it again but in a different context
this is all you need to use shared preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
then when you want to set it you use the editor you just got
editor.putString(key,pass).commit;
then to get it from shared preferences you would just do
preferences.getString(key,defaultString);