Android preferences


Android preferences

Android preferences have the function to monitor the application and the user preferences. In every application of your smartphone, you will find default preferences. The only way to get access to these is via the PreferenceManager instance.

This method has a direct relation with the getDefaultSharedPreferences(Context). For any preference, the SharedPreference instance can recover the int value through the getInt key.

In this sample, we will change the file that contains the values of preference through the edit() and usage of the putInt. Here, we will increase the count of the times we enter the app and the exact number will show on the screen.

Every time you will open your application, you will witness the increase in count.

Code

Following is the code of PreferencesDemo.java:

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 text preview is written below:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://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>

Image

Image Not Found