天天看點

從零開始學android<資料存儲(1)SharedPreferences屬性檔案.三十五.>

在android中有五種儲存資料的方法,分别是:

Shared Preferences

Store private primitive data in key-value pairs.
對應屬性的鍵值對屬性檔案存儲

Internal Storage

Store private data on the device memory.
裝置記憶體存儲

External Storage

Store public data on the shared external storage.
外部存儲器存儲,如記憶體卡

SQLite Databases

Store structured data in a private database.
sqlite資料庫存儲

Network Connection

Store data on the web with your own network server.網絡存儲

今天這一節我們一起來學習Shared Preferences 屬性檔案存儲的方式來存儲簡單的資料

我們可以使用Shared Preferences 來存儲 booleans, floats, ints, longs, and strings型的簡單資料并以鍵值對的形式儲存為xml檔案。

為了執行個體化Shared Preferences 我們可以使用

getSharedPreferences()和

getPreferences()

 這兩個方法

第一個方法需要傳入一個檔案名和存儲的模式

第二種方法預設為隻有一個屬性檔案,隻需要傳入一個存儲模式就行了

存儲模式 :

MODE_PRIVATE僅本應用可用

MODE_APPEND可追加

MODE_WORLD_READABLE

,可被其他應用讀

MODE_WORLD_WRITEABLE

.可被其他應用寫

具體操作見代碼注釋

xml檔案

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="89dp"
        android:text="存儲資訊" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="36dp"
        android:text="讀取資訊" />

</RelativeLayout>
           
JAVA檔案
package com.example.sharedpreferences;

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

public class MainActivity extends Activity {
	private SharedPreferences sharedPreferences;
	private Button saveData, getDate;
	public static final String FILENAME = "flyou";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		sharedPreferences = getSharedPreferences(FILENAME, MODE_PRIVATE);
		saveData = (Button) this.findViewById(R.id.button1);
		getDate = (Button) this.findViewById(R.id.button2);
		saveData.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				SharedPreferences.Editor editor = sharedPreferences.edit();
				editor.putString("username", "jay");
				editor.putString("password", "553274238");
				Boolean flag = editor.commit();
				Toast.makeText(MainActivity.this, "執行完成,執行結果:-->" + flag, 2)
						.show();
			}
		});
		getDate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String username = sharedPreferences.getString("username",
						"未找到比對資訊");
				String password = sharedPreferences.getString("password",
						"未找到使用者密碼");
				Toast.makeText(MainActivity.this,
						"使用者名:——>" + username + ",密碼:——>" + password, 2).show();
			}
		});
	}
}
           
從零開始學android&lt;資料存儲(1)SharedPreferences屬性檔案.三十五.&gt;
從零開始學android&lt;資料存儲(1)SharedPreferences屬性檔案.三十五.&gt;

接下來使用改方法來實作本地記住賬号和密碼的功能

裡面可能會涉及到一些沒有講到的知識,大家可以先了解下,也對前面學過的其他元件進行一下回顧

xml檔案

主界面

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="19dp"
        android:layout_marginTop="42dp"
        android:text="使用者名" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="58dp"
        android:text="密    碼" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView1"
        android:layout_alignBottom="@+id/textView1"
        android:layout_marginLeft="40dp"
        android:layout_toRightOf="@+id/textView1"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView2"
        android:layout_alignBottom="@+id/textView2"
        android:layout_alignLeft="@+id/editText1"
        android:ems="10"
        android:inputType="textPassword" />

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button1"
        android:layout_alignRight="@+id/editText2"
        android:text="記住密碼" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button1"
        android:layout_alignBottom="@+id/button1"
        android:layout_alignParentLeft="true"
        android:text="新增賬號" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toLeftOf="@+id/checkBox1"
        android:text="登入" />

</RelativeLayout>
           
登入後界面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>
           
JAVA檔案
package com.example.sharepreferencesdemo;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class MainActivity extends Activity {
	private SharedPreferences sharedPreferences;
	private Button login;
	private CheckBox checkBox;
	private EditText username, password;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		login = (Button) this.findViewById(R.id.button1);
		checkBox = (CheckBox) this.findViewById(R.id.checkBox1);
		username = (EditText) this.findViewById(R.id.editText1);
		password = (EditText) this.findViewById(R.id.editText2);
		sharedPreferences = getPreferences(MODE_PRIVATE);// 通過getPreferences執行個體化sharedPreferences對象

		String usernameString = sharedPreferences.getString("username", "");// 讀取使用者名
		username.setText(usernameString);// 為編輯框設定内容

		// 擷取複選框的選中狀态,如果選中的話就 進行記住密碼的操作
		if (sharedPreferences.getBoolean("checked", false)) {
			// 擷取密碼
			String passwordString = sharedPreferences.getString("password", "");
			// 設定編輯框資訊
			password.setText(passwordString);
		}

		login.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// 通過edit 方法執行個體化Editor對象,儲存資訊
				SharedPreferences.Editor editor = sharedPreferences.edit();
				// 以鍵值對的形式儲存資訊
				editor.putString("username", username.getText().toString());
				editor.putString("password", password.getText().toString());
				// 判斷複選框的選中狀态并進行存儲
				if (checkBox.isChecked()) {
					editor.putBoolean("checked", true);
				} else {
					editor.putBoolean("checked", false);
				}
				// 執行儲存操作
				editor.commit();

				// 設定進度對話框
				final ProgressDialog dialog = new ProgressDialog(
						MainActivity.this);
				// 設定标題
				dialog.setTitle("使用者登入");
				// 設定提示資訊
				dialog.setMessage("正在登入,請稍後……");
				// 開始進度對話框
				dialog.onStart();
				// 延時線程操作
				new Thread() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						try {
							// 休眠3秒
							Thread.sleep(3 * 1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} finally {
							// 對話框消失
							dialog.dismiss();
							// 設定意圖轉跳
							Intent intent = new Intent(MainActivity.this,
									main.class);

							// 傳遞意圖資訊
							intent.putExtra("username", username.getText()
									.toString());
							// 開始activity轉跳
							startActivity(intent);
							MainActivity.this.finish();
						}
					}
				}.start();// 開始線程操作
				// 顯示對話框
				dialog.show();

			}
		});

	}
}
           
登陸後的界面
package com.example.sharepreferencesdemo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.TextView;

public class main extends Activity {
	private TextView text;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.linearlayout);
		text=(TextView)this.findViewById(R.id.textView3);
		Intent intent=getIntent();
		text.setTextSize(15);
		text.setGravity(Gravity.CENTER_HORIZONTAL);
		text.setTextColor(Color.CYAN);
		text.setText("歡迎: "+intent.getStringExtra("username"));
	}
}
           
從零開始學android&lt;資料存儲(1)SharedPreferences屬性檔案.三十五.&gt;
從零開始學android&lt;資料存儲(1)SharedPreferences屬性檔案.三十五.&gt;
未點選記住密碼,第二次登入。
從零開始學android&lt;資料存儲(1)SharedPreferences屬性檔案.三十五.&gt;
點選記住密碼登入
從零開始學android&lt;資料存儲(1)SharedPreferences屬性檔案.三十五.&gt;
點選記住密碼後,第三次登入
從零開始學android&lt;資料存儲(1)SharedPreferences屬性檔案.三十五.&gt;

介紹了SharedPreferences屬性檔案的存儲,我們可以進行較小資料的快速存儲與便捷讀取

下節預報:Internal Storage内部存儲器

繼續閱讀