android SharedPreferences詳解(android儲存使用者狀態資訊方法)

來源:互聯網
上載者:User


在andorid很多應用開發中都需要記錄使用者登入資訊,使用靜態變數手機關機使用者狀態清除,解決方案是使用SharedPreferences儲存android使用者資訊。

一、SharedPreferences基礎知識介紹

擷取SharedPreferences的兩種方式:
1 調用Context對象的getSharedPreferences()方法
2 調用Activity對象的getPreferences()方法
兩種方式的區別:
調用Context對象的getSharedPreferences()方法獲得的SharedPreferences對象可以被同一應用程式下的其他組件共用.
調用Activity對象的getPreferences()方法獲得的SharedPreferences對象只能在該Activity中使用.
 
SharedPreferences的四種操作模式:
Context.MODE_PRIVATE
Context.MODE_APPEND
Context.MODE_WORLD_READABLE
Context.MODE_WORLD_WRITEABLE
 
Context.MODE_PRIVATE:為預設操作模式,代表該檔案是私人資料,只能被應用本身訪問,在該模式下,寫入的內容會覆蓋原檔案的內容
Context.MODE_APPEND:模式會檢查檔案是否存在,存在就往檔案追加內容,否則就建立新檔案.
Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用來控制其他應用是否有許可權讀寫該檔案.
MODE_WORLD_READABLE:表示當前檔案可以被其他應用讀取.
MODE_WORLD_WRITEABLE:表示當前檔案可以被其他應用寫入.

二、資料儲存至SharedPreferences:

使用者登入成功後記錄登入資訊方法
SharedPreferences preferences=getSharedPreferences("user",Context.MODE_PRIVATE);
Editor editor=preferences.edit();
String userName="使用者名稱";
editor.putString("userName", userName);
editor.commit();

三、從SharedPreferences擷取資料:

SharedPreferences preferences=getSharedPreferences("user", Context.MODE_PRIVATE);
String name=preferences.getString("name",null);

四、清除SharedPreferences值

SharedPreferences preferences=getSharedPreferences("user", Context.MODE_PRIVATE);
preferences.edit().clear().commit();
使用者點擊使用者程式退出後清除SharedPreferences登入資訊


五、SharedPreferences來儲存使用者參數及讀取


軟體需求:使用者輸入姓名和年齡點擊儲存按鈕將資訊儲存到xml中當再次登陸的時候輸入的資訊顯示在文字框中

Activity檔案

 

[java] view plain copy
package com.example.shareperences; 
 
import java.util.Map; 
 
import android.app.Activity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 
 
import com.example.service.PrefercesService; 
 
public class MainActivity extends Activity { 
    private Button button; 
    private EditText name,age; 
    private PrefercesService prefercesService; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main); 
        button=(Button)this.findViewById(R.id.button); 
        name=(EditText)this.findViewById(R.id.name); 
        age=(EditText)this.findViewById(R.id.age); 
        prefercesService=new PrefercesService(this); 
        Map<String,String> params=prefercesService.getPreferences(); 
        name.setText(params.get("name")); 
        age.setText(params.get("age")); 
    } 
 
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
        // Inflate the menu; this adds items to the action bar if it is present. 
        getMenuInflater().inflate(R.menu.main, menu); 
        return true; 
    } 
    public void save(View v){ 
        /*
         * 如果想在Activity中得到SharedPreferences對象則可以用方法
         * this.getPreferences(mode)這裡只有一個參數 檔案儲存體類型,此時檔案的名字預設為
         * 當前activity的名字 不包括包名
         */ 
        String nameString=name.getText().toString(); 
        String ageString=age.getText().toString(); 
        prefercesService.save(nameString,Integer.parseInt(ageString)); 
        Toast.makeText(MainActivity.this, R.string.success, Toast.LENGTH_LONG).show(); 
    } 
 

[java] view plain copy
package com.example.service; 
 
import java.util.HashMap; 
import java.util.Map; 
 
import android.content.Context; 
import android.content.SharedPreferences; 
import android.content.SharedPreferences.Editor; 
 
public class PrefercesService { 
    private Context context; 
    public PrefercesService(Context context) { 
        super(); 
        this.context = context; 
    } 
  /**
   * 儲存參數 
   * @param name 姓名
   * @param age  年齡
   */ 
    public void save(String name, int age) { 
        //第一個參數 指定名稱 不需要寫尾碼名 第二個參數檔案的操作模式 
        SharedPreferences preferences=context.getSharedPreferences("itcast", Context.MODE_PRIVATE); 
        //取到編輯器 
        Editor editor=preferences.edit(); 
        editor.putString("name", name); 
        editor.putInt("age", age); 
        //把資料提交給檔案中 
        editor.commit(); 
    } 
    /**
     * 擷取各項配置參數
     * @return
     */ 
   public Map<String,String> getPreferences(){ 
     SharedPreferences pre=context.getSharedPreferences("itcast", Context.MODE_PRIVATE); 
     //如果得到的name沒有值則設定為空白 pre.getString("name", ""); 
     Map<String,String> params=new HashMap<String,String>(); 
     params.put("name", pre.getString("name", "")); 
     params.put("age", String.valueOf(pre.getInt("age", 0))); 
        
       return params; 
        
        
   } 

布局檔案注意button應該這樣設定

[html] view plain copy
<Button  
         android:layout_width="match_parent" 
         android:layout_height="wrap_content" 
         android:id="@+id/button" 
         android:text="@string/save" 
         android:onClick="save" 
         /> 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.