Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Android User Preferences: How to save and load user preferences in Android

In this article we will discuss about the mechanism used to load and save user preferences in Android applications.

Most of the Android apps need to save data in the system, as well as only to save the information about the apps’ state during the onPause () method call, so the user progress is not lost. Here most of the non-trivial apps also need to save the user settings, and here some apps must manage and control the large amounts of information in files or databases system process. This class introduces us to the principal data storage options in the Android system including saving key-value pairs of the primitive data types in a shared preferences file, and saving arbitrary files in the Android's file system with databases managed by SQLite (It is also a platform of the database system). Here we will also discuss about some save and load process with some methods.



Via Application


Saving simple user data

This process is used by the SharedPreferences object in the system.


Sharing data among activities in the

same application

This process is used for consumption through the getSharedPreferences () method.


Saving to a file

Saving is very much required here. This process is used through the FileOutputStream and OutputStreamReader



Reading from a file

After saving the file it is also required to retrieve the data from that particular system which is controlled via the FileInputStream and InputStreamReader classes.


Saving to external storage

In the computer system we can also store data at different storage devices. Here we use the getExternalStorageDirectory () method to return the actual path to the external storage device or area.


Accessing files in the res/raw


This is a very vital process to learn. This process is totally controlled by the openRawResource () method in the Resources object (obtained via the getResources () method).


Creating a database helper class

Database system is now managed and controlled through extending the SQLiteOpenHelper class.

Table1: Showing save and load methods

Concept of Android persistence

Android persistence is an important concept and three basic ways of persisting data are given below

  1. A lightweight mechanism is also known as shared preferences to save insignificant chunks of data.
  2. The Traditional file systems also present here.
  3. A relational database management system through the support of SQLite databases.

What are the major importances of preferences?

Generally the development is needed to store the user preferences such as font size, font name, font style, profile info, etc. In that circumstance we have to discuss the following importance of the Preferences.

  1. We can save the data to a file; nevertheless we have to accomplish some file management through the routines.
  2. We have more than a few pieces of information to save the data, such as text size, font name, preferred color in the background etc.
  3. The task of writing to a file becomes more burdensome or time-consuming.
  4. The unconventional inscription to a text file is to use the database; nevertheless saving primitive data to a database might overkill for the designer or in terms of run-time performance.

Saving and loading files

It is a very well known process and practice to use the Shared Preferences or a database to accumulate and store our application data.Nevertheless there are some situations when we want to use the files that directly depends on Android’s managed mechanisms process architecture. Following is one example.

Listing 1: Sample showing files streams

  String FILE_NAME = “sgcfile.tmp”;
  /* create a new output file stream that’s private to this application.*/
  FileOutputStream fos1 = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
  /*create a new file input stream.*/
  FileInputStream fis1 =  new openFileInput(FILE_NAME); /*Parameterize Constructor*/

Those types of methods only maintain and support the files through the up-to-date presentation folder specifying the path extractors.

If the filename that we specify at the time of creating a FileOutputStream does not exist, Android will create it for us. The default behavior for existing files is to overwrite them; to append an existing file, specify the mode as Context.MODE_APPEND. If we want to use the standard way of the system to share a file, which is present in the middle of the applications, is too expensive to a Content Provider. Different types of system which can process to hypothesize either the Context.MODE_WORLD_READABLE or Context.MODE_WORLD_WRITEABLE at the movement of creating the output file to mark the system that is also presented in supplementary or in different types of applications. That type of syntax is also shown here.

Listing 2: Sample showing files types

  String outputgenerate_file = “sgccopy.txt”; /*Text file message passes through here*/
  FileOutputStream fos1 = openFileOutput(outputgenerate_file, Context.MODE_WORLD_WRITEABLE);

In that scenario the SharedPreferences object allows us to store the simple application data concluded by the name/value and the pairs. As per our specification the name for the data which we want to save, and then both value will be saved automatically to an Extensible Markup Language file format for us.

Preference objects

Instead of using the view objects to build up the User Interface and settings use various subclasses of the Preference class which are declared in an Extensible Markup Language file. Generally a preference object is the building block for a single setting scenario. Every Preference gives the impression as an item in a list and also provides the appropriate User interface for users to modify the settings.

Including static files as resources

When our application necessitates external file possessions, we can include them in our distribution package by placing them in the res/raw folder of our project order. Generally these types of order are like hierarchical model. In that case to access these Read Only file possessions and call the openRawResource method from our application’s Resource object and also receive an InputStream based on the specified resource structure.

Listing 3: Sample showing resources

  Resources sgcresources = getResources();
  InputStream sgcfilemodel = myResources.openRawResource(R.raw.sgcfilename);

Now adding a raw file to our resources hierarchy model is an excellent alternative for the preexisting data sources. In that case we can mention dictionaries where it is not desirable or even probable to renovate them into an Android database. The Android’s resource instrument let us hypothesize the dissimilar resource files for different types of languages, locations, or hardware configurations. For those types of process, result is given here, as we could connect, for illustration, create an application that enthusiastically loads a dictionary and the resource based on the user of the current settings.

File Management Tools

File management tools are very much important part of the Android system. It supplies approximately rudimentary file management tools which generally helps us deal with the file system as per requirement. There are many conveniences located within the customary File package. Generally this package is very much important for us for working in the Input system programming model. Point should be remembered that Android does supply approximately some specialized utilities for file management that are available from the application’s Context scenario system. Some required file types and applications are mentioned here.

File Type



This delete File is used to remove files that are created by the current application.


fileList is used for returning a String array that embraces all the files that is created by the up-to-date and also existing application.

Table 2: Showing files types

How to load up Android user preference

In a simple way we can divide the process mainly into two ways to get the content in the Web View. One is to provide the browser with a Uniform Resource Locator and have the browser display that page via loadUrl().In that way the browser will access the Internet through whatever means are available to that unambiguous or exact device at the present time like Wi-Fi, cellular network, Bluetoothtethered phone. The other way is to use loadData() method. In that situation we can supply the Hypertext Markup Language for the browser to view.

By displaying snippets of Hypertext Markup Language we can also retrieve as part of other processing, as per illustration we can also provide description of an entry in an Atom feed. Generate a whole User Interface using Hyper Text Markup Language, as an alternative of using the Android widget set.

Now there are two flavors of the loadData() method. The very simpler and easy way allows us to provide the content which may be of MIME type, encoding, etc.

Now we are giving a simple illustration that gives us the concept of file streaming process.

Listing 4: Sample showing files streaming process

  browser.loadData("<html><body>Welcome, SGC!</body></html>","text/html", "UTF-8");
  public class AndroidScoreSavingTestexample : MonoBehaviour 
                  string message_data;
                  loadMessage = "welcome to working area of Mrbool…..";
                  string data;
                  FileInfo f1; 
                  void Start()
                      f1 = new FileInfo(Application.dataPath + "\\" + "sgcfileinfo1.txt");
                      Screen.SetResolution(800, 600, true);
                  void OnGUI()
                      GUILayout.BeginArea(new Rect(0,0,500,500)); /*Draw a rectangle here*/
                      GUILayout.Label(message_data + " " + data);
                                   Message_data = "File creation complete";
                          message = "Saving_Data";
                                   Load(); /*Calling Load function*/
                                   Message_data = " File is not found……";   
                  void Save()
                      StreamWriter w1;
                                     w1 = f1.CreateText();   
                                     w1 = f1.CreateText();
                  void Load()
                  StreamReader r1 = File.OpenText(Application.dataPath + "\\" + " sgcfileinfo1.txt ");
                  string info = r1.ReadToEnd();
                  data = info;

Programmatically retrieve and modify the preferences values

In this section we will discuss that the actual procedure implemented for the PreferenceActivity class enables developers to straightforwardly create the preferences and also enables the users to transmute them during runtime (actually running the program time). The variety of the uses of general types of the preferences in our own system applications process steps are given below.

Following are the screen shots and steps to accomplish the tasks. At first, open eclipse exe, after that select File and new Android Project. Then follow the screens below to set the project.

Open project screen

Figure 1: Open project screen

Set the application name

Figure 2: Set the application name

Configure the project

Figure 3: Configure the project

Create activity

Figure 4: Create activity

Activity created

Figure 5: Activity created


Listing 5: Sample showing retrieving and modifying references

  Name of the file is
   /*this is the package name which is used in the project*/
  import android.content.Intent;
  import android.content.SharedPreferences;
  import android.os.Bundle;
  import android.view.View;
  import android.widget.EditText;
  import android.widget.Toast;
  public class usepreftheactivity extends Activity 
  /*access the Activity class in the use usepreftheactivity class*/
  /* called when the activity is first created. */
  public void onCreate(Bundle savedInstanceState) 
  /*This method is use to load the respective Preference.*/
  public void onClickLoad(View view) 
  Intent i = new Intent(“”);
  /*this method is required to display the respective Preference and print the text.*/
  public void onClickDisplay(View view) 
  SharedPreferences appPrefs =getSharedPreferences(“”,MODE_PRIVATE);
  DisplayText(appPrefs.getString(“editTextPref”, “”));
  public void onClickModify(View view) 
  SharedPreferences appPrefs =
  SharedPreferences.Editor prefsEditor = appPrefs.edit();
  prefsEditor.putString(“editTextPref”,((EditText) findViewById(;
  prefsEditor.commit(); /*This is use for execute the preferable or user given text.*/
  /*this part is use to show the text*/
  private void DisplayText(String str)  
  Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();


After writing the code, just press the F11 to return the application on the Android emulator again. In that undertaking we just go to clicking the Display Preferences option and the Values button will demonstrate the value exposed.


Now go to the third step, enter a string in the EditText view and if we want to update it just click on the Modify Preferences values option or load preference option.


After completing the third step we just click the Display Preferences Values again. In that situation one point should be remembered that text or value is saved through the preference option.

After completing the above steps and the scenario, let us discuss some points in the code level.

In the onClickDisplay () method, we first used the getSharedPreferences () method to get an occurrence of the SharedPreferences class. We can also do this by specifying the name of the Extensible Markup Language file. In this case we are receiving the data from the respective package [package;] which is used in our programming structure.


To retrieve a string preference, generally we use the getString() method for passing it the key to the preference that we want to repossess.

  public void onClickDisplay(View view) 
         SharedPreferences appPrefs =
         DisplayText(appPrefs.getString(“editTextPref”, “”));

If we illustrate the above code then at first we say that the MODE_PRIVATE constant indicates the preferences file that can only be opened by the presentation that produced it. In the onClickModify() method, we also created a SharedPreferences.Editor object through the edit() method of the SharedPreferences object. In that respect we have to change the value of a string preference and we use the putString() method. This also saves the changes to the preferences file and for the use of the process we are going to use the commit() method.

  public void onClickModify(View view) 
   SharedPreferences appPrefs =
  SharedPreferences.Editor prefsEditor = appPrefs.edit();
  prefsEditor.putString(“editTextPref”,((EditText)         findViewById(;

Caution: After writing the code, it should be set in the Android Emulator and run it through the eclipse IDE. But it is also known that the output can also be generated via the configuration of the android system Emulator. Different Emulator may change the output scenario as per their model process.

Here is a sample Figure showing the respective output.

Showing the output

Figure 6: Showing the output


In this Article we have elaborately discussed about android preferences. Android Preference is very important for the Android developer, designer and also Android user. In these circumstances we have explained the Save and load of user preference. We have also discussed about the preference and the features of the preference, which is very much vital in app development. At end of this article we have also shown a programming logic structure. However in the article we have tried to deliver user preference for the Android user.

Website: Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login