On my SettingsActivity i am saving a value with the following code:
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("ClassName", strArrClasses.get(i));' // i is a variable inside a loop
int intClassID = i+1;
editor.putInt("ClassID", intClassID);
editor.commit();
I'm now trying to get the value of the SharedPreference with the Key "ClassID" on my MainActivity with the following code:
SharedPreferences sharedPrefs = getPreferences(MODE_PRIVATE);
int intClassID = sharedPrefs.getInt("ClassID", 543548564);
My problem now is that I cant access the class ID and I am always getting the default value.
Edit:
I already checked if i can get the ClassID on my SettingsActivity and that works well
use getSharedPreferences instead. Like
SharedPreferences sharedPrefs = getSharedPreferences(name, MODE_PRIVATE);
as from document here
getPreferences retieves a SharedPreferences object for accessing
preferences that are private to this activity. This simply calls the
underlying getSharedPreferences(String, int) method by passing in this
activity's class name as the preferences name.
and getSharedPreferences retrieve SharedPreference by the name.
In your case you used getPreferences which returned SharedPreferences of those activities only.
Related
My Android app stores 15-20 settings pairs with SharedPreferences, and I've been using a helper class so I don't have to create a new method in every class that needs to retrieve them.
Some retrievals are starting to take >100ms, and I'm not sure my current method is efficient for performance since it passes in the Context and creates a new SharedPreferences object each time. This happens numerous times throughout the app's AsyncTasks.
Here's what I've been doing:
public class SharedPrefHelper {
static void setDefaults(String key, String value, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value);
editor.apply();
}
static void setDefaultsInt(String key, int value, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(key, value);
editor.apply();
}
//... continued with other variable types and getDefault variants
//.......
}
Would below be a more efficient way of handling this?
public class SharedPrefHelper {
private static SharedPreferences preferences;
static void init(#NonNull final App app) {
preferences = PreferenceManager.getDefaultSharedPreferences(app);
}
//App is the Application class, init is called in onCreate()
static void setDefaults(String key, String value) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value);
editor.apply();
}
//... continued with other variable types and getDefault variants
//.......
}
Or are there other variable keywords that would do better (final, etc)?
+100ms is a long time for such a simple action and so little key-value pairs.
I think the problem is not here.
However, to answer your question, yes, the proposed alternative is certainly better than the original one. Indeed, there is no point in calling getDefaultSharedPreferences(context) multiple times, as that method points to a default file, which is set application-wide.
So just store it as instance/static field (but avoid static as much as possible).
preferences.edit()
returns a new, fresh, Editor (EditorImpl, it maintains a Map of the changed key-value pairs and then persist everything on apply) every call, so you're totally fine.
I'm trying to send integer value from activity to a fragment to change text size value, Iv tried user bundle and custom constructor and didn't work.
So how can I use shared preferences for this purpose?
Hey have you tried something like this
Bundle bundle=new Bundle();
bundle.put('key',0);
FragmentName name=new FragmentName();
name.setArguements(bundle);
Integer q=getArguments.getInt(key)
If you insist on shared preference use this code :
To save the data
private void saveSp(String key , String value){
PreferenceManager.getDefaultSharedPreferences(Context)
.edit()
.putString(key, value).apply();
}
To get your data:
PreferenceManager.getDefaultSharedPreferences(Context).getString("string", "default")
I have a boolean variable public static boolean isInDarkTheme but when I try to change the value in my settings activity it only gets changed tempolarily.
I did it so:
if (on) {
//Do something when Switch button is on/checked
MainActivity.isInDarkTheme = true;
} else {
//Do something when Switch is off/unchecked
MainActivity.isInDarkTheme = false;
}
Log.d("DarkTheme", "SETTINGS " + MainActivity.isInDarkTheme);
in my settings the variable is changed but when I go back to my main with the
arrow I created with this:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
picture with this button
it is still the same in the main
but! when I use my software key to get back to the MainActivity it get saved
picture with software back key
Any idea what I can do that it get saved with the other button?
your variable will not be saved and will be collected by garbage collector once the activity is destroyed.
you have to use something like SharedPreferences.
to save the variable
SharedPreferences sharedPrefrences = getSharedPreferences("pref_name", MODE_PRIVATE);
sharedPrefrences.edit().putBoolean("isDarkTheme", true).apply();
to load
SharedPreferences sharedPrefrences = getSharedPreferences("pref_name", MODE_PRIVATE);
// key , default value
boolean isDark= sharedPrefrences.getBoolean("isDarkThem", false);
read about SharedPreferences here
The most likely reason is that both activities are loaded by different class loaders with the effect that the MainActivity you "see" in your Settings activity is a different one than the one you "see" in your other activity. You can find that out by logging the classloader "attached" to the MainActivity by calling MainActivity.class.getClassLoader()
I have two instances of shared preferences in my activity class. One instance I'm using to retrieve data that is already stored in shared preferences. The other instances I'm trying to store new sets of data, into a different file, that I'm retrieving from api. Can we do that because null values are being stored in the shared preferences.
Here is a part of my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);){
..........
SharedPreferences sharedPreferences = getSharedPreferences("User",Context.MODE_PRIVATE);
email = sharedPreferences.getString("email",DEFAULT);
//some piece of code........
setdata();//in this method I'm initializing the variables
SharedPreferences sharedPreferences2 = getSharedPreferences("File",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences2.edit();
editor.putString("a",a);
editor.putString("b",b);
editor.putString("c",c);
editor.putString("d",d);
editor.putString("e",e);
editor.commit();
}
public void setData(){
a="hello";
b="world";
c="hello";
d="world";
e="hello";
}
All these are in my onCreate method of my activity class.
a,b,c,d,e are global variable which I'm initializing in some other method of the class. I'm making the method call in onCreate method before implementing the shared preferences. But null values are being stored.
You have answered you question... The code you have posted is in onCreate method of your activity and a,b,c,d,e are global variables.
So they have null values when the activity starts.
You need to execute the code to save the values after you have initialized the value of a,b,c,d,e which is after receiving data from the API.
I'm writing my first android app, and I have an EditText object that I want to be read across my entire program (multiple activities). I'd like to take in a user's name on one screen/activity/layout and read it in several others to manipulate or display it, so I've found that the string needs to be public and static, and that there should be a class with my global variables. What is the correct way to do this? I've tried using bundles and several other methods, but none seem to work.
You should definitely be passing this value through intents.
Intent intent = new Intent(getApplicationContext(),NEXTCLASS.class);
intent.putExtra("username",mEditText1.getText().toString());
startActivity(intent);
and then to receive it in the next class
Bundle extras = intent.getExtras();
mEditText1.setText(extras.getString("username"))
You could also use shared preferences however I think that is unnecessary for your situation as you do not need the username to persist when the app is closed.
Update:
To use shared prefs..
SharedPreferences sharedPreferences = getSharedPreferences("myprefs", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", myusername);
To read from shared prefs...
SharedPreferences sharedPreferences = getSharedPreferences("myprefs", MODE_PRIVATE);
String username = sharedPreferences.getString("username", "");
An example of using a static property
public class utility {
public static String USERNAME = "username";
}
To invoke you do not need to instantiate the class just do this from each class that needs it
String username = sharedPreferences.getString(utility.USERNAME, "")
You can use SharedPreferences to store the value. Read more here.