how to use SharedPreference among activities - android

I Am writing a code using SharedPreference to store username and password of a user but each time I entered information the older one in xml file are override by newer one what I have to to to get all my data?
SharedPreferences sp1=getSharedPreferences("myshared", 0);
sp1.edit().putString("name", name.getText().toString()).commit();
sp1.edit().putString("pass", pass.getText().toString()).commit();
sp1.edit().putString("age",age.getText().toString()).commit();
sp1.edit().putString("id",id.getText().toString()).commit();

It sounds like you're overwriting your shared preferences between activities. SharedPreferences are persistent like a file on disk, so you shouldn't ever have an issue with the values not being set, hence why you must be overwriting it.
You can get your SharedPreferences by doing
SharedPreferences sp1=getSharedPreferences("myshared", 0);
String name = sp1.getString("name", "noname");
String pass = sp1.getString("pass", "nopass");
...
You can determine if the name/pass was set by checking if they equal the default value (noname and nopass in this case, though it could easily be null).

Related

Android Saving data on Button

I have a button in a customView which has several numbers on it individually,it counts backward
now my program doesn't keep value on it when user taps back and closes the program How can I prevent this ?
You can pass value from one activity to other using intents. If you want to persist data,the simplest way to achieve this would be saving it in Shared Preferences.
Developer link has good information on how to implement this -
You can save the value Key, Value pair and then retrieve it when the app is up again.
you can Use SharedPreferences its easy to write and get.
You can create one like this
SharedPreferences prefs = getSharedPreferences("yours", MODE_PRIVATE);
and write to like this
SharedPreferences.Editor prefsEditor=prefs.edit();
prefsEditor.putString("what you want", "value of what you want");
prefsEditor.apply();
and retrive like this
String s=prefs.getString("what you want", "value to be retrived if failur happens in retreiving")
if the value not important after end the program you can save it into public static variable
but if you need the variable after end the program you can use SharedPreferences
follow this tutorial http://developer.android.com/reference/android/content/SharedPreferences.html

How do I save and read an integer on android libgdx?

How do I save an integer that can be overwritten and then read it on android? I am using libgdx. I know how to do it for my desktop, but I want internal storage.
You should use libgdx Preferences.
That way it will work cross-plattform! (including Android)
Since you just want to store some Integer that should be just what you need.
See example:
//get a preferences instance
Preferences prefs = Gdx.app.getPreferences("My Preferences");
//put some Integer
prefs.putInteger("score", 99);
//persist preferences
prefs.flush();
//get Integer from preferences, 0 is the default value.
prefs.getInteger("score", 0);
There are different ways to do that:
You can write to a FileHandle. Just create a FileHandle like Gdx.files.local("myfile.txt"); and write to it using fileHandle.writeString(Integer.toString(myInt));
Note, that Internal and Classpath are read-only, so you can't write files there.
Also note, that not all types of the gdx.files. are usable for all backends. More on that here.
The second way to do that are the Preferences. The Preferences are the only way to have persistent data for HTML5 applications.
The Preferences are XML files in which you can store, read and change data.
To create Preferences for your app you just need to call:
Preferences myPref = Gdx.app.getPreferences("PreferenceName");
Note, that you should use the full name, for example com.stackoverflow.preferences, as on desktop all Preferences use the same file.
To write data you can use myPref.putInteger("name", value) for Integers, myPref.putBoolean(("name", value) for Booleans... Make sure you call myPref.flush() after all changes, to save the new data.
To get the data you can call myPref.getInteger("name, defaultValue"). The default value is returned if there is no data with the given name.
More on Preferences here.
Hope i could help.

Write File without MODE_WORLD_READ/WRITE

Okay, I have come across many tutorials on creating and writing/reading a file. What I want my Android app is to create a small text file where it will read and write some settings so my user information can be saved. The problem is every tutorial I have come across uses the SDcard (which allows the user and any other app to read) or use MODE_WORLD_READABLE which makes any app read off of it.
I was wondering how I can create and read/write my file but private or atleast keep it on the internal storage of the phone.
Here's an easy example. To read a preference do this:
SharedPreferences preferences = getSharedPreferences("YourAppName", MODE_PRIVATE);
String thisString = preferences.getString("KeyForThisString", "default");
You can getInt, getLong, etc.
To store the preferences, use these lines:
SharedPreferences preferences = getSharedPreferences("YourAppName",MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("KeyForThisString", thisString);
editor.commit();
As before, you can putInt, putLong, etc.
The available methods for this API are here: http://developer.android.com/reference/android/content/SharedPreferences.html
dont know how to use it much and from what im seeing at least, its not much of a difference unless im wrong.
I still recommend to use SharedPreferences technique. It's explicitly easy and save a lot of time.
You can use it to save any primitive data: booleans, floats, ints, longs, and strings.
For example, you can do that each time when user invokes any changes to your Application because it's high performance technique. By this way even on crash all edited info will be stored.
Suppose you have an Activity.
Use this method where data is your String that you wanted to save to file.
private void saveInfo(String data){
String key = "myKey";
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(key , data);
editor.commit();
}
Now, when you launch your application again onCreate method invoked and you can load your information back:
private void loadInfo(){
String key = "myKey";
SharedPreferences mPrefs = context.getSharedPreferences(LauncherUI.PREFS_NAME, 0);
String yourData = mPrefs.getString(key, ""); // "" means if no data found, replace it with empty string
}
Here is a link to 5 types to store data: Storage Options

Android storing string array

I've been looking for over the past day and a half at several websites about how to store strings/string arrays/etc. and I can't seem to figure it out. I'm not sure if I'm just not quite comprehending how to implement data storage..or what. But here is my problem, simply put, I have two activity pages (we'll name 'A,B' respectively) . All I want to do is get a string from a text view in Activity B, store it in an array, and then have it accessed by clicking a button in Activity A.
I know it is simple, but I hit a block for some reason... I am trying to use SharedPreferences but how would I obtain the string from Activity B, store it in a global array, and let it be accessed by a different activity (Activity A) ?
Just store it into shared preferences (usually in onPause()):
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString(GAME_STATE, writer.toString());
editor.commit();
in one activity and load in another (usually in onResume()):
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
String jsonState = preferences.getString(GAME_STATE, null);
And nothing prevents you from using public static variables
You can't store an array directly in shared preferences, but you can store a set.
See putStringSet and getStringSet. You can add all the items from your array to a LinkedHashSet (as long as they are unique) if you wish to store them in SharedPreferences. See Konstantin's answer for the general idea on how to use SharedPreferences.
Yes you can obtain and store value in global array but you will loss everything once you close the application. So its better you create a table and store/get values from the table whenever you required.
Here is an example for creating SQLite example.

Shared Preference problem in android app

in my app the first activity is a sign in page. In the edit boxes i am typing the user name and password. Those values are been move to an api and in return i am getting the userid from the server as an xml file.
I am parsing the xml file and storing the value in shared preferrence as follows
SharedPreferences.Editor IdEditor = Id.edit();
IdEditor.putString("useridValue", chap.getid());
IdEditor.commit();
And in the next time when the user opens the app i want to check whether it is already signed i or not. How to check this using the value stored in Shared preference
is your Id class extending SharedPreferences ?
maybe
String userId = Id.getString("useridValue");
If your preference is stored in the default preference then you can
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String userId = prefs.getString("useridValue");
on a side note you shouldn't really use a capital I on the IdEditor variable it should probably be idEditor
Check whether this entry already exist in shared preference, using:
id.containskey("useridvalue")

Categories

Resources