Thursday, 24 November 2011

Using Preferences with Android

What is preferences in Android ?

Well preferences is Android's way of saving the applications setting .
So the next question that might arise in your mind is :

Why use android's preferences , instead of that why not same the settings in my own file  ??

Well there are several reasons for using android's built-in preferences

  1. It is simple (instead of using extra data file handelling )
  2. The UI is the same as android's settings , so it is intuitive and user friendly to the end user
  3. No need to define external permissions in the android manifest file , thus your application will not use extra not permissions 
So , the 2 questions - What and Why is covered , the next question that arises is How to use it ? Which is also quiet simple . As I feel , android has taken good care that its developers find it easy and powerful to develop applications . Lets now directly start trying preferences - 

Using preferences can be summed up in the following steps :

  1. Create a preferences.xml file in  res/xml 
  2. Create a Mypreference class that extends PreferencActivity 
  3. Create a button in main activity that will call the MyPreference Activity
  4. Display the preferences in the main activity
STEP 1

In the res/xml create a preference.xml , the preference.xml file will hold the different settings name , the settings/preferences can be grouped together , a preference can be a checkbox preference , edittext preference or a list preference , we can also define a customized preference ( will be studied later ) by extending the Preference class . Well , so the preference.xml file will look like the following :
  
 
  
     
          
            
         
     
  
         
             
          
        
 

Well , now lets guide you through the terms involved  which are not directly understandable :


  • android:key - which will be used to access preferences for other activities 
  • android:defaultValue - which will the value when the application is first installed
  • android:inputType - the input type of the softkey board , if you want to type number then use the input type as phone 
  • android:entries - well this contains the entries , which can be got from a xml file , in the above case the xml filename is array which is presents in /res/values/arrays.xml which is defined as below :



    
    option 1
    option 2
 option 3
 option 4
 option 5
 option 6
    

Note :

  1.  Please do not confuse the filename arrays.xml with the @array/myoptions , array here is because it is defined as a  string-array in the xml
STEP 2
Next task is simpler , create a MyPreference class which extends PreferenceActivity as below :
package com.tapan.PreferencesExample;

import android.os.Bundle;
import android.preference.PreferenceActivity;

public class MyPreference extends PreferenceActivity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 addPreferencesFromResource(R.xml.preference);
}
}
Please remember to add the following line to the AndroidManifest.xml

STEP 3 & 4

As for both the steps we are dealing with only one Activity ie the main Activity , I decided to combine both the steps . For this I have written the java code which is pretty self explanatory :


package com.tapan.PreferencesExample;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class PreferencesExampleActivity extends Activity {
    SharedPreferences sharedPreferences;
 
 /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button b=(Button) findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // Call the MyPreference Activity when the Button is clicked 
    Intent i=new Intent(PreferencesExampleActivity.this,MyPreference.class);
    startActivity(i);
   }
  });
    }

    /* Called When the Activity is resumed 
     * It will be used to refresh the preferences list
     * Also called when the activity is first created
     * */
    @Override
 protected void onResume() {
  super.onResume();
  TextView tv=(TextView)findViewById(R.id.PrefrencesText);
  // Getting the shared preferences 
  sharedPreferences= PreferenceManager.getDefaultSharedPreferences(PreferencesExampleActivity.this);
        
  // Getting the EditText preference( android:key="etpreference")
  String etpref=sharedPreferences.getString("etpreference","" );
  
  // Getting the Checked preference( android:key="cpreference")
  String cpref=Boolean.toString(sharedPreferences.getBoolean("cpreference", false));
  
  // Getting the List  preference( android:key="opreference")
  String opref=sharedPreferences.getString("opreference", "");
        tv.setText("The preferences are- \nEditText preference:"+etpref+"\nChecked Preference:"+cpref+"\nList Preference:"+opref);
 }
}


Thus , we got the android preference working , look at the following screen shots to get a better idea :



You can find the project HERE

No comments:

Post a Comment