I have to save my application's settings, but I don't know if I should use a file or a table. I don't need to share them with other application and these settings are just 3-4 booleans used to remember the application to execute an action in a way or in another one. Is it a good idea to create a table just for 3-4 values? Or should I use a file instead small?
If its a question of storing the 3-4 values in application then i would suggest to use the SharedPreference.
You can store and retrieve the Sharedpreferences as below:
Application shared preferences can be fetched using getSharedPreferences() method.The following code can be used to get application shared preferences.
SharedPreferences pref = getApplicationContext().getSharedPreferences(
"any_prefname", MODE_PRIVATE);
Available mode for shared preference:
MODE_WORLD_READABLE
MODE_WORLD_WRITEABLE
MODE_PRIVATE
To edit sharedpreference value, we need editor to edit and save the changes in shared preferences.
Editor editor = pref.edit();
and to save data commit() is used.
Editor.commit();
You can save data into shared preferences using editor. All the primitive data types like booleans, floats, ints, longs, and strings are supported. Call editor.commit() in order to save changes to shared preferences.
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes
Get data from Shared Preference:
Data can be retrived from saved preferences by calling getString() (For string) method.For boolean getBoolean() Remember this method should be called on Shared Preferences not on Editor.
// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Delete data from shared preference and delete sharedpreference:
To delete data from shared preferences we can use remove(“key_name”).If we want to delete all the data, call clear()
editor.remove("student_name");//will delete student_name
editor.commit();
Following will clear all the data from shared preferences
editor.clear();
editor.commit();
You will get the details here -http://developer.android.com/guide/topics/data/data-storage.html
Use sharedPref to save the app settings instead of file and sqLite.
Related
I am using Android Studio and programming in Kotlin. I haven't been able to find a way to save the data entered by the user so it appears when they reopen the app. Thank you ahead of time!
You have to store your data in shared preference when any click event listen or on edittext textwatcher you can set your character in preference but best way is on any click event save data on preference and when activity open set data from preference on edittext.
Store it in Shared Preferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
use this save the value..
Editor editor = sharedpreferences.edit();
editor.putString("key_name", "value"); //here give name and value to save
editor.commit();
use this to get the value.
String edittextvalue = pref.getString("key_name", null); //put edittextvalue where ever you what to show the value.
use this step to remove or clear the value
editor.remove("name");
editor.commit();
String getString(String name, String defValue){...}
This is the definition of getString(...) method of SharedPreferences so I think it's possible if I run code below, it returns 1 two times:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
Timber.e(pref.getString("new", "1"));
Timber.e(pref.getString("new", "100"));
because at the first time its empty, so "1" will store, after that because of it has value ("1"), it will return it's value ("1") not default value ("100")
but it returns "1" and "100" and "new" does not store in my pref file (located in data/data/...)
Am I understanding it wrong or something goes wrong in this code?
Use can only get The data using getString.
to store data use Editor.commit();
Editor editor = settings.edit();
editor.putString("someKey", "someVal");
editor.commit();
only after that you can get this value.
String value = settings.getString("someKey", "someDefaultValueIfThisKeyNotUsedBefore");
In this example, you will recieve "someVal" if commit is used beforehand.
You must put"Something" to SharedPreferences.Editor, and commit them.
pref.getString wont store anything.
Refer to the links below:
https://developer.android.com/reference/android/content/SharedPreferences.html
https://developer.android.com/reference/android/content/SharedPreferences.Editor.html
I tried to append the data in shared preference file by using
SharedPreferences sharedPreferences = getSharedPreferences("myData", MODE_APPEND);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("name", userName.getText().toString());
editor.putString("password", password.getText().toString());
editor.commit();
But I found that new value overwrites the old value. Will you help me to fix this issue?
MODE_APPEND doesn't mean that you add multiple values for each key. It means that if the file already exists it is appended to and not erased . We usually used MODE_PRIVATE.
As for saving multiple names and passwords, you can take a look at putStringSet(string key Set<String> values Method.
You can save the for each key a set of string values. You can separate the username and password by some special character or string. You may even serialize an object to json.
So basically what you need to do is:
Get the list of values from Shared Preferences
Append the current value to the list.
Save the List back to Shared Preferences.
I am attempting to save a user id using SharedPreferences. Do values saved as SharePreferences persist across all Activities in my application so I can access the userid from any application? Below is my code for saving the userid.
userid = result.substring(3, result.length());
Log.d("userid at onpostexecute", userid);
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); // to update userid
editor.putString("userid", userid);
editor.commit();
And here is the code for accessing the userid from the SharedPreferences in another activity.
SharedPreferences prefs = getPreferences(MODE_PRIVATE); // to access userid
String userid = prefs.getString("userid", "");
Log.d("shared prefs userid", userid);
What is strange is that the above code is in my onCreate method but it doesn't show up in the Logcat even though other log data is displayed before and after this code. So is there something wrong with my code that I can't even get it to display in my logcat? I can't even tell if it is being updated.
Values saved as sharedPreferences can be shared between activities if you tell it to. Right now you are creating a preference that is only accessible to that same activity. You need to use:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
Like this you are creating a sharedPreference between your application. There is a lot of explanation on the topic in the accepted answer to another question. Link to question
As discussed in the answer the way you are using to save the preference will only work in the same activity that saved it.
I assume you mean can you access them from any Activity, yes, they do persist even when you leave your app and come back. From the Docs
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
If this Log.d("userid at onpostexecute", userid); doesn't even show up then I would put a breakpoint there and make sure you have a value for userid. I would also check your logcat filters to make sure that you are getting all logs. Just make sure that the type in the spinner is set to "verbose" just to be sure
how to strore data in shared preferences in table format
For store the values using shared preference use below code
SharedPreferences prefs=getSharedPreferences("Key", 0);
Editor e= prefs.edit();
e.putString("Name", "AAA");
e.commit();
For retrieve the shared prefs value use below code
SharedPreferences prefs=getSharedPreferences("Key", 0);
String s= prefs.getString("Name", "");
I don't think you can save table in sharedpreferences; it is saved as like key-value pair.
You can serialize your object and save it in the preferences. Use Serializable or JSON or Protocol Buffers or whatever you're comfortable with.
SharedPreferences store primitive data in a file as key-value pairs.
The SharedPreferences class provides a general framework that allows
you to save and retrieve persistent key-value pairs of primitive data
types. You can use SharedPreferences to save any primitive data:
booleans, floats, ints, longs, and strings.
http://developer.android.com/guide/topics/data/data-storage.html#pref
I adviese to use SQLITE Database to store data in table format.
http://developer.android.com/guide/topics/data/data-storage.html#db
Shared preferences = "Key" , "Value" sets.
If we wants to store small amount of data like usernames, passwords then we will go for Shared Preferences.
To store small amount of data there is no need of creation of Database, tables, insertion query and retrieval query --- So better to go for Shared Preferences.
Shared Preferences is to stores small amount of data, where as SQLite3 is to store large amount of data.
Shared preferences works like HashMap in Collections.
Shared preferences data will be stored in xml file. This xml file we can find in the following location.
Go to
Open DDMS perspective.
Select emulator / rooted Device from the left side panel.
Select File explorer tab from the right side panel.
Open data folder.
Again open data folder.
Open our package name.
Here you will find the Shared Preference folder.
Inside this Shared Preference folder - our shared preference xml file will be visible.
We can pull this xml file from the emulator by selecting the xml file and click on Left arrow on top right side of the DDMS window.
We can also change values in the xml file, then we can push this changed xml file into emulator by clicking on the Right arrow which is there on top right side of this DDMS window.
Note: When you push anything into emulator "DONT FORGET TO RESTART YOUR EMULATOR". Otherwise the changes will not be effected.
Storing the values into shared preferences
import android.content.SharedPreferences;
SharedPreferences preference;
SharedPreferences.Editor editor;
preference=getApplicationContext().getSharedPreferences("PROFILE", 0);
editor=preference.edit();
editor.putString("MANUALPROFILENAME", newProfileValue);
editor.commit();
For getting the values from the shared preferences
import android.content.SharedPreferences;
SharedPreferences preference;
SharedPreferences.Editor editor;
preference=getBaseContext().getSharedPreferences("PROFILE", 0);
String manualsetunset =preference.getString("MANUALPROFILEENAME", "false");// Here false is default value. If the required string does not found in shared preference, the default value will be stored in the string object.