วันพุธที่ 4 กรกฎาคม พ.ศ. 2555

Share Preference

-->

Share Preference

Complicated and robust Android applications often need to utilize some type of data storage. Depending on the situation, different data storage methods are available to the developer:

  • Shared Preferences for lightweight usage, such as saving application settings and the user interface (UI) state
  • A built-in SQLite database for more complicated usage, such as saving application records
  • The standard Java flat file storage methods: InputFileStream and OutputFileStream

These are discussed in this chapter.Also discussed is the Content Provider Android component that is used to share data between applications. It should be noted that another basic data storage method managed by the Android system, the onSaveInstanceState() and onRestoreInstanceState() pair. The optimal method to use depends on the situation, as discussed in each case that follows.

SharedPreferences is an interface that an application can use to quickly and efficiently
save data in name-values pairs, similar to a Bundle.


Creating and Retrieving Shared Preferences
The shared preferences for an activity can be accessed using the getPreferences() method, which specifies the operating mode for the default preferences file. If instead multiple preference files are needed, each can be specified using the getSharedPreferences() method. If the shared preferences XML file exists in the data
directory, it is opened; otherwise, it is created.The operating mode provides control over the different kinds of access permission to the preferences:

  • MODE_PRIVATE—Only the calling application has access to the XML file.
  • MODE_WORLD_READABLE—All applications can read the XML file.
  • MODE_WORLD_WRITEABLE—All applications can write to the XML file.

After a SharedPreferences object is retrieved, an Editor object is needed to write the name-value pairs to the XML file using the put() method. Currently, there are five primitive types supported: int, long, float, String, and boolean.The following code shows how to create and store shared preferences data:
SharedPreferences prefs = getSharedPreferences("myDataStorage", MODE_PRIVATE);
Editor mEditor = prefs.edit();
mEditor.putString("username","datastorageuser1");
mEditor.putString("password","password1234");
mEditor.commit();

The following shows how to retrieve shared preferences data:
SharedPreferences prefs = getSharedPreferences("myDataStorage", MODE_PRIVATE);
String username = prefs.getString("username", "");
String password = prefs.getString("password", "");

Share Preference Example Code

SharePreferenceActivity.java Code

package android.code.preference;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class SharePreferenceActivity extends Activity {
   
      private String PREFS_NAME = "preference";
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        final EditText et = (EditText)findViewById(R.id.et);
        Button set = (Button)findViewById(R.id.set);
        Button get = (Button)findViewById(R.id.get);
       
        set.setOnClickListener(new OnClickListener() {
                 
                  public void onClick(View arg0) {
                        SharedPreferences setPref = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = setPref.edit();
                        editor.putString("data", et.getText().toString());
                        editor.commit();
                  }
            });
       

        get.setOnClickListener(new OnClickListener() {
                 
                  public void onClick(View v) {
                    SharedPreferences pref = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
                    String data = pref.getString("data", "");
                   
                    et.setText(data);
                  }
            });
       
    }
}


main.xml code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#001155"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"
        android:textColor="#f5f062"
        android:textSize="30dp"
        android:textStyle="bold"
        android:text="Share Preference" />


    <EditText
        android:id="@+id/et"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"        
        android:text="Share Data" />
   
    <Button
        android:id="@+id/set"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:textColor="#FF0000"
        android:textStyle="bold"
        android:text="Set Share Perference" />
   
    <Button
        android:id="@+id/get"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:textColor="#076f02"
        android:textStyle="bold"
        android:text="Get Shared Preferences" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:src="@drawable/android" />
   
</LinearLayout>


Download Share Preference Example Code -->




Android Control ควบคุมอุปกรณ์ต่างๆ ด้วย Android

สอนเขียน Android  สอนเขียนโปรแกรม Android