Example: Preferences in Android

Posted on Jan 14, 2010 (4 years ago). Seen 48,958 times. 4 comments. Permalink Feed
Member since Dec 23, 2009
Location: Oakland
Stream Posts: 0
Tagged as: Android Tutorial

Preferences in Android are used to keep track of application and user preferences.

In any application, there are default preferences that can accessed through the PreferenceManager instance and its related method getDefaultSharedPreferences(Context)

With the SharedPreference instance one can retrieve the int value of the any preference with the getInt(String key, int defVal). The preference we are interested in this case is counter

In our case, we can modify the SharedPreference instance in our case using the edit() and use the putInt(String key, int newVal) We increased the count for our application that presist beyond the application and displayed accordingly.

To further demo this, restart and you application again, you will notice that the count will increase each time you restart the application.


PreferencesDemo.java

Code:
package org.example.preferences;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;

public class PreferencesDemo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// Get the app's shared preferences
SharedPreferences app_preferences =
PreferenceManager.getDefaultSharedPreferences(this);

// Get the value for the run counter
int counter = app_preferences.getInt("counter", 0);

// Update the TextView
TextView text = (TextView) findViewById(R.id.text);
text.setText("This app has been started " + counter + " times.");

// Increment the counter
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("counter", ++counter);
editor.commit(); // Very important
}
}

main.xml

Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>

Screenshot


Source
http://thenewcircle.com/static/tutorials/PreferencesDemo.zip

Comments

Posted on Aug 30, 2010
Photo Sam Morris
Developer
Gamershots.com
Member since Aug 30, 2010
hi Serete,
From your example, would that integer be accessible from another application on the same device?
Posted on Aug 30, 2010
Photo Sam Morris
Developer
Gamershots.com
Member since Aug 30, 2010
Posted on Apr 4, 2011
Photo Sankar G
Member since Apr 4, 2011
Nice Example for the beginners.
Posted on Apr 2, 2012
Photo Korada Rameshbabu
Xpio
Member since Mar 30, 2012
where the file will be stored