Wednesday, December 28, 2011

Android Tutorial: Preferences

Tutorial: Preferences

11.1. Using preferences

We will continue using the example project "de.vogella.android.social".

Create an Android XML resource "preferences.xml" of type "PreferenceScreen".

How to create a XML file for storing preference value definitions

Open the file via right-mouse click and Open-withAndroid XML Resource Editor. Press Add, add a "PreferenceCategory" and add two preferences "EditTextPreferences" to this category : "User" and "Password".

Adding a category to the preference XML file

Adding the field "user" to the preference XML file

Adding the field "password" to the preference XML file

You can also maintain other properties to EditTextField, e.g. the inputMethod. Add for example the following attribute to the XML definition of your password to make the input quoted with *.

      android:inputType="textPassword"     

Create the class "MyPreferencesActivity" with extends PreferenceActivity. This activity will load the "preference.xml" and will allow to maintain the values.

     package de.vogella.android.socialapp;  import android.os.Bundle; import android.preference.PreferenceActivity;  public class MyPreferencesActivity extends PreferenceActivity {  @Override  public void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);      addPreferencesFromResource(R.xml.preferences);  } }     

To make this class available as an activity for Android you need to register it in your "AndroidManifest.xml" file. Select "AndroidManifest.xml" and the tab "Application". Scroll to the botton of the view and add your new activity via the "Add" button.

How to define a new activity in the AndroidManifest.xml

To make use of our new preference activity and the preference values we adjust the "OverviewActivity". The first button will show the current values of the preferences via a Toast and the second button will revert the maintained user name to demonstrate how you could change the preferences via code.

     package de.vogella.android.socialapp;  import android.app.Activity; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast;  public class OverviewActivity extends Activity {  SharedPreferences preferences;  @Override  public void onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);   setContentView(R.layout.main);   Button button = (Button) findViewById(R.id.Button01);   // Initialize preferences   preferences = PreferenceManager.getDefaultSharedPreferences(this);    button.setOnClickListener(new OnClickListener() {    public void onClick(View v) {     String username = preferences.getString("username", "n/a");     String password = preferences.getString("password", "n/a");     showPrefs(username, password);    }   });    Button buttonChangePreferences = (Button) findViewById(R.id.Button02);   buttonChangePreferences.setOnClickListener(new OnClickListener() {    public void onClick(View v) {          updatePreferenceValue();    }   });  }    private void showPrefs(String username, String password){   Toast.makeText(     OverviewActivity.this,     "Input: " + username + " and password: "       + password, Toast.LENGTH_LONG).show();   }    private void updatePreferenceValue(){   Editor edit = preferences.edit();   String username = preferences.getString("username", "n/a");   // We will just revert the current user name and save again   StringBuffer buffer = new StringBuffer();   for (int i = username.length() - 1; i >= 0; i--) {    buffer.append(username.charAt(i));   }   edit.putString("username", buffer.toString());   edit.commit();   // A toast is a view containing a quick little message for the   // user. We give a little feedback   Toast.makeText(OverviewActivity.this,     "Reverted string sequence of user name.",     Toast.LENGTH_LONG).show();  }     

To open the new preference activity we will use the method onOptionsItemSelected(). Even though we currently have only one option in our menu we use a switch to be ready for several new menu entries. To see the current values of the preferences we define a button and use the class "PreferenceManager" to get the sharedPreferences.

     @Override public boolean onCreateOptionsMenu(Menu menu) {  MenuInflater inflater = getMenuInflater();  inflater.inflate(R.menu.mainmenu, menu);  return true; }  // This method is called once the menu is selected @Override public boolean onOptionsItemSelected(MenuItem item) {  switch (item.getItemId()) {  // We have only one menu option  case R.id.preferences:   // Launch Preference activity   Intent i = new Intent(OverviewActivity.this, MyPreferencesActivity.class);   startActivity(i);   // Some feedback to the user   Toast.makeText(OverviewActivity.this, "Enter your user credentials.",    Toast.LENGTH_LONG).show();   break;   }  return true; }    

11.2. Run

Run your application. Press the "menu" hardware button and then select your menu item "Preferences". You should be able to enter your user settings then press the back hardware button to return to your main activity. The saved values should be displayed in a small message windows (Toast) if you press your first button. If you press the second button the username should be reversed.

The running application showing the maintenance dialog for the field "user" in the preference activity

12. Dialogs via the AlertDialog

We have already used a "Toast" which is a small message window which does not take the focus. In this chapter we will use the class "AlertDialog". AlertDialog is used to open a dialog from our activity. This modal dialog gets the focus until the user closes it.

An instance of this class can be created by the builder pattern, e.g. you can chain your method calls.

You should always open a dialog from the class onCreateDialog(int) as the Android system manages the dialog in this case for you. This method is automatically called by Android if you call showDialog(int).

Create a new Android project "de.vogella.android.alertdialog" with the activity "ShowMyDialog". Maintain the following layout for "main.xml".

             

Change the code of your activity to the following.

    package de.vogella.android.alertdialog;  import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.Toast;  public class ShowMyDialog extends Activity {  /** Called when the activity is first created. */  @Override  public void onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);   setContentView(R.layout.main);   }   public void openMyDialog(View view) {   showDialog(10);  }   @Override  protected Dialog onCreateDialog(int id) {         switch (id) {         case 10:             // Create out AlterDialog             Builder builder = new AlertDialog.Builder(this);             builder.setMessage("This will end the activity");             builder.setCancelable(true);             builder.setPositiveButton("I agree", new DialogInterface.OnClickListener() {                 public void onClick(DialogInterface dialog, int which) {                     ShowMyDialog.this.finish();                 }             });             builder.setNegativeButton("No, no", new DialogInterface.OnClickListener() {                 public void onClick(DialogInterface dialog, int which) {                     Toast.makeText(getApplicationContext(),"Activity will continue",Toast.LENGTH_LONG).show();                 }             });             AlertDialog dialog = builder.create();             dialog.show();         }         return super.onCreateDialog(id);     }  }   

If you run your application and click your button you should see your dialog.

Showing the running application with the dialog open

More on dialogs can be found on Android Dialogs standard documentation.

No comments:

Post a Comment

My Headlines

RF Optimization 2G,3G,4G and Wimax

Subscribe Now: google

Add to Google Reader or Homepage