Ever wondered how to store data in any Android application. Well here’s the answer to that. Through this Blog, I would like to bring you all how to store data in an Android application using Preferences.

Android provides many ways of storing data in an application. One of the ways to store data is through Preferences. Preferences allow us to save and retrieve data.

For using Preferences, you need to call a method getSharedPreferences().

Preferences store private primitive persistent data in a key, value pair.

Now, how do we get access to the Preference?

getPreference() from within Activity – to access activity specific preference.

getSharedPreferences() from within Activity or other application Context –

to access application-level preference.

getDefaultSharedPreferences() on PreferenceManager – to get the shared preferences that work in concert with Android’s overall preference framework.

Examples include:

1. Security Access Token

2. Endpoint URLs.

3. Other user

To Save the Preferences:

getPreferences(MODE_PRIVATE).edit().putString(“Name of Variable”, value).commit();

To Retrieve the Preferences:

“variable” = getPreferences(MODE_PRIVATE).getString(“Name of Variable”, value).

Types of Preferences:

Type Use Syntax CheckBox You are simply interested in a true/false value <CheckBoxPreference android:key=”applicationUpdates” …….. /> EditText If user want to enter value i.e. name, number, etc. <EditTextPreference android:title=”Your Name”

android:key=”username”

android:summary=”Please provide your username“ >

</EditTextPreference> List Where the user is shown a list of options and select one of them as their preferences <ListPreference android:key=”downloadType”……/>



Example:

Create a new folder in the res folder and name is as xml. In this newly created folder, add a file and name it myappreferences.xml

Definition: Implement setting page using Preferences.

The myapppreferences.xml file

The root node for the preference file must be <PreferenceScreen>.

You can also group items together. There are two ways of doing this:

– You can group items together with a title.

– Use <PreferenceCategory> to do this

<?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > <PreferenceCategory android:title="Settings" > <EditTextPreference android:title="Password" android:summary="Set Your Password" android:key="prefUserPassword"/> </PreferenceCategory> <PreferenceCategory android:title="Security Settings" > <CheckBoxPreference android:defaultValue="false" android:key="prefLockScreen" android:summary="Lock The Screen With Password" android:title="Screen Lock" > </CheckBoxPreference> <ListPreference android:key="prefUpdateFrequency" android:title="Reminder for Updation" android:summary="Set Update Reminder Frequency" android:entries="@array/updateFrequency" android:entryValues="@array/updateFrequencyValues" /> </PreferenceCategory> </PreferenceScreen>

activity_main.xml

Take one Button and one TextView:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#00bcd4" tools:context=".MainActivity" > <Button android:id="@+id/buttonSettings" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="150dp" android:textSize="25dp" android:text="Settings" /> <TextView android:id="@+id/textViewSettings" android:textSize="21dp" android:textColor="#1a237e" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_below="@+id/buttonSettings" android:layout_marginTop="66dp" android:text="No Settings" android:textAppearance="?android:attr/textAppearanceMedium" /> </RelativeLayout>

Add new Activity in AndroidManifest.xml

<activity android:name="com.example.preferencesexercise.UserSettingActivity" android:label="@string/app_name" ></activity>

The Basic Settings – MainActivity.java

public class MainActivity extends Activity { //Initialize for store the Result as SETTINGS_RESULT private static final int SETTINGS_RESULT = 1; Button settingButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Initialize Button Button btnSettings=(Button)findViewById(R.id.buttonSettings); // start the UserSettingActivity when user clicks on Button btnSettings.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub Intent i = new Intent(getApplicationContext(), UserSettingActivity.class); startActivityForResult(i, SETTINGS_RESULT); } }); } private void displayUserSettings() { SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); String settings = ""; settings=settings+"Password: " + sharedPrefs.getString("prefUserPassword", "NOPASSWORD"); settings=settings+"

Remind For Update:"+ sharedPrefs.getBoolean("prefLockScreen", false); settings=settings+"

Update Frequency: " + sharedPrefs.getString("prefUpdateFrequency", "NOUPDATE"); TextView textViewSetting = (TextView) findViewById(R.id.textViewSettings); textViewSetting.setText(settings); } }

UserSettingActivity.java

public class UserSettingActivity extends PreferenceActivity { @SuppressWarnings("deprecation") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.myapppreferences); } }

Conclusion:

When developing a mobile application, a common need is to store data or user’s preferences. In order to make use of the preferences framework, the first step is to extend the PreferenceActivity class.

Preferences are more useful when you want to store your data in local database. It’s very easy to use. Hope through this Blog I was able to make things clear on how to use Preferences to store data in any Android application.

Keep visiting Our website Acadgild for more updates on Big Data and other technologies. Click here to learn Android App Development.