
Serete Itebete
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
counterIn 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
Sourcehttp://marakana.com/static/tutorials/PreferencesDemo.zip
Edited 5 times. Last edit by Sankar G on Apr 4, 2011 at 2:45:11 AM (about one year ago).

Sam Morris
Developer
Gamershots.com
hi Serete,
From your example, would that integer be accessible from another application on the same device?
Edited one time. Last edit by Sam Morris on Aug 30, 2010 at 2:36:28 PM (about one year ago).

Sam Morris
Developer
Gamershots.com

Sankar G
Nice Example for the beginners.

Korada Rameshbabu
Xpio
where the file will be stored