I can't obtain data from SharedPreferences.. After I click on a button, it executes AsyncTask in a different class named Background.
public class Background extends AsyncTask<Integer,Void,String>{
private Context context;
private AsyncResponse listener;
public Background(Context context,AsyncResponse listener) {
this.context = context;
this.listener=listener;
}
AsyncResponse is an interface that I've created to inform my MainMactivity that background work has been finished. It's just:
package com.example.pablo.zad3;
public interface AsyncResponse {
void TaskCompleted();
}
Then I want to pass the result to SharedPreferences:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
SharedPreferences prefs = this.context.getSharedPreferences("MyPrefs",Context.MODE_PRIVATE);
prefs.edit().putString("A", s);
prefs.edit().commit();
listener.TaskCompleted();
}
But in my MainActivity I can't get the resulting string, it's like there was no A key in SharedPreferences (I always get "NO DATA"):
#Override
public void TaskCompleted() {
SharedPreferences prefs = this.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
if(prefs != null) {
String text = prefs.getString("A", "NO DATA");
editText2.setText(text);
}
}
I don't know what I'm doing wrong, can u help me?
The problem are those two lines:
prefs.edit().putString("A", s);
prefs.edit().commit();
at the first one you are opening SharedPreferences for edit and do the changes ...
now at the second line you are opening it again ... which causing the previous changes rollback ...
As the "family" of putXXX(...) method of the SharedPreferences.Editor class returns Editor itself you should do something like:
prefs.edit().putString("A", s).putXXX(...).putXXX(...).commit();
(by putXXX(...) I mean puting other preferences fx putInt("Z", 666))
now the changes will be saved
Use this for writing to preferences:
//Write to preferences
String s = "this is a test.";
SharedPreferences prefs = this.getSharedPreferences("MyPrefs",this.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("A", s);
editor.apply();
And this for retrieving information
//Fetch from preferences
SharedPreferences prefs2 = this.getSharedPreferences("MyPrefs", this.MODE_PRIVATE);
if(prefs2 != null) {
String text2 = prefs.getString("A","");
Log.d(LOG_TAG, "This is the string: "+text2);
}
The only thing that you missed is an editor.
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'm trying to store type of user string in Shared Preferences in an Activity, but when i try to getString from Shared Preferences in a service class in this case myFirebaseInstanceIDService it keeps giving me a Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference error.
Here is where i am putting the value
btNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterTutorActivity.this, ChooseSub.class));
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
sharedPref.edit().putString("Type", "Tutor").apply();
signUpTutor();
}
});
and in myFirebaseInstanceIDService
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private FirebaseAuth mAuth = FirebaseAuth.getInstance();
private String type;
SharedPreferences sharedPref;
#Override
public void onTokenRefresh() {
super.onTokenRefresh();
if(mAuth.getCurrentUser() != null)
{
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
sendRegistrationToServer(refreshedToken);
}
}
public void sendRegistrationToServer(String refreshedToken)
{
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
type = sharedPref.getString("Type", "");
FirebaseDatabase.getInstance().getReference().child("Users").child(type).child(mAuth.getCurrentUser().getUid())
.child("tokenID").setValue(refreshedToken);
}
}
I don't really now what i'm doing wrong with the Shared Preferences?
You can store the token in Shared Preferences until you app is ready to consume it:
SharedPreferences sharedPref = getSharedPreferences( getPackageName() + "_preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.edit().putString("Type", "Tutor");
editor.commit();
signUpTutor();
You can request for the token like this:
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("Type", Context.MODE_PRIVATE);
String type = sharedPref.getString("Type", null);
I made a class to make SharedPreferences operations easy. i am sharing it here hope it will help you out.
public class PreferenceUtils {
private SharedPreferences pref;
private SharedPreferences.Editor editor;
public PreferenceUtils(Context context) {
pref = PreferenceManager.getDefaultSharedPreferences(context);
}
public void setPrefrences(String key, String value) {
editor = pref.edit();
editor.putString(key, value);
editor.apply();
}
public void setPrefrences(String key, int value) {
editor = pref.edit();
editor.putInt(key, value);
editor.apply();
}
public void setPrefrences(String key, boolean value) {
editor = pref.edit();
editor.putBoolean(key, value);
editor.apply();
}
public String getPrefrence(String key, String Default) {
return pref.getString(key, Default);
}
public int getPrefrence(String key, int Default) {
return pref.getInt(key, Default);
}
public boolean getPrefrence(String key, boolean Default) {
return pref.getBoolean(key, Default);
}
public void deletePref(String[] key) {
editor = pref.edit();
for (int i = 0; i < key.length; i++)
editor.remove(key[i]);
editor.apply();
}
public void deletePref(String key) {
editor = pref.edit();
editor.remove(key);
editor.apply();
}
}
now where ever you want to use SharedPreferences, just initialize this class there.
for Activity,
PreferenceUtils utils = new PreferenceUtils(classname.this);
for Fragment,
PreferenceUtils utils = new PreferenceUtils(getActivity());
for service,
PreferenceUtils utils = new PreferenceUtils(getApplicationContext());
now for saving values you simply have to use object of PreferenceUtils class,
for example in your case,
utils.setPrefrences("Type", "Tutor");
and you can easily get value with that object too,
utils.getPrefrence("Type", null);
Happy Coding.
Ok So i figured out my problem thanks to everyone. I created a MyApplication class that extends Application and created a getContext method. And now it works. Thank you for helping me.
While Writing data in shared preferences use commit() instead of apply()
sharedPref.edit().putString("Type", "Tutor").commit();
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...
Hi I'am new to android.
I want to create a shared preferences when the app is first installed and the insert some data.
The shared preference has to be used from all activities in the app.
I tried creating the shared preference in the onCreate() function of the first activity and inserted values into it.And edited the data from another activity.
But when I restart the app the shared preference changes to the data give in the
onCreate().
Can somebody help me?
The way if you want to insert data once:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences preferences = getSharedPreferences("myPref", MODE_PRIVATE);
boolean shouldInsertData = preferences.getBoolean("shouldInsertData", true);
if(shouldInsertData){
//insert your data into the preferences
preferences.edit().putBoolean("shouldInsertData", false).apply();
}
}
Share Preference is best way to store short information. but if you will create share preference from an active, it may create problem to access it from other activity.
You should create a global common share preference from application so you can access it through out the android project, any where in any activity.
I get reference from here -
It is 4 step process.
Step 1- create a java class file name as "myapp" and extend it by application.
public class MyApp extends Application {
private static Context context;
private String TAG ="myApp";
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
// Log.e(TAG, " myapp stater");
}
public static Context getContext(){
return context;
}}
Step 2 - in android manifest file inside application tab add android:name=".myapp"
Step 3 - Create java class name as "SharePreferenceUtils" (note don't use name SharePreference.)
public class SharePreferenceUtils {
private static String PREFERENCE_NAME = "shopeasy-ecommerce";
private static SharePreferenceUtils sharePreferenceUtils;
private SharedPreferences sharedPreferences;
private SharePreferenceUtils(Context context){
PREFERENCE_NAME = PREFERENCE_NAME + context.getPackageName();
this.sharedPreferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
}
public static SharePreferenceUtils getInstance(){
if (sharePreferenceUtils == null){
sharePreferenceUtils = new SharePreferenceUtils(SplashActivity.getContext());
}
return sharePreferenceUtils;
}
// login response user_id 1234
public void saveString(String key, String Val ){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, Val);
editor.commit();
}
public String getString(String key, String defVal){
return sharedPreferences.getString(key, defVal);
}
public String getString(String key){
return sharedPreferences.getString(key, "");
}
public void saveInt(String key, int Val ){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, Val);
editor.commit();
}
public int getInteger(String key){ return sharedPreferences.getInt(key, 0 ); }
/**
* Clear all values from this preference
*/
public void clear() {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
/**
* Clear value of given key from this preference
*
* #param key name of the key whose value to be removed
*/
public void clearString(String key) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove(key);
editor.commit();
}}
Step 4 Call sharePreferenceUtil from activity
SharePreferenceUtils.getInstance().saveString("Username", "username value here");
Now you can access sharepreference from any activity. Just call instance of sharepreference java class.
I have to implement a functionality in which I have to store multiple id's in SharedPreferences in an application in android. I have to perform three main operations on data in preferences
1. add and save new id
2. delete a particular id
3. check if id exists
I wrote following class to perform all operations needed.
public class PreferenceUtils {
Context context;
private static final String TAG = PreferenceUtils.class.getName();
private static final String FAVOURITES = "favourites";
SharedPreferences preferences;
SharedPreferences.Editor editor;
public PreferenceUtils(Context context) {
this.context = context;
preferences = PreferenceManager.getDefaultSharedPreferences(context);
editor = preferences.edit();
}
public void save(long id) {
Set<String> prefStrings = preferences.getStringSet(FAVOURITES, new HashSet<String>());
prefStrings.add(id+"");
editor.putStringSet(FAVOURITES, prefStrings);
editor.commit();
editor.clear();
Log.d(TAG,id + " saved");
}
public void delete(long id) {
Set<String> prefStrings = preferences.getStringSet(FAVOURITES, new HashSet<String>());
prefStrings.remove(id + "");
editor.putStringSet(FAVOURITES, prefStrings);
editor.commit();
editor.clear();
Log.d(TAG,id + " deleted");
}
public boolean isExists(long id) {
final Set<String> prefStrings = preferences.getStringSet(FAVOURITES, new HashSet<String>());
return prefStrings.contains(id+"");
}
public Set<String> getAll() {
return preferences.getStringSet(FAVOURITES, new HashSet<String>());
}
public void clearHistory() {
editor.clear();
editor.commit();
}
}
I am creating instance of PreferenceUtils class from MainActivity like this:
PreferenceUtils pref = new PreferenceUtils(getApplicationContext());
Now the problem is when I am saving few values in preferences and closing application using back button or a Quit button (which will finish() MainActivity) everything is working fine and I am getting all the values from preferences. However, if I am force closing the application and reopening it I am getting only the first value I saved and rest all values are lost.
Try to remove the editor.clear() in both save and delete.this might be your problem.