Save string/EditText in memory android studio - java

I have a problem with save the value of string or editText in java android. When I redirect from FirstActivity to Second and return after it to First, I need that a String that i fill earlier stay in the place that I wrote it. (Like a cookies in js).

You could use shared preferences for this process.
In that case, Best practise to create SharedPreference and for global usage, you need to create a global class like below:
public class PreferenceHelper {
private final SharedPreferences mPrefs;
public PreferenceHelperDemo(Context context) {
mPrefs = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 -for private mode
}
private String PREF_Key= "Key";
public String getKey() { // To retrieve data
String str = mPrefs.getString(PREF_Key, null);
return str;
}
public void setKey(String pREF_Key) { // To store and edit Data
Editor mEditor = mPrefs.edit();
mEditor.putString(PREF_Key, pREF_Key);
mEditor.commit();
}
public void clearData(string pREF_Key){ // To delete data
editor.remove(pREF_Key);
editor.commit();
}
}
Then you could use these functions with global class in your activity class to store, retrieve and delete the shared preference data.
Hope this will solve your problem!

Related

Is this an efficient way to get/set multiple SharedPreferences in a singleton helper?

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.

SharedPreferences, Singleton Class - What should you use for calling, editing, saving and recalling two integer values

My app will carry two scores the entire time, calling them, adding to them, saving them, and later calling them back again for other functions and editing. What is the best method for this? These will be the only numbers needed throughout the app.
All I am looking for is the most efficient option I should implement. And if possible a simple example of making, editing, saving and recalling. Thank you.
I suggest using SharePreferences because you are only need to store very small data.
Hint:
synchronized void saveScores(final Context contex, final String scoreOneKey, final String scoreTwoKey, final Integer scoreOne, final Integer scoreTwo){
final SharedPreferences sharedPreferences = context.getSharedPreferences("user.score.key", Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS)
final SharedPreferences.Editor preferencesEditor = sharedPreferences.edit();
preferencesEditor.putInt(scoreOneKey, scoreOne);
preferencesEditor.putInt(scoreTwoKey, scoreTwo);
preferencesEditor.commit();
}
Things to Note here are:
You are method must synchronized as multiple threads can access the game score.
Notice the sharedPreference access controls (MODE_PRIVATE | MODE_MUTI_PROCESS) that tells the OS that this sharedPreference is not accessible by other apps but at same time it is possible to access it from multiple process of your app ( if you can even encrypt the scores before saving them.)
UpdatedYou can use SharedPreferences To save Scores When you will call getFirstScore() first Time it will return 0 as the variable is not yet created and then you can call setFirstScore() to save it.
public class ScoreDatabase{
private Context context;
private SharedPreferences pref;
private SharedPreferences.Editor editor;
public ScoreDatabase(Context context){
this.context=context;
pref = context.getSharedPreferences("MY_PREFS", Context.MODE_PRIVATE);
editor = pref.edit();
}
public int getFirstScore() {
return pref.getInt("FIRST_SCORE", 0);
}
public int getSecondScore() {
return pref.getInt("SECOND_SCORE", 0);
}
public void setFirstScore(int score) {
editor.putInt("FIRST_SCORE", score);
editor.commit();
}
public void setSecondScore(int score) {
editor.putInt("SECOND_SCORE", score);
editor.commit();
}
}
Now make instance of this class and use anywhere you want just pass getApplicationContext() in the constructor
//In your MainActivity class
ScoreDatabase scoreDatabase=new ScoreDatabase(getApplicationContext());
//call set function when you want to set score
scoreDatabase.setFirstScore(10);
scoreDatabase.setSecondScore(20);
//Call get function when you want to get score
int firstScore=scoreDatabase.getFirstScore();
int secondScore=scoreDatabase.getSecondScore();

Changing MainActivity in Java

I'm making a toggle button which changes activity but it changes only for once but want to make it permanent so user does not need to change it again and again.
Use Shared Preference for that . When user Toggle Button ON (logged) into your application store login status into sharedPreference and clear sharedPreference when user click on OFF(logged Out).
Check every time when user enter into application if user status from shared Preference is true then no need to login otherwise move to login page.
To achieve that first create one class, in that class you need to write all the function regarding get and set value in the sharedpreference . Please look at this below Code.
public class SaveSharedPreference
{
static final String PREF_USER_NAME= "username";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setUserName(Context ctx, String userName)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_USER_NAME, userName);
editor.commit();
}
public static String getUserName(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}
}
Now first check
if(SaveSharedPreference.getUserName(MainActivity.this).length() == 0)
{
// call Login Activity
}
else
{
// Call Next Activity
}

recommended way to store/restore user info in an android app

I made a Utils class where I have static properties and functions that serves my app. I also have the info of the user, such as name email etc., and 2 functions to store/restore this info, so in general it looks like this:
public class Utils {
static public int userId;
static public String name;
static public String email;
static public void writeData(Context context) {
SharedPreferences.Editor pref = context.getSharedPreferences("q", Context.MODE_PRIVATE).edit();
pref.putInt("userid", userId);
pref.putString("email", email);
pref.putString("name", name);
pref.commit();
}
static public void readData(Context context) {
SharedPreferences prefs = context.getSharedPreferences("q", Context.MODE_PRIVATE);
userId = prefs.getInt("userid", 0);
email = prefs.getString("email", "");
name = prefs.getString("name", "");
}
}
I don't need to explain the simplicity of the above but I was wondering if there is a more recommended/standard way to do this.
Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has chosen. If you're interested in creating user preferences for your application, see Preference Activity, which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences). Although, using SharedPreferences in your case is more than an okay way of storing simple data.

Android Activity not saving preferences?

I have a Settings activity in my android application which purpose is to save preferences upon an item selection. My problem is, my settings don't get saved. The following method is called every time a user selection is made:
public void savePreferences()
{
defaultVolumeUnit = MySingleton.getInstance().getDefaultVolumeUnit();
defaultPressureUnit = MySingleton.getInstance().getDefaultPressureUnit();
defaultTempUnit = MySingleton.getInstance().getDefaultTempUnit();
settings = getSharedPreferences(SettingsTAG, 0);
Editor editor = settings.edit();
editor.putInt("selectVolume", defaultVolumeUnit);
editor.putInt("selectPressure", defaultPressureUnit);
editor.putInt("selectTemperature", defaultTempUnit);
editor.commit();
}
I also use the following code in my MAIN activity where all the settings get restored upon start up:
public void restoreValues()
{
settings = getSharedPreferences(SettingsTAG, 0);
int SelectedVolume = settings.getInt("selectVolume", 0);
int SelectedPressure = settings.getInt("selectPressure", 0);
int SelectedTemperature = settings.getInt("selectTemperature", 0);
// Necessary assignments here...
}
I use global variables throughout my whole application and those get saved but the settings do not. I'm positive that both savePreferences() and restoreValues() method gets called but whatever the user had selected doesn't get saved.
In other words, nothing gets saved/restored. I don't know what I'm doing wrong but this issue has been driving me nuts. This used to work for me before but I'm doing a Settings UI revamp and the same code suddenly isn't working...
Any help please?
Think you should be doing this in your activity:
private SharedPreferences prefSettings;
public void restoreValues()
{
prefSettings = PreferenceManager.getDefaultSharedPreferences(this);
int SelectedVolume = prefSettings.getInt("selectVolume", 0);
int SelectedPressure = prefSettings.getInt("selectPressure", 0);
int SelectedTemperature = prefSettings.getInt("selectTemperature", 0);
// Necessary assignments here...
}
In your method that I've noticed, your parameters do not look right actually...why are you using SettingsTAG, with 0 as parameters to the getSharedPreference method? Is your activity extending PreferenceActivity? You should be using the context.
public void savePreferences()
{
defaultVolumeUnit = MySingleton.getInstance().getDefaultVolumeUnit();
defaultPressureUnit = MySingleton.getInstance().getDefaultPressureUnit();
defaultTempUnit = MySingleton.getInstance().getDefaultTempUnit();
//settings = getSharedPreferences(SettingsTAG, 0);
settings = PreferenceManager.getDefaultSharedPreferences(context); // Notice CONTEXT!
Editor editor = settings.edit();
editor.putInt("selectVolume", defaultVolumeUnit);
editor.putInt("selectPressure", defaultPressureUnit);
editor.putInt("selectTemperature", defaultTempUnit);
editor.commit();
}
Edit:
If you want to debug it, it might be better to do it this way:
public class PreferencesActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener{
private static final String TAG = "PreferencesActivity";
///.... code....
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key){
Log.d(TAG, "onSharedPreferenceChanged() - key = " + key);
// Yup! The key within the shared preferences was changed... inspect 'em via Log!
}
The reason: you're "listening" on the changes whenever its made to confirm that you are indeed saving the preferences. When you're done with debugging, be sure to take out the Log calls so that it does not appear in the logcat.

Categories