Create SharedPreference from xml - android

I am using SharedPreference to store data between activities (it's not anything settings-related, just user data).
I created these static methods in a utils class to handle writing to/reading from shared preference from anywhere in my app:
public static <T> void saveData(Context context, String key, T value, String typeOfValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences("FILE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
switch (typeOfValue) {
case ("String"):
editor.putString(key, (String) value);
break;
case ("int"):
editor.putInt(key, (Integer) value);
break;
case ("Boolean"):
editor.putBoolean(key, (Boolean) value);
break;
default:
break;
}
editor.commit();
}
public static <T> T loadData(Context context, String key) {
SharedPreferences sharedPreferences = context.getSharedPreferences(FILE, Context.MODE_PRIVATE);
return (T) sharedPreferences.getAll().get(key);
}
I have these questions:
If I do this way, when is the preference file "FILE" created? Is it created when the application is installed or only when the first save or load method is called? Is it an xml?
What if I want to make sure
A shared preference file called "FILE" is created when the application is installed.
Inside that file, declare a list of permanent keys (no more keys will be added later) and have them all set to default values.
How do I do that? I heard that creating the shared preference from XML might help, but after reading the android api, it seems like this kind of shared preference is for the "settings" in android only.
I know that you can "kinda" set the default value like this
String username = prefs.getString("username_key", "DefaultUsername");
But I don't want this since all my read methods are generic. Also, I don't like this cause I don't really know what happens under the hood. It doesn't seem like the default value is actually set into the preference file, it might simply return the default value if a value has not yet been set.

You can view the sharedPreference.xml.
Use Android Studio -> tools -> Android -> Android Device Monitor.
The file path is /data/data/<package_name>/shared_prefs
So you can test when the file created.

Related

Remember/Forget device function on android app

I am building an app which connects & then controls a device.
I am wanting to add a remember device function and forget device function so the user can stick to one device or switch.
I am new to android so any help on how to implement this would be great.
You can keep the information in SharedPreferences. If you are connecting to a Bluetooth device then you need to remember the Mac address of the device.
Store and retrieve the info using the following functions.
public static void addDataToSharedPrefsString(String key, String value,Context context) {
SharedPreferences.Editor sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(
context).edit();
sharedPreferences.putString(key, value);
sharedPreferences.commit();
}
public static String getDataFromSharedPrefString(String key,Context context) {
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(context);
String value = preferences.getString
(key, "");
return value;
}
Add to shared pref by
addDataToSharedPrefsString("macAddress", "MAC123q4e",context);
get the shared value by
getDataFromSharedPrefString("macAddress",context);
if you want to delete an existing item in shared pref, set the value null.
addDataToSharedPrefsString("key", null,context);
I hope this is your requirement and this solution would help you.

Android SharedPreferences IOException Error

So I'm trying to write some strings to SharedPreferences in my android app. I first declare SharedPreferences and its original properties in my Application subclass. I want to be able to change the values of my data in other activities in the app but I get the error below. How should I fix this? Some other guy posted the same question but no one really answered him so that's why I'm asking again. Any help is appreciated! Thanks
SharedPreferencesImpl﹕ writeToFile: Got exception:
java.io.IOException: java.nio.charset.CoderResult[Malformed-input error with erroneous input length 1]
at com.android.internal.util.FastXmlSerializer.flush(FastXmlSerializer.java:225)
at com.android.internal.util.FastXmlSerializer.append(FastXmlSerializer.java:86)
at com.android.internal.util.FastXmlSerializer.escapeAndAppendString(FastXmlSerializer.java:127)
at com.android.internal.util.FastXmlSerializer.text(FastXmlSerializer.java:361)
at com.android.internal.util.XmlUtils.writeValueXml(XmlUtils.java:425)
at com.android.internal.util.XmlUtils.writeMapXml(XmlUtils.java:245)
at com.android.internal.util.XmlUtils.writeMapXml(XmlUtils.java:185)
at android.app.SharedPreferencesImpl.writeToFile(SharedPreferencesImpl.java:596)
at android.app.SharedPreferencesImpl.access$800(SharedPreferencesImpl.java:52)
at android.app.SharedPreferencesImpl$2.run(SharedPreferencesImpl.java:511)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
Some example code:
This is declared in my Application class:
editor.putString("firstRun", "true");
editor.apply();
This is declared in my outside activity:
editor.putString("firstRun", "false");
editor.apply();
And this is how my shared preferences is declared (in my Application subclass):
SharedPreferences prefs = getApplicationContext().getSharedPreferences("My App", 0);
EDIT:
Here's more code:
Application Class
public class MainApplication extends Application {
public static SharedPreferences prefs;
public SharedPreferences.Editor editor;
public void onCreate() {
super.onCreate();
// Data Configurations etc
prefs = getSharedPreferences("My App", Context.MODE_PRIVATE);
editor = prefs.edit();
Map<String, ?> keys = prefs.getAll();
if (keys.size() == 0) {
editor.putString("firstRun", "true");
editor.apply();
}
// Block of Code saving more strings to shared preferences
}
}
Activity where preferences are being changed:
public class MainActivity extends Activity {
public void onCreate() {
super.onCreate();
SharedPreferences.Editor editor = MainApplication.prefs.edit();
if (MainApplication.prefs.getString("firstRun", "false").equals("true")) {
// Set data correctly
editor.remove("firstRun");
editor.putString("firstRun", "false");
editor.apply();
// yadda yadda yadda more code doing other things not related to shared preferences
}
}
}
}
SHOULD'VE MENTIONED THIS, I am also saving json stuff to the shared preferences.
Some logcats of the SharedPreferences:
Tutorial, true
Notification0, {"alert":"Test Alert","category":"news","date":"Aug 7, 2015","name":"Alert01"}
VersionNum, 1.0
firstRun, false
New0, {"alert":"Test Alert","category":"news","fileData":"<!doctype html><html itemscope=\"\" itemtype=\"http://schema.org/WebPage\" lang=\"en\"><head><meta content=\"Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for.\" name=\"description\"><meta content=\"noodp\" name=\"robots\"><meta content=\"/images/google_favicon_128.png\" itemprop=\"image\"><meta content=\"origin\" id=\"mref\" name=\"referrer\"><title>Google</title> <script>(function(){window.google={kEI:'29q4Va--H4W0eI2jsMgP',kEXPI:'3700337,3700372,4028875,4029815,4031109,4032235,4032500,4032678,4033307,4033344,4034882,4035869,4036527,4036848,4037333,4037457,4037569,4038012,4038399,4038464,4038821,4039386,4039462,4039879,4039886,4039895,4039937,4040028,4040061,4040112,4040136,4040412,4040513,4040678,4040849,4040865,4040976,4040982,4041079,4041304,4041323,4041440,4042052,4042103,4042125,8300095,8300200,8300203,8500394,8501295,8501407,8501489,8501584,8501767,10200083,10200095,10201249,10201251,16200005,16200009,16200011',authuser:0,j:{en:1,bv:21,pm:'p',u:'c9c918f0',qbp:0,rre:false},kscs:'c9c918f0_21'};google.kHL='en';})();(function(){google.lc=[];google.li=0;google.getEI=function(a){for(var b;a&&(!a.getAttribute||!(b=a.getAttribute(\"eid\")));)a=a.parentNode;return b||google.kEI};google.getLEI=function(a){for(var b=null;a&&(!a.getAttribute||!(b=a.getAttribute(\"leid\")));)a=a.parentNode;return b};google.https=function(){return\"https:\"==window.location.protocol};google.ml=function(){return null};google.time=function(){return(new Date).getTime()};google.log=function(a,b,d,e,g){a=google.logUrl(a,b,d,e,g);if(\"\"!=a){b=new Image;var c=google.lc,f=google.li;c[f]=b;b.onerror=b.onload=b.onabort=function(){delete c[f]};window.google&&window.google.vel&&window.google.vel.lu&&window.google.vel.lu(a);b.src=a;google.li=f+1}};google.logUrl=function(a,b,d,e,g){var c=\"\",f=google.ls||\"\";if(!d&&-1==b.search(\"&ei=\")){var h=google.getEI(e),c=\"&ei=\"+h;-1==b.search(\"&lei=\")&&((e=google.getLEI(e))?c+=\"&lei=\"+e:h!=google.kEI&&(c+=\"&lei=\"+google.kEI))}a=d||\"/\"+(g||\"gen_204\")+\"?atyp=i&ct=\"+a+\"&cad=\"+b+c+f+\"&zx=\"+google.time();/^http:/i.test(a)&&google.https()&&(google.ml(Error(\"a\"),!1,{src:a,glmm:1}),a=\"\");return a};google.y={};google.x=function(a,b){google.y[a.id]=[a,b];return!1};google.load=function(a,b,d){google.x({id:a+k++},function(){google.load(a,b,d)})};var k=0;})();google.kCSI={};\ngoogle.j.b=(!!location.hash&&!!location.hash.match('[#&]((q|fp)=|tbs=rimg|tbs=simg|tbs=sbi)'))\n||(google.j.qbp==1);(function(){window.google.sn='webhp';google.timers={};google.startTick=function(a,b){google.timers[a]={t:{start:google.time()},it:{},bfr:!!b,b:{},olh:null};window.performance&&window.performance.now&&(google.timers[a].wsrt=Math.floor(window.performance.now()))};google.tick=function(a,b,d){google.timers[a]||google.startTick(a);google.timers[a].t[b]=d||google.time()};google.bit=function(a,b,d){google.timers[a]||google.startTick(a);var c=google.timers[a].it[b];c||(c=google.timers[a].it[b]=[]);var e=c.push({s:d||google.time()})-1;return function(){c[e]&&(c[e].e=d||google.time())}};google.blockCSI=function(a,b){google.timers[a].b[b]=!0};google.unblockCSI=function(a,b,d){if(a=google.timers[a]){a=a.b;a[b]=!1;for(var c in a)if(a.hasOwnProperty(c)&&a[c])return;google.csiReport&&google.csiReport(void 0,void 0,d)}};google.rolh=function(a){google.uolh();google.timers.load&&(google.timers.load.olh=a,window.addEventListener?window.addEventListener(\"load\",a,!1):window.attachEvent&&window.attachEvent(\"onload\",a))};google.uolh=function(){if(google.timers.load){var a=google.timers.load;a.olh&&(window.addEventListener?window.removeEventListener(\"load\",a.olh,void 0):window.attachEvent&&window.detachEvent(\"onload\",a.olh),a.olh=null)}};google.startTick(\"load\",!0);google.blockCSI(\"load\",\"ol\");google.blockCSI(\"load\",\"xjs\");google.iml=function(a,b){google.tick(\"iml\",a.id||a.src||a.name,b)};})();google.afte=!0;google.aft=functio
The odd thing is that when I set Tutorial to false later on in my app, it does set it to false. But then when I rerun the program, Tutorial is set back to true. However, I don't reset it in my code anywhere. This sometimes happens with firstRun as well but sometimes it DOES get set to false... Any ideas? I'll double check.
I don't know the exact reason for your problem, but SharedPreferences objects are intended to store small amounts of data anyway. If you need to store more data I would advise saving it to internal storage instead.
I have never had any problems storing and retrieving data to internal storage, whereas I run into bugs and irritating restrictions with SharedPreferences (such as no putStringList). For all but the simplest data I would avoid SharedPreferences.

Android: Unbale to save boolean in SharedPreferences

Hey guys I am unable to save a boolean value using SharedPreferences. The value is ALWAYS true for some reasons. Here is how I save the value:
public static void setSharedPreference(Context ctx, String keyValue, boolean value){
SharedPreferences sp = ctx.getSharedPreferences(Constants._preferencesName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean(keyValue,value);
editor.commit();
}
And this is how I get it back:
public static boolean getBooleanPreference(Context ctx, String keyValue){
boolean prefValue;
SharedPreferences sp = ctx.getSharedPreferences(Constants._preferencesName, ctx.MODE_PRIVATE);
prefValue = sp.getBoolean(keyValue, false);
return prefValue;
}
What is wrong?!
Your code is syntactically correct, but I suspect you are passing different Context while saving than you are passing while reading from prefs. This will result in accessing different shared preferences storage. This is especially easy to step on if you are doing your writes and reads in different activities and decide to pass this as context. Unless there's a reason for doing so then you most likely want to reach your preferences from anywhere in your app then use always application context instead (getApplicationContext()).
Everything is correct in your code.
The ONLY possibility of a mistake is when you are calling these methods. Please use getApplicationContext() while putting and retrieving data.
And please do a "Clear data" for the app and start with a clean SharedPreference.

How to use one time domain name in android?

I have a RESTful web-service, I am retrieving a data to android device
So here My ip address/Doamin name may change like..
192.168.0.1 or1-255 etc or It may be www.stackexchange.com or www.stackoverflow.com
Like my data will be stored in 192.168.0.1/rst/api/login or www.stackoverflow.com/rest/api/sitemview
So to over come this I want to use domain name as One time when i install application
in my application I have other pages like Login,display list-view, Single ItemView.
So this domain name should stored in device and pass to other activities every time when I use.
I used shared preferences like
public static void savePreferences(Context ctx, String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(ctx);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
so when they load
public static Object loadSavedPreferences(Context ctx, String key) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(ctx);
return sharedPreferences.getString(key, "");
}
So here My problem is that This one time value is not permanent when ever I force close or Restart devise that passing value is not working
Any suggetion
If your domain name fixed, use below code.
public class WS{
public static final String domain="http://blah.ws";
}
Access it in each activity
with
String apiPath=WS.domain+your_rest_path;

Getting application data using SharedPreferences in Xamarin.Android

I need to extract the application data using SharedPreferences in Xamarin.Android.
Here is what I have tried in android.
public static void SetAuthentication(bool authenticationValue)
{
var localSettings = Application.Context.GetSharedPreferences ("Hello", FileCreationMode.Private);
localSettings.Edit ().PutBoolean ("ValidUser", authenticationValue).Commit ();
}
public static bool GetAuthentication()
{
var retValue = false;
object value;
var localSettings = Application.Context.GetSharedPreferences ("Hello", FileCreationMode.Private);
localSettings.GetBoolean ("ValidUser", out value);
}
But somehow I feel this is not the right approach.
Any guidance is appreciated.
Thanks
On the Android platform, preferences are stored in a text file in the private folders of the Android application - there are 2 ways to access these SharedPreferences data files.
You can either use the "default" file for the application, or you can use a named file, using any name you want.
This second approach is what you have chosen to do by calling GetSharedPreferences with a filename.
I would suggest to just use the "default" preferences. This way has some advantages:
the code is simpler
the preferences can be accessed more easily in a PreferenceActivity later on
To do this, create your ISharedPreferences instance using:
ISharedPreferences localSettings =
PreferenceManager.GetDefaultSharedPreferences (mContext);
Once you have your "default" shared preferences in this manner, the rest of your code stays the same.
For more info, check out related questions:
How do I use SharedPreferences in Xamarin.Android?
save android app string value after close xamarin
I agree with Richard so just to be clear and complete I would do like this:
public static void SetAuthentication(Context ctx, bool authenticationValue)
{
ISharedPreferences pref = ctx.GetSharedPreferences("your_app_preferences", FileCreationMode.Private);
ISharedPreferencesEditor edit = pref.Edit();
edit.PutBoolean("ValidUser", authenticationValue);
return edit.Commit();
}
public static bool GetAuthentication(Context ctx)
{
ISharedPreferences pref = ctx.GetSharedPreferences("your_app_preferences", FileCreationMode.Private);
return pref.GetBoolean("ValidUser"), null);
}
I hope this will make you feel happier.

Categories

Resources