Android dev tutorial: Shared Preferences Screen in Android

This entry is part 22 of 50 in the series Android Development Primer

Now that we are familiar with what Shared Preferences are and how they work, its time to actually look into one of the main applications of the Shared Preferences – the Shared Preferences Screen most commonly used as the Settings screen of many applications to remember the user preferences.

So start up your Main activity and start coding. Complete Source Code is at the bottom.

  • In the layout for you main activity, have a button that launches another activity which will be the Preferences Screen.
  • Create another activity Second.java. Remember to choose PreferenceActivity as the parent class for this activity and not the regular Activity.
  • Much like we set the content view of a normal activity, we need to provide this activity with a layout.
  • Go ahead and create an XML file second.xml. In the resource type choose Preference and not Layout. Leave the root element as PreferenceScreen.
  • Go ahead and write the following code inside the <PreferenceScreen></PreferenceScreen> tags.
    <CheckBoxPreference
            android:key="first"
            android:title="first option"
            android:summary="This is the first option" />
    
    <CheckBoxPreference
            android:key="second"
            android:title="second option"
            android:summary="This is the second option" />
    
  • Remember that the android:key attribute that is present here is the key for the key-value pair that is present in the SharedPreferences. While accessing the value you will have to refer to it via this key.
  • Switch over to Second.java and paste the below code after super.OnCreate(Bundle savedInstanceState)
    addPreferencesFromResource(R.xml.second);
    
  • In the above method, we have provided a layout for the activity. It is obvious that we have not used setContentView() method. For now it’ll be sufficient for you to know that in order to provide a PreferenceScreen a layout, we make use of addPreferenceFromResource() method. It takes care of all the saving and rewriting of values in SharedPreferences.
  • Switch over to the MainActivity.java file, get a reference to the button and set the onClickListener() method to call the activity Second.class, with the help of an intent.
  • Save your work and execute it on am emulator/device

spscreen1 spscreen2

  • Remember that the saving of values to SharedPreferences and rewriting the values, are done by Android on its own since the activity we have created inherits PreferenceActivity.
  • Now, to access the values in the SharedPreferences, add the below lines wherever you need it.
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    boolean first = settings.getBoolean("first", false);
    
  • Remember that the method signature of the method above is getBoolean(key, defValue). So we need to provide the name of the key exactly. Recall that in second.xml we have given the value of first to the android:key attribute of our first CheckBoxPreference. Here we use the same value to get the value from the Shared Preferences.

COMPLETE SOURCE CODE

MainActivity.java

package com.nero.myfirstapp;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Main extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
        boolean first = settings.getBoolean("first", false);

        Button but = (Button) findViewById(R.id.button1);
        but.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
			 	Intent intent = new Intent(MainActivity.this, Second.class);
			 	startActivity(intent);
			}
		});
    }
}

Second.java

package com.nero.myfirstapp;

import android.app.Activity;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Second extends PreferenceActivity {
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.second);

    }
}

second.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <CheckBoxPreference
        android:key="first"
        android:title="first option"
        android:summary="This is the first option" />

    <CheckBoxPreference
        android:key="second"
        android:title="second option"
        android:summary="This is the second option" />

</PreferenceScreen>
Series Navigation<< Android dev primer: Shared Preferences – An IntroductionAndroid development: Introducing SQLite >>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy This Password *

* Type Or Paste Password Here *

44,588 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>