1. 程式人生 > >SharedPreferences 寫入讀取

SharedPreferences 寫入讀取

cnblogs 數字 enc toast str clear make 點擊事件 步驟

任務:

使用SharedPreferences將姓名和年齡信息保存到文件

首先設計界面xlm

1 ?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:tools="http://schemas.android.com/tools"
 4     android:id="@+id/activity_main"
 5     android:layout_width="match_parent"
 6     android:layout_height="match_parent"
 7     android:orientation="vertical"
 8     tools:context="hello.xingxibaocunduqu.MainActivity">
 9 
10     <EditText
11 android:id="@+id/name" 12 android:layout_width="match_parent" 13 android:layout_height="wrap_content" 14 android:hint="@string/name" /> 15 16 <EditText 17 android:id="@+id/age" 18 android:layout_width="match_parent" 19 android:layout_height="wrap_content" 20 android:hint="@string/age" 21 android:digits="0123456789"/> 22 //
為限制只能輸入數字“0123456789" 23 <LinearLayout 24 android:layout_width="match_parent" 25 android:layout_height="wrap_content" 26 android:orientation="horizontal"> 27 28 <Button 29 android:id="@+id/xieru" 30 android:layout_width="0dp" 31 android:layout_height="wrap_content" 32 android:layout_weight="1" 33 android:onClick="onClick" 34 android:text="@string/button1" 35 android:textSize="20sp" /> 36 37 <Button
38 android:id="@+id/duqu" 39 android:layout_width="0dp" 40 android:layout_height="wrap_content" 41 android:layout_weight="1" 42 android:onClick="onClick" 43 android:text="@string/button2" 44 android:textSize="20sp" /> 45 </LinearLayout> 46 </LinearLayout>

第二步:由java代碼來實現。其主要的步驟為“保存方法”,“讀取方法”,以及實現按鈕事件

  

1 private void save(String name, String age) {
2     SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();//獲取對象,並且命名文件的名稱
3     editor.putString("name", name);  //保存數據
4     editor.putString("age",age);
5     editor.commit();
6     editor.clear();
7     Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_LONG).show();
8 }//保存方法的實現代碼

private void readPrefs() {
    SharedPreferences prefs = getSharedPreferences("data", MODE_PRIVATE); //獲取對象,讀取data文件
    String username = prefs.getString("name", ""); //獲取文件中的數據
    String userage = prefs.getString("age", "");
    Toast.makeText(MainActivity.this, "姓名是:"+username+"年齡是:"+userage, Toast.LENGTH_LONG).show();
}      //讀取方法的實現代碼

public void onClick(View view) {          //按鈕的點擊事件
    switch (view.getId()) {
        case R.id.xieru:
            name = etname.getText().toString();
            age = etage.getText().toString();
            save(name,age);    //調用保存方法,將輸入的姓名和年齡保存
            break;
        case R.id.duqu:
            readPrefs();   //調用讀取方法,將保存的文件中的姓名和年齡顯示出來
            break;
    }
}

SharedPreferences 寫入讀取