NOTE:

NOTE: Of late, I have been getting requests for very trivial problems that many of you are facing in your day-to-day work. This blog is not to solve your "project" problems - surely not a "Support" site.
I just love to share my knowledge in my spare time and would appreciate any questions or feedback on the articles and code I have shared. I also do appreciate thought-provoking questions that would lead me to write more articles and share.
But please do not put your day-to-day trivial problems here. Even if you do, you most probably would not get a response here.
Thanks

Search This Blog

x

Monday, 12 October 2009

Shared Preferences | Android Developer Tutorial (Part 13)


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.

34 comments:

  1. 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?

    ReplyDelete
  2. thanks a lot for your blog. it helped me a lot in my project as i am a new android developer

    ReplyDelete
  3. Great post,

    Thank you a lot for this and it is exactly what I am looking for.

    ReplyDelete
  4. Hi Sai.,,
    I have a doubt in how to do mms application in android,plz give me some hint..

    Thanks,
    Abhilash

    ReplyDelete
  5. Shared preferences are applicable only class that extends an activity ?

    i wanna shared pref for my class that gives me error for context
    please help me?

    ReplyDelete
    Replies
    1. 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.

      Delete
  6. Hi,
    I 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?

    ReplyDelete
  7. HI
    I'm Trying to put String array to Shared preferences its showing null pointer exception

    so how to put it into it?

    Adv.. thanks & regards

    ReplyDelete
  8. Please post all files. xml, import statements etc. Its so unclear.
    Thanks anyways.

    ReplyDelete
  9. Hi there,
    Thanks 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?

    ReplyDelete
  10. Hi Shahar,
    Yah, 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.

    ReplyDelete
  11. Hi,

    How 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.

    ReplyDelete
  12. Thanks this really helped a lot!

    ReplyDelete
  13. Hi Sai,
    Can we implement the Content Providers on Shred Preferences? for sharing data between the applications.

    ReplyDelete
  14. Hi,

    I 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.

    ReplyDelete
  15. very nice...keep it up..

    ReplyDelete
  16. Hi,
    Your code i much useful for my apps . Thanks a lot.

    Thanks & Regards,
    Jayaprakash.R

    ReplyDelete
  17. Hi,

    Thanks for sharing this knowledgeable code along with step by step clear detailed explaination.

    Regards,
    Sumith.M.P

    ReplyDelete
  18. Hi Sai...
    Thanks for posting.. very useful..

    ReplyDelete
  19. Hello,

    Thanks 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

    ReplyDelete
  20. Good evening mam,
    I 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..

    ReplyDelete
    Replies
    1. Hello Javed,
      You 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.

      Delete
  21. I have used this information on my webpage
    thanks for sharing...

    ReplyDelete
  22. Hi,

    Can any one give an idea how to change fontsize from prefernce xml file.

    ReplyDelete
  23. Hello Mam,
    This 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

    ReplyDelete
  24. 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?

    ReplyDelete
  25. This comment has been removed by the author.

    ReplyDelete
  26. hi sai,
    i 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

    ReplyDelete
  27. it is not goin to the next intent.....can some one help me how to add image using adb ....

    ReplyDelete
  28. Hi 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!

    ReplyDelete
  29. dear mam,
    i want to learn Android, so what is better way to learn, can u plz tell me, i m waiting for reply

    ReplyDelete
  30. i wanna shared pref for my class that gives me error for context
    please help me?
    Best Home Loans

    ReplyDelete