× 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 SharedPreferences: How to share data in Android

In this article we will learn about the Android’s way of sharing data. We will also learn the process to use the built-in content provider’s policy and implement with our own content providers.

Generally the SharedPreferences class provides general types of framework that allows us to save and retrieve the persistent key-value pairs of the primitive data types like booleans, floats, ints, longs, and strings. This data will be persevered to the user sessions if our application is killed. Nevertheless the session will be continued in that situation. At first we retrieve information about the SharedPreferences Object. Because without proper sharedPreferences object we cannot get exact knowledge of the shared information through the Android devices. Here we will discuss about the two methods like getSharedPreferences (), getPreferences ().

getSharedPreferences ()

The use of this method needs multiple preferences files identified by name, which you will specify with the first parameter.

getPreferences ()

Use this if you need only one preferences file for your application. As this will be the only preferences file for your application, you don't need to supply a name.

Now, the only one instance of the SharedPreferences object is returned to any callers for the same name, which actually means they will see each other as soon as they are completed it. To read the values you need to call the methods such as getBoolean (), getInt (), etc. of the instance of SharedPreferences.

Listing 1: Sample showing methods for creating shared preferences object

SharedPreferences shaprefer = getSharedPreferences (“sgcfile.txt”, 0);
boolean ob_silent = shaprefer.getBoolean("silentMode", false);

Basically some functions are used in our Android SharePreference system which performs a lot of standard functionalities. At first we will discuss the edit () method which is used to get a SharedPreferences object. Secondly with Editor, we will just add the values with methods such as putBoolean () and putString () and thirdly we will commit all new values using the commit () method.

Listing 2: Sample showing creation of Editor Object and set different values into it

SharedPreferences settings = getSharedPreferences(“SgcPrefsFile”, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);

Basically the Android system provides different types of traditions for storing data of an application scenario. One of this ways is called Shared Preferences. The Shared Preferences allows us to save and also retrieve the data in the form of key/value pair. Generally in order to use this shared preferences, you have to call the method getSharedPreferences () which also returns a SharedPreference instance pointing to the file that usually contains the values of preferences.

Listing 3: The general syntax is shown here for creating shared preferences object

SharedPreferences sharedpreferences_job = getSharedPreferences (SGCPREFERENCES, Context.MODE_PRIVATE);

In this programming model the first parameter is the key and the second parameter is the MODE option. Apart from this, there are other modes available which are discussed below in tabular format.

  • MODE_APPEND: This will append the new preferences with the already existing preferences.
  • MODE_ENABLE_WRITE_AHEAD_LOGGING: This mode is used in the database system, the database open flag. At that situation it is set and it would enable logging by default.
  • MODE_MULTI_PROCESS: This is another important mode here. This method will check for the modification of the preferences even if the sharedpreference instance is already been loaded in the structure.
  • MODE_PRIVATE: This is the private type of MODE. When we are setting this mode the file are going to a secure system level and also it can only be accessed by calling application.
  • MODE_WORLD_READABLE: This is readable types of model. This is specially designed for the read operation. These modes allow other applications to read the preferences.
  • MODE_WORLD_WRITEABLE: This is writeable mode. This mode can allow other applications to write the preferences system.

We can save something in the sharedpreferences by using SharedPreferences Editor Class. We will call the edit method of the SharedPreference request and obtain it in an editor object. The general syntax is shown below.

Listing 4: Sample showing Editor and its value settings.

Editor edit1=sharepreference.edit();

In that situation we will also discuss some part from the putString () method. There are methods available in the editor class which allows manipulation of data inside shared preferences. Methods are discussed below.

  • apply():This method is used to apply process. It is an abstract method. It will commit our changes back from the editor to the sharedPreference object that we are calling.
  • remove(String key): It is a parameterized function. It will remove the value whose key has been passed as a parameter.
  • clear():Basically this method is used for erase. It will remove all values from the editor.
  • putFloat(String key, float value): It is parameterized function. We can pass string and float value through the method. It will save a float value in a preference editor.
  • putInt(String key, int value): putInt () is a parameterized function which takes two parameters, string and float. Generally it will save an integer value in a preference editor process.
  • putLong(String key, long value): putLong () is also a parameterized function. It can also save a long value.

Sharing Data in Android:

Now we know that the stores of its data are not relevant to the application using it; as well as it is also important how this packages can access the data which is stored in it using a consistent programming interface. Generally the content provider behaves very similar to a database system. Through the database system we can query through it; we can also edit its content, as well as add or delete the content. Nevertheless, as per as database, a content provider can also use different ways or process to store its data through different communication mechanism. The data can also be stored in a database in file format or even over a network (it is a process to communicate through the system). Android ships with many useful content providers, including the following tools; it is also used for sharing purpose.

  • Browser: This tool is used to store data such as browser bookmarks, browser history, and so on, which is interrelated with the surfing process.
  • CallLog: The CallLog stores data such as missed calls, call details etc.
  • Contacts: The Contact tools stores contact details.
  • MediaStore: The MediaStore stores media files such as audio, video, and images.
  • Settings: The setting stores the devices settings and preferences.

Now many built-in content providers are also available, we can also create our own content providers. This provider is used to query a content provider; here we can also specify the query string in the form of a Uniform Resource Identifier with an option specified for a particular row or record. The format of the query Uniform Resource Identifier is shown below.


There are also various parts of the Uniform Resource Identifier present here. We can follow the points below.

  • At first the standard prefix for the content provider, which is required.
  • Secondly the data path specifies the kind of data requested here. As per the illustration, if we are getting all the contacts from the contacts content provider, then the data path would be people. The Uniform Resource Identifier would look like this way content: //contacts/people.
  • The third point that the id specifies the unambiguous or exact record requested. As per illustration, if we are looking for the contact number in the Contacts content provider, then in that situation the Uniform Resource Identifier would look like the following content:// contacts/people/3. Now let us check some illustrations of the query strings as shown below in the table.
Query String Description
content://media/internal/images This query string is specific for returning the list of all the internal images on the devices.
content://media/external/images This is another query string, which also returns the list of all the images stored on the external storage (as per illustration. SD card) on the device.
content://call_log/calls This query is very popular because it is very important for us to store call information. So it returns a list of all calls registered in the Call Log.
content://browser/bookmarks This is another query string which also returns a list of bookmarks that are stored in the browser (internet surfing software).

Table 1: Query string description with example of Query Strings

Retrieving Shared Preferences:

Accessing saved Shared Preferences is also done with the getSharedPreferences () method. Pass the name of the Shared Preference that we want to access, and use the type-safe get methods to extract saved values. Here each getter takes a key and a default value (used when no value is available for that key), as shown in the skeleton code below.

Listing 5: Sample is showing retrieval of shared preferences object and getting different parameter values from the object.

public void loadingthePreferences() 
/*Get the stored preferences*/
int mode = Activity.MODE_PRIVATE; 
SharedPreferences sgcSharedPreferences = getSharedPreferences(SGCPREFS,mode);

/* Retrieve the saved values.*/
boolean Itrue = sgcSharedPreferences.getBoolean(“isTrue”, false);
float Lfloat = sgcSharedPreferences.getFloat(“lastFloat”, 0f);
int totnumber = sgcSharedPreferences.getInt(“totalNumber”, 1);
long aNumber = sgcSharedPreferences.getLong(“aNumber”, 0);

String stringPreference;
stringPreference = sgcSharedPreferences.getString(“thetextEntryValuehere..”,“”);

Sharing through the Content Provider:

Content Provider is also taking a very standard role of sharing the data. This is a very simple program, which is the best way to understand the content providers. Now we will show the process, which can be used as a content provider from within our Android application.


At first we will just open the Eclipse, and create a new Android project with a name. Here we give our project name as Share_Preference.

Creating project

Figure 1: Creating project

Now click on Next button to proceed. Provide workspace location as shown below. Then click on Next.

Specify workspace location

Figure 2: Specify workspace location

Select activity from the options mentioned in the text box. Click on Next

Specify activity type

Figure 3: Specify activity type

Mention activity name and other parameter values as shown below and click Finish.

Specify activity name

Figure 4: Specify activity name

Now the activity will be created successfully as shown in the left hand explorer

Project created successfully

Figure 5: Project created successfully


In the second step we can just add the following declarations in the main.xml file.

Listing 6: This is a sample main.xml file with different attribute values. Attribute values are stored for future use in the application.

<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical” >
android:transcriptMode=”normal” />
android:layout_height=”wraping_content” />
android:layout_height=”wrapping_content” />


In step three we just set this code in the sgcProviderActivity.java class

Listing 7: Sample showing sgcProviderActivity.java class. This class is used to create adapter with different layout values set for use in the application

package ceimaa.netii.net.Provider;
import android.app.ListActivity;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.CursorAdapter;
import android.widget.SimpleCursorAdapter;

public class ProviderActivity extends ListActivity 
/* Function is called when the activity is first created here. */
public void onCreate(Bundle savedInstanceState)
Uri allContacts = Uri.parse(“content://contacts/people”);
Cursor c;
if (android.os.Build.VERSION.SDK_INT <11)
/*Before Honeycomb (Android Version) we can use it */
c = managedQuery(allContacts, null, null, null, null);
/*Honeycomb and later*/
CursorLoader cursorLoader = new CursorLoader(this, allContacts, null,null,null ,null);
c = cursorLoader.loadInBackground();
String[] columns=new String[] /*Create object columns that initialize via string*/
int[] views = new int[] 
R.id.contactName, R.id.contactID

SimpleCursorAdapter adapter; /*adapter variable*/

if (android.os.Build.VERSION.SDK_INT <11)
/*before Honeycomb*/
adapter = new SimpleCursorAdapter(this, R.layout.main, c, columns, views);
/*Honeycomb (Android Version) and later*/
adapter = new SimpleCursorAdapter(this, R.layout.main, c, columns, views, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);


This is the 4th step. In this step we can easily add the following code to the AndroidManifest.xml file.

Listing 8: Sample showing AndroidManifest.xml file. This is used to set version code, version name, permission, filter etc

<?xml version=“1.0“ encoding=“utf-8“?>
<manifest xmlns:android=“http://schemas.android.com/apk/res/android“
package=”net. ceimaa.netii.net.Provider”
android:versionName=”1.0” >
<uses-sdk android:minSdkVersion=”14” />
<uses-permission android:name=”android.permission.READ_CONTACTS”/>
android:label=”@string/application_name” >
android:name=”.ProviderActivity” >
<intent-filter >
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />


In step five, we will just launch an AVD (Android Virtual Device) and create a few members in the Android Emulator. To add the contact, we can just go to the Phone application and click on the Star icon at the top of the system. We can also click on the MENU button on the emulator and click the new contact menu item. Add name, phone number, and e-mail address of a few people as per our requirement.


After completing the above job we just press F11 to debug the application on the Android emulator. In the following Image 6, it shows the activity displaying the list of contacts we have just created.

Displaying list of contacts

Figure 6: Displaying list of contacts

Concept of saving files that can be shared with other Apps:

We have just discussed about saving files that are basically the new files received by the users through applications. All these files should be saved to a "public" location on the device where other apps can access them and the user can also copy them from the device. When we are doing so, we should use one of the shared public directories, such as Music/, Pictures/, and Ringtones etc.

There is no doubt that the modern mobile technology is totally dependent on the Operating system. Different levels of apps are also available in the cloud, which can easily communicate with those types of apps. But some time users cannot communicate with Internet each and every time. So in that situation sharing process is very much important for us. We also know that different types of hardware and software are present for sharing the data like Bluetooth, flash transfer etc. We generally communicate from one device to other via these types of hardware and software. So we need a very good knowledge of sharing concepts. Through this article we can get a very clear idea of the sharing concepts in Android.

Website: www.techalpine.com 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