We saw in an earlier tutorial (Part 12) how data can be
stored in SQLDB. However, many applications may provide a way to capture user
preferences on the settings of a specific application or an activity. For
supporting this, Android provides a simple set of APIs.
Preferences are typically name value pairs. They can
be stored as “Shared Preferences” across various activities in an application
(note currently it cannot be shared across processes). Or it can be something
that needs to be stored specific to an activity (which is not discussed here).
The context object lets you retrieve SharedPreferences
through the method Context.getSharedPreferences().
In my example, I will set 2 preferences i.e. MyName
and MyWallpaper
in one activity i.e ManageSharedPref.java. Retrieve
these values in the next activity – ViewSharedPrefs.java.
The second activity displays my preferred name in a list view and also resets
the android wallpaper to the image that I had set as a preferred wallpaper in
the first activity. When you run this application, if you come back to the
home, you will see the wall paper is reset.
Here is the code in ManageSharesPrefs:
SharedPreferences
myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor =
myPrefs.edit();
prefsEditor.putString(MY_NAME, "Sai");
prefsEditor.putString(MY_WALLPAPER, "f664.PNG");
prefsEditor.commit();
First, I obtain a SharedPreferences object
making it readable by all. The first parameter is a name of a file that stores
my preferences. This automatically creates the xml file if it does not exist
and then stores in the same.
Next, I edit it. That creates an editor object, using
which I input my preferences. Here, for the wall paper, I have put an image
name. I also need to push the actual image file into the android storage which
I do this way.
adb push <local> <remote>
In this case it is
adb push f664.PNG
/data/misc/wallpaper/f664.PNG
This command creates a folder called wallpaper in
/data/misc and copies the f664.PNG file from my current location to the android
storage.
When I click the “View Shared Preferences” button, I am
taken to the next activity. Here is the code in ViewSharedPrefs that gets
executed:
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String prefName = myPrefs.getString(MY_NAME, "nothing");
String wallPaper = myPrefs.getString(MY_WALLPAPER, null);
if(wallPaper != null) {
try {
Bitmap
bm = BitmapFactory.decodeFile("/data/misc/wallpaper/"+wallPaper);
Log.d(getClass().getSimpleName(),"Wallpaper name is: "+ wallPaper);
setWallpaper(bm);
Toast.makeText(this, "Wall paper
has been changed." +
"You may go to the home screen to view the same", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException fe){
Log.e(getClass().getSimpleName(),"File not found");
}
catch (IOException ie) {
Log.e(getClass().getSimpleName()," IO Exception");
}
}
ArrayList<String> results = new ArrayList<String>();
results.add("Your Preferred name is: " + prefName);
this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));
There are 3 steps to understand here:
1. Step 1: Retrieve
the shared prefs data from the object.
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String prefName = myPrefs.getString(MY_NAME, "nothing");
String wallPaper = myPrefs.getString(MY_WALLPAPER, null);
2. Step 2: Display
the name
ArrayList<String> results = new ArrayList<String>();
results.add("Your Preferred name is: " + prefName);
this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));
3. Step 3: Reset the
wall paper.
if(wallPaper != null) {
try {
Bitmap
bm = BitmapFactory.decodeFile("/data/misc/wallpaper/"+wallPaper);
Log.d(getClass().getSimpleName(),"Wallpaper name is: "+ wallPaper);
setWallpaper(bm);
Toast.makeText(this, "Wall paper
has been changed." +
"You may go to the home screen to view the same", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException fe){
Log.e(getClass().getSimpleName(),"File not found");
}
catch (IOException ie) {
Log.e(getClass().getSimpleName()," IO Exception");
}
}
It is this simple. The complete code is available here.
With the mode (permission) is it necessary to ensure that every retrieval of the file uses the same mode? Or is it safe to use the permission mode in the first activity's onCreate such that the file is created with the permission you want and would then ignore future use of the mode param?
ReplyDeletethanks a lot for your blog. it helped me a lot in my project as i am a new android developer
ReplyDeleteGreat post,
ReplyDeleteThank you a lot for this and it is exactly what I am looking for.
Hi Sai.,,
ReplyDeleteI have a doubt in how to do mms application in android,plz give me some hint..
Thanks,
Abhilash
mms application means............
DeleteShared preferences are applicable only class that extends an activity ?
ReplyDeletei wanna shared pref for my class that gives me error for context
please help me?
You can try a "work around". For example if a class that extends activity is calling a method from another class that doesn't extend activity, then just create a new parameter for that method that tells you what the preference is.
DeleteHi,
ReplyDeleteI want to share the data between two different applications without help of Content Providers.But I unable to get the data..
Anyone please tell me the way,How to use shared preference between two applications?
HI
ReplyDeleteI'm Trying to put String array to Shared preferences its showing null pointer exception
so how to put it into it?
Adv.. thanks & regards
Please post all files. xml, import statements etc. Its so unclear.
ReplyDeleteThanks anyways.
Hi there,
ReplyDeleteThanks that looks wonderful.
about: "shared-preferences",
after i close the application(onDestroy() has happend), does the shared-preferences file is still exist? meaning: the next time i'll open the app can i read from that file the values i entered previously?
Hi Shahar,
ReplyDeleteYah, we can get the values which was stored previously.Even after onDestroy() also the shared-preference file exists.And just check the Context.MODE_PRIVATE,Context.MODE_PUBLIC,... modes for situation.
Hi,
ReplyDeleteHow to use Sharedprefence in BroadcastReceiver.
I am unable to get values in it.
SharedPreferences sp = context.getSharedPreferences("mypre", context.MODE_WORLD_READABLE);
SharedPreferences.Editor ed = sp.edit();
ed.putString("Number", number);
ed.commit();
M getting null valu from pref.
Thanks this really helped a lot!
ReplyDeleteHi Sai,
ReplyDeleteCan we implement the Content Providers on Shred Preferences? for sharing data between the applications.
Hi,
ReplyDeleteI have multiple activities and also i have exit menu option, my problem is when i click exit from menu option its destroying the current activity only not all all activities. So please help me if you send sample code it will be helpfull.
very nice...keep it up..
ReplyDeleteHi,
ReplyDeleteYour code i much useful for my apps . Thanks a lot.
Thanks & Regards,
Jayaprakash.R
Hi,
ReplyDeleteThanks for sharing this knowledgeable code along with step by step clear detailed explaination.
Regards,
Sumith.M.P
Hi Sai...
ReplyDeleteThanks for posting.. very useful..
Hello,
ReplyDeleteThanks for this wonderful post. I have a question here - Can we access the system defined Shared Preferences here? If so, how to identify the relevant preference which we need to work on? Please assist.
Thanks
Good evening mam,
ReplyDeleteI need some help from you. I hope you will replay,
Here is my problem.
I am making one application in android
In my application I am having 5 checkboxes for displaying different task on another activity in this user have to select 1, 2 or 3 checkbox which he/she want to see on next screen. In first screen i am having Save button also. after checking checkboxes user have to click on save button. My question is I want to show only those Expandable list on second activity which is selected by user on check box when user click on save button please tell in details with example me how to do this? Thank you very much..
My email is javedsalat@gmail.com
Thanks again..
Hello Javed,
DeleteYou have 5 checkbox And 1 button in one activity.
First u have to take 5 boolean value in one Global class for each checkbox .When user click on Save button u want to store checkbox's status in Global.class's boolean value And another next activity u want to retrive its value and show Expandable list.
I have used this information on my webpage
ReplyDeletethanks for sharing...
Hi,
ReplyDeleteCan any one give an idea how to change fontsize from prefernce xml file.
Hello Mam,
ReplyDeleteThis is shushruth, I am developing on a bluetooth android application where i can do search and pairing of device successfully, but when i try to send a "CHARACTER" say "t", it throws error saying unsupported content format, can please know what is the correct format to send a char through bluetooth..
Regards,
Shushruth
Hi, I am able to read, access and edit the shared preferences for classes within the same package. But I problems with sharing the shared preferences from different packages. Is there way do do it?
ReplyDeleteThis comment has been removed by the author.
ReplyDeletehi sai,
ReplyDeletei want store the username,and password permanently,that means if i login once into my application it wont ask second time ,it needs to go directly into application...
please respond to my query...
thanks
it is not goin to the next intent.....can some one help me how to add image using adb ....
ReplyDeleteHi Sai, Thank you for sharing your experience and knowledge!!! I've run across your blog entries again and again and have found every one insightful. Thanks again!
ReplyDeletemany many thanks
ReplyDeletedear mam,
ReplyDeletei want to learn Android, so what is better way to learn, can u plz tell me, i m waiting for reply
i wanna shared pref for my class that gives me error for context
ReplyDeleteplease help me?
Best Home Loans