1. 程式人生 > >android學習筆記(一)資料儲存與訪問

android學習筆記(一)資料儲存與訪問

Android為資料儲存提供了以下幾種方式:

1.檔案儲存方式

2.SharedPreference儲存方式

3.Content Provider 內容提供者

4.網路儲存方式

(一).檔案操作方式(其本質即為輸入輸出流的操作)

實現登入介面賬號、密碼的儲存功能。



1.寫佈局檔案,分別新增:

a.圖片控制元件(ImageView)

b.兩個輸入框(EditText)

c. 單選框(CheckBox)

d. 登入按鈕(Button)

<span style="font-size:14px;"><LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.weimitechnology.QQLogin.MainActivity" 
    xmlns:android="http://schemas.android.com/apk/res/android">
    
	<LinearLayout 
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:orientation="horizontal"
	    android:padding="20dip">
	    
    	<ImageView
        android:layout_width="92dp"
        android:layout_height="match_parent"
        android:src="@drawable/f25" />
   
	    <LinearLayout 
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:orientation="vertical">
	
	    <EditText
	        android:id="@+id/QQ_number"
	        android:layout_width="fill_parent"
	        android:layout_height="wrap_content" 
	        android:hint="請輸入QQ號碼"/>
	    
	    <!-- 密碼不能以明文方式顯示 -->
	    <EditText
	        android:id="@+id/QQ_password"
	        android:layout_width="fill_parent"
	        android:layout_height="wrap_content"
	        android:inputType="textPassword"
	        android:hint="請輸入QQ密碼"/>
   		</LinearLayout>
    </LinearLayout>
    
    <CheckBox 
    	android:id="@+id/QQChecked"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:layout_gravity="center"
        android:text="記住密碼"/>
    
    <Button 
        android:id="@+id/QQLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       android:layout_gravity="center_horizontal"
        android:text="登入"/>
    
</LinearLayout></span>

2.構建一個工具類(其中兩個函式,分別實現登資訊的儲存、恢復)

a. 函式一: public static boolean saveUserInfo(String number, String password)

引數 number:傳入輸入框中的賬號資訊

引數 password: 傳入輸入框中的密碼資訊

備註;當用戶選擇儲存密碼,且登入成功後,儲存使用者登入資訊,下次開啟應用時自動返回登入賬號密碼。

b.函式二: public static Map<String, String> getUserInfor()

返回型別:Map返回使用者賬號密碼資訊

備註:OnCreate(Bundle savedInstanceState)中呼叫

package com.weimitechnology.QQLogin.utils;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import android.text.TextUtils;
import android.util.Log;

public class Utills {

	/* 函式一:儲存賬號 密碼 */
	public static boolean saveUserInfo(String number, String password){
		
		//  將資料寫入檔案的步驟:
		try { // 1.指定檔案路徑
			String path = "/data/data/com.weimitechnology.QQLogin/QQLogin.txt";
			FileOutputStream fosFileOutputStream = new FileOutputStream(path);
			
			// 2.給出所要寫入的內容 54321##123456
			String data = number + "##" + password;
			
			// 3.以位元組流的方式寫入檔案
			fosFileOutputStream.write(data.getBytes());
			
			// 4.重新整理資料
			fosFileOutputStream.flush();
			
			// 5.關閉資料流
			fosFileOutputStream.close();
			
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		return false;		
	}
	
	
	/*函式二:賬號密碼資訊的恢復*/
	public static Map<String, String> getUserInfor(){
		
		// 讀取資料的步驟:
		try {
			// 1.獲取檔案儲存路徑
			String path = "/data/data/com.weimitechnology.QQLogin/QQLogin.txt";
			FileInputStream fis = new FileInputStream(path);
			
			// 2.構建了一個字元流
			BufferedReader reader= new BufferedReader(new InputStreamReader(fis));
			
			// 3.獲取文字資訊
			String text = reader.readLine();
			
			// 4.對文字資訊進行分割解析
			if(!TextUtils.isEmpty(text))
			{
				String[] spit = text.split("##");
				Map<String, String> userInforMap = new HashMap<String, String>();
				Log.d("getUserInfor()",spit[0]+";"+spit[1]);
				userInforMap.put("number", spit[0]);
				userInforMap.put("password",spit[1]);
				fis.close();
				return userInforMap;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}


檔案操作歸納:

(1).寫入文字資訊

1.定義寫入路徑並獲得輸出流

String path = "/data/data/包名/檔名"

FileOutputStream fos = new FileOutputStream(path);

2.獲取所需寫入的資料

String data = number + "##" + password;

3.寫入資料

fos.write(data.getBytes());

4.重新整理資料,關閉輸入輸出流

fos.flush();

fos.close();

(2).讀取文字資訊

1.指定路徑並獲得輸入流

String path = "/data/data/包名/檔名"

FileInputStream fis = new FileItputStream(path);

2.獲取字元流物件

BufferedReader reader = new BufferedReader(new InputStreamReader(fis));

3.讀取文字資訊

String text = reader.readLine();

4.關閉輸入輸出流

fis.close();

(3).對讀取資料進行解析

從文字中所讀取的資料 text = "98765##43210",中間的 ## 為寫入文字資訊是新增的分隔符:

if(!TextUtils.isEmpty(text))// 如果所讀取道到得文字資訊不為空

{

String[] spit = text.split("##");// 對文字中 ## 資訊進行分割

Map<String, String> userInforMap = new HashMap<String, String>(); // 新建Map<String, String> 物件

Log.d("getUserInfor()",spit[0]+";"+spit[1]);  

userInforMap.put("number", spit[0]);// key-values對應,spit[0]中存放的是賬號資訊

userInforMap.put("password",spit[1]);// key-values對應,spit[1]中存放的是密碼資訊

fis.close();

return userInforMap;

}


3.Activity中實現登入及資訊儲存、回顯

package com.weimitechnology.QQLogin;

import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.weimitechnology.QQLogin.utils.Utills;


public class MainActivity extends Activity implements OnClickListener {

    private static final String TAG = "MainActivity";
	private EditText qNumber;
	private EditText qPassword;
	private CheckBox qCheck;
	private Button qLogin;

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
/*        // 去除標題欄,必須在setContentView之前呼叫
        requestWindowFeature(Window.FEATURE_NO_TITLE);*/
        
        setContentView(R.layout.activity_main);
        
        qNumber = (EditText) findViewById(R.id.QQ_number);
        qPassword = (EditText) findViewById(R.id.QQ_password);
        qCheck = (CheckBox) findViewById(R.id.QQChecked);
        qLogin = (Button) findViewById(R.id.QQLogin);
    
        qLogin.setOnClickListener(this);
        
        // 回顯資料
        Map<String, String> userInforMap = Utills.getUserInfor();
        if(userInforMap != null){
        	Log.d(TAG," 顯示賬號、密碼:" + userInforMap.get("number") +"," + userInforMap.get("password"));
        	qNumber.setText(userInforMap.get("number"));
        	qPassword.setText(userInforMap.get("password"));
        	}
    }

	@Override
	public void onClick(View v) {
		// 執行登入操作
		
		// 1.取出除賬號和密碼
		String QQnumber = qNumber.getText().toString();
		String QQpassword = qPassword.getText().toString();
		if(TextUtils.isEmpty(QQnumber) || TextUtils.isEmpty(QQpassword))
		{
			Toast.makeText(this, "賬號、密碼不能為空", Toast.LENGTH_SHORT).show();
			return;
		}
		
		// 2.判斷記住密碼是否被選中,如果被選中儲存起來
		if(qCheck.isChecked())
		{
			Log.d(TAG,"記住密碼:" + QQnumber +"," + QQpassword);
			boolean isSuccess = Utills.saveUserInfo(QQnumber, QQpassword);
			if(isSuccess){
				Toast.makeText(this, "儲存成功", Toast.LENGTH_SHORT);
			}else{
				Toast.makeText(this, "儲存失敗",Toast.LENGTH_SHORT);
			}
			
		}
		
		// 3.登入成功
		Toast.makeText(this, "登入成功", Toast.LENGTH_SHORT).show();
	}
}
備註(記得複習):按鈕點選功能一共有4種實現方式