android學習筆記10————–SharedPreferences實現軟件參數的保存和獲取

很多時候我們開發軟件需要向用戶提供軟件參數設置功能,如電子書軟件的背景顏色設置,喜好設置等。在Android的應用的使用SharedPreferences類來

保存軟件設置參數非常方便。

使用SharedPreferences類保存數據,其實是將這些參數保存在xml文件中,文件存放在/data/data/包名/shared_prefs目錄下:

 

 

點擊保存後,

 

 

將test.xml導出,打開

 

 

即為我們保存的數據。

點擊讀取按鈕:

 

 

讀取正確。

代碼:

[java]
import android.app.Activity; 
import android.content.Context; 
import android.content.SharedPreferences; 
import android.content.SharedPreferences.Editor; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.widget.Toast; 
 
public class SharedPreferencesActivity extends Activity 

    private EditText nameEditText; 
    private EditText ageEditText; 
    private Button   save; 
    private Button   read; 
    private Button   exit; 
    private TextView resulTextView; 
     
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
         
        nameEditText=(EditText)findViewById(R.id.name); 
        ageEditText=(EditText)findViewById(R.id.age); 
        save=(Button)findViewById(R.id.save); 
        read=(Button)findViewById(R.id.read); 
        exit=(Button)findViewById(R.id.exit); 
        resulTextView=(TextView)findViewById(R.id.result); 
         
        save.setOnClickListener(listener); 
        read.setOnClickListener(listener); 
        exit.setOnClickListener(listener); 
         
    } 
     
    private OnClickListener listener=new OnClickListener() 
    {        
        @Override 
        public void onClick(View v) 
        { 
            Button button=(Button)v; 
            SharedPreferences sharedPreferences=SharedPreferencesActivity. 
            this.getSharedPreferences("test", Context.MODE_PRIVATE); 
            switch (button.getId()) 
            { 
                case R.id.save: 
                    String name=nameEditText.getText().toString(); 
                    String age=ageEditText.getText().toString();                                         
                    Editor editor=sharedPreferences.edit(); 
                    editor.putString("name", name); 
                    editor.putInt("age", Integer.parseInt(age)); 
                    editor.commit(); //內容提交  
                    Toast.makeText(SharedPreferencesActivity.this, "保存成功",  
                            Toast.LENGTH_SHORT).show(); 
                    break; 
                     
                case R.id.read: 
                    String namevalue= sharedPreferences.getString("name", "");//如果存在name返回name的值,如果不存在該元素,返回“”  
                    int agevalue= sharedPreferences.getInt("age", -1); 
                    resulTextView.setText("姓名是:"+namevalue+"\n"+"年齡是:"+agevalue); 
                    Toast.makeText(SharedPreferencesActivity.this, "讀取成功",  
                            Toast.LENGTH_SHORT).show(); 
                    break; 
                     
                case R.id.exit: 
                    android.os.Process.killProcess(android.os.Process.myPid()); 
                    break; 
     
                default: 
                    break; 
            } 
             
        } 
    }; 

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

public class SharedPreferencesActivity extends Activity
{
 private EditText nameEditText;
 private EditText ageEditText;
 private Button   save;
 private Button   read;
 private Button   exit;
 private TextView resulTextView;
 
 @Override
 public void onCreate(Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  
  nameEditText=(EditText)findViewById(R.id.name);
  ageEditText=(EditText)findViewById(R.id.age);
  save=(Button)findViewById(R.id.save);
  read=(Button)findViewById(R.id.read);
  exit=(Button)findViewById(R.id.exit);
  resulTextView=(TextView)findViewById(R.id.result);
  
  save.setOnClickListener(listener);
  read.setOnClickListener(listener);
  exit.setOnClickListener(listener);
  
 }
 
 private OnClickListener listener=new OnClickListener()
 {  
  @Override
  public void onClick(View v)
  {
   Button button=(Button)v;
   SharedPreferences sharedPreferences=SharedPreferencesActivity.
   this.getSharedPreferences("test", Context.MODE_PRIVATE);
   switch (button.getId())
   {
    case R.id.save:
     String name=nameEditText.getText().toString();
     String age=ageEditText.getText().toString();          
     Editor editor=sharedPreferences.edit();
     editor.putString("name", name);
     editor.putInt("age", Integer.parseInt(age));
     editor.commit(); //內容提交
     Toast.makeText(SharedPreferencesActivity.this, "保存成功",
       Toast.LENGTH_SHORT).show();
     break;
     
    case R.id.read:
     String namevalue= sharedPreferences.getString("name", "");//如果存在name返回name的值,如果不存在該元素,返回“”
     int agevalue= sharedPreferences.getInt("age", -1);
     resulTextView.setText("姓名是:"+namevalue+"\n"+"年齡是:"+agevalue);
     Toast.makeText(SharedPreferencesActivity.this, "讀取成功",
       Toast.LENGTH_SHORT).show();
     break;
     
    case R.id.exit:
     android.os.Process.killProcess(android.os.Process.myPid());
     break;
 
    default:
     break;
   }
   
  }
 };
}

 

佈局文件:www.aiwalls.com

[java]
<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
    <LinearLayout  
                android:layout_width="match_parent"  
                android:id="@+id/linearLayout1"  
                android:layout_height="wrap_content"> 
        <TextView  
                android:text="姓名:"  
                android:textSize="20sp" 
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"></TextView> 
                 
        <EditText  
                android:id="@+id/name"  
                android:layout_width="fill_parent" 
                android:layout_height="wrap_content"></EditText> 
                 
    </LinearLayout> 
    <LinearLayout  
                android:layout_width="match_parent"  
                android:id="@+id/linearLayout2"  
                android:layout_height="wrap_content"> 
                 
        <TextView  
                android:text="年齡:"  
                android:textSize="20sp" 
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"></TextView> 
                 
        <EditText  
                android:id="@+id/age"  
                android:layout_width="fill_parent" 
                android:layout_height="wrap_content"></EditText> 
                 
    </LinearLayout> 
    <LinearLayout  
                android:layout_width="match_parent"  
                android:id="@+id/linearLayout3"  
                android:layout_height="wrap_content"> 
                 
        <Button  
                android:text="保存數據"  
                android:id="@+id/save"  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"></Button> 
                 
        <Button  
                android:text="讀取數據"  
                android:id="@+id/read"  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"></Button> 
                 
        <Button  
                android:text="退出"  
                android:id="@+id/exit"  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"></Button> 
                 
    </LinearLayout> 
    <TextView  
                android:text="顯示讀取值"  
                android:id="@+id/result"  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"></TextView> 
 
</LinearLayout> 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <LinearLayout
       android:layout_width="match_parent"
       android:id="@+id/linearLayout1"
       android:layout_height="wrap_content">
        <TextView
          android:text="姓名:"
          android:textSize="20sp"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"></TextView>
          
        <EditText
          android:id="@+id/name"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"></EditText>
          
    </LinearLayout>
    <LinearLayout
       android:layout_width="match_parent"
       android:id="@+id/linearLayout2"
       android:layout_height="wrap_content">
       
        <TextView
          android:text="年齡:"
          android:textSize="20sp"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"></TextView>
          
        <EditText
          android:id="@+id/age"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"></EditText>
          
    </LinearLayout>
    <LinearLayout
       android:layout_width="match_parent"
       android:id="@+id/linearLayout3"
       android:layout_height="wrap_content">
       
        <Button
          android:text="保存數據"
          android:id="@+id/save"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"></Button>
          
        <Button
          android:text="讀取數據"
          android:id="@+id/read"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"></Button>
          
        <Button
          android:text="退出"
          android:id="@+id/exit"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"></Button>
          
    </LinearLayout>
    <TextView
       android:text="顯示讀取值"
       android:id="@+id/result"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"></TextView>

</LinearLayout>

 

 

每次啟動程序時,自動讀取參數,隻要做簡單改動:

[java]
import android.app.Activity; 
import android.content.Context; 
import android.content.SharedPreferences; 
import android.content.SharedPreferences.Editor; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.widget.Toast; 
 
public class SharedPreferencesActivity extends Activity 

    private EditText nameEditText; 
    private EditText ageEditText; 
    private Button   save; 
    private Button   read; 
    private Button   exit; 
    private TextView resulTextView; 
     
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
         
        nameEditText=(EditText)findViewById(R.id.name); 
        ageEditText=(EditText)findViewById(R.id.age); 
        save=(Button)findViewById(R.id.save); 
        read=(Button)findViewById(R.id.read); 
        exit=(Button)findViewById(R.id.exit); 
        resulTextView=(TextView)findViewById(R.id.result); 
         
        save.setOnClickListener(listener); 
        read.setOnClickListener(listener); 
        exit.setOnClickListener(listener); 
         
        SharedPreferences sharedPreferences=SharedPreferencesActivity. 
        this.getSharedPreferences("test", Context.MODE_PRIVATE); 
        String namevalue= sharedPreferences.getString("name", ""); 
        int agevalue= sharedPreferences.getInt("age", -1); 
        nameEditText.setText(namevalue); 
        ageEditText.setText(String.valueOf(agevalue));       
    } 
     
    private OnClickListener listener=new OnClickListener() 
    {        
        @Override 
        public void onClick(View v) 
        { 
            Button button=(Button)v; 
            SharedPreferences sharedPreferences=SharedPreferencesActivity. 
            this.getSharedPreferences("test", Context.MODE_PRIVATE); 
            switch (button.getId()) 
            { 
                case R.id.save: 
                    String name=nameEditText.getText().toString(); 
                    String age=ageEditText.getText().toString();                                         
                    Editor editor=sharedPreferences.edit(); 
                    editor.putString("name", name); 
                    editor.putInt("age", Integer.parseInt(age)); 
                    editor.commit(); //內容提交  
                    Toast.makeText(SharedPreferencesActivity.this, "保存成功",  
                            Toast.LENGTH_SHORT).show(); 
                    break; 
                     
                case R.id.read: 
                    String namevalue= sharedPreferences.getString("name", ""); 
                    int agevalue= sharedPreferences.getInt("age", -1); 
                    resulTextView.setText("姓名是:"+namevalue+"\n"+"年齡是:"+agevalue); 
                    Toast.makeText(SharedPreferencesActivity.this, "讀取成功",  
                            Toast.LENGTH_SHORT).show(); 
                    break; 
                     
                case R.id.exit: 
                    android.os.Process.killProcess(android.os.Process.myPid()); 
                    break; 
     
                default: 
                    break; 
            } 
             
        } 
    }; 
}
 

 

若想保存的xml文件被其他文件訪問,應修改:

SharedPreferences sharedPreferences=SharedPreferencesActivity.
this.getSharedPreferences("test", Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);

 

 

 

可以看到其讀寫權限發生變化

測試的其他Activity

[java]
import android.app.Activity; 
import android.content.Context; 
import android.content.SharedPreferences; 
import android.content.pm.PackageManager.NameNotFoundException; 
import android.os.Bundle; 
import android.util.Log; 
 
public class LogActivity extends Activity 

    private static final String TAG="LogActivity"; 
 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
        //Log.i(TAG, "TAG打印測試");  
         
        try 
        { 
            Context context=this.createPackageContext("com.luku.SharedPreferences", 
                    Context.CONTEXT_IGNORE_SECURITY); 
            SharedPreferences sharedPreferences=context.getSharedPreferences 
                    ("test", Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE); 
            String namevalue= sharedPreferences.getString("name", ""); 
            int agevalue= sharedPreferences.getInt("age", -1); 
            Log.i(TAG, "名字是:"+namevalue+","+"年齡為:"+agevalue); 
        } catch (NameNotFoundException e) 
        { 
            // TODO Auto-generated catch block  
            e.printStackTrace(); 
        } 
         
         
    } 

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Log;

public class LogActivity extends Activity
{
 private static final String TAG="LogActivity";

 @Override
 public void onCreate(Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  //Log.i(TAG, "TAG打印測試");
  
  try
  {
   Context context=this.createPackageContext("com.luku.SharedPreferences",
     Context.CONTEXT_IGNORE_SECURITY);
   SharedPreferences sharedPreferences=context.getSharedPreferences
     ("test", Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
   String namevalue= sharedPreferences.getString("name", "");
   int agevalue= sharedPreferences.getInt("age", -1);
   Log.i(TAG, "名字是:"+namevalue+","+"年齡為:"+agevalue);
  } catch (NameNotFoundException e)
  {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  
 }
}

 

 

由其他程序訪問成功!

 

摘自 奔跑的蝸牛

發佈留言