Android Saving of Strings - java

I'm wanting to save the value of strings (numeral Strings) to somewhere where i can when the user reloads the app, the values can be passed back into the app. Being saved to local storage is preferrable

I would suggest using shared preferences over a SQLLite DB if you are only saving a small amount of strings.
private void saveStringToPreferences(String key, String str){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, str);
editor.apply();
}
private void getStringFromPreferences(String key){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String previousText = preferences.getString(key, "");
return previousText;
}

You really should do some research before asking such a question. Here is a link to the options available for storing data in android:
http://developer.android.com/guide/topics/data/data-storage.html

Related

Save string/EditText in memory android studio

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!

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.

Why do i get the default value back?

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.

SharedPreferences don't work

i'm having little problems using the SharedPreferences. I want to save and later load strings to/from the Preferences.
I initialize my prefs in the onCreate-method:
prefs = this.getSharedPreferences("com.example.android_test", Activity.MODE_PRIVATE);
I do saving in another method:
public void saveUser()
{
prefs.edit().putString("username", username);
prefs.edit().putString("password", password);
prefs.edit().apply();
}
And loading in yet another method:
public void loadUser()
{
username = prefs.getString("username", "default");
password = prefs.getString("password", "test");
}
And those are my Test-Methods:
public void showUser(View v)
{
loadUser();
text.setText(username);
}
public void addUser(View v)
{
changeUser(eingabe.getText().toString(),"newpass");
}
public void changeUser(String user, String pass)
{
username = user;
password = pass;
saveUser();
}
username and password are global, private Strings, eingabe is an EditText and text is a TextView.
However, when executing showUser() i only get the defaultvalue displayed to the TextView, even if im using saveUser with different usernames... No crash or anything... its just only the defaultvalue being shown...
You forgot to commit your edits:
prefs.edit().putString("username", username).commit();
prefs.edit().putString("username", username);
prefs.edit().putString("password", password);
Change this each time edit will return diffrent instance so your changes wont get committed.
Editor editor = prefs.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.commit();
Try this.
Unlike commit(), which writes its preferences out to persistent
storage synchronously, apply() commits its changes to the in-memory
SharedPreferences immediately but starts an asynchronous commit to
disk and you won't be notified of any failures. If another editor on
this SharedPreferences does a regular commit() while a apply() is
still outstanding, the commit() will block until all async commits are
completed as well as the commit itself.
Ok, apply is same as commit, it only writes the preferences atomically making it thread safe. (It requires API Level 9 though, so be careful)
See the documentation
The problem is what Rajesh CP is saying.
You need to create an editor pointer and then apply:
Editor editor = prefs.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.apply();
Else, every time you create a new instance of the editor and when you apply the changes, the editor that is being instructed to apply the changes, doesn't have any changes

Global EditText Variables

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.

Categories