Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 數據存儲四大方式详解:文件、SD 卡、SharedPreferences 與 SQLite

編輯:關於 Android 程式設計

Android 為開發者提供了多種數據持久化的方式,以下將詳細說明其中最常見的四種,並附上實作範例。

第一種:文件存儲數據

核心原理:Context 提供了兩個方法來打開數據文件裡的文件 IO 流——FileInputStream openFileInput(String name) 與 FileOutputStream openFileOutput(String name, int mode)。這兩個方法的第一個參數用於指定文件名,第二個參數則指定打開文件的模式,可選值如下:

MODE_PRIVATE:預設操作模式,代表該文件為私有數據,只能被應用本身訪問。在此模式下,寫入的內容會覆蓋原文件;若想將新內容追加到原文件,可使用 Context.MODE_APPEND。

MODE_APPEND:該模式會檢查文件是否存在,存在就追加內容,否則建立新文件。

MODE_WORLD_READABLE:表示當前文件可被其他應用讀取。

MODE_WORLD_WRITEABLE:表示當前文件可被其他應用寫入。

此外,Context 還提供了幾個重要方法:

getDir(String name, int mode):在應用的數據文件夾下取得或建立 name 對應的子目錄。

File getFilesDir():取得該應用的數據文件夾的絕對路徑。

String[] fileList():返回該應用數據文件夾的全部文件。

實例:

核心程式碼:

版面配置:

 

 <LinearLayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools"> <EditText android:hint="請輸入用戶名" android:id="@+id/name" android:layout_height="wrap_content" android:layout_width="match_parent"> <EditText android:hint="請輸入密碼" android:id="@+id/pwd" android:layout_height="wrap_content" android:layout_width="match_parent"> <LinearLayout android:layout_height="wrap_content" android:layout_width="wrap_content" android:orientation="horizontal"> <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:onClick="mybtn1" android:text="保存"> </Button> <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:onClick="mybtn2" android:text="讀取"> <TextView android:id="@+id/tv" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/hello_world" android:textSize="35sp"> </TextView> </Button> </LinearLayout> </EditText> </EditText> </LinearLayout>

activity 中:

 

filename:

 

 private String filename = "info.txt";

 

保存:

 public void mybtn1(View view) { String Name = name.getText().toString(); String Pwd = pwd.getText().toString(); try { // 字節文件輸出流用於將數據寫入到 File FileOutputStream fos = openFileOutput(filename, MODE_APPEND); PrintWriter out = new PrintWriter(fos); out.println(Name); out.println(Pwd); out.flush(); fos.close(); out.close(); name.setText(""); pwd.setText(""); } catch (FileNotFoundException e) { e.printStackTrace(); } }

讀取:

 public void mybtn2(View view) { try { FileInputStream fis = openFileInput(filename); // 字節轉換成字符流,再轉換為緩沖字符流 BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String line = null; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line + "\n"); tv.setText(sb.toString()); } } catch (FileNotFoundException e) { e.printStackTrace(); } }

效果圖:

 

第二種:SD 卡存儲數據

讀寫步驟如下進行:

1、調用 Environment 的 getExternalStorageState() 方法判斷手機是否插了 SD 卡,且應用具有讀寫 SD 卡的權限,如下程式碼將返回 true:

Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)

2、調用 Environment.getExternalStorageDirectory() 方法取得外部存儲器(即 SD 卡)的目錄,或使用 "/mnt/sdcard/" 目錄。

3、使用 IO 流操作 SD 卡上的文件。

注意點:手機應該已插入 SD 卡,對於模擬器而言,可透過 mksdcard 命令來建立虛擬存儲卡;並且必須在 AndroidManifest.xml 上配置讀寫 SD 卡的權限:

<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission></uses-permission>

實例:

核心程式碼:

版面配置:用上面的版面配置

 

activity:

 

filename:

 private String filename = "my.txt";

保存:

 public void mybtn1(View view) { String Name = name.getText().toString(); String Pwd = pwd.getText().toString(); // 1. 判斷 SD 可用否 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // 2. 獲取路徑 String path = Environment.getExternalStorageDirectory().getAbsolutePath(); // 3. 獲取流對象進行讀寫操作 try { PrintWriter out = new PrintWriter(new FileOutputStream(path + "/" + filename)); out.println(Name); out.println(Pwd); out.flush(); name.setText(""); pwd.setText(""); } catch (FileNotFoundException e) { e.printStackTrace(); } } else { Toast.makeText(this, "SD 卡不可用", 0).show(); } }

讀取:

 public void mybtn2(View view) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { String path = Environment.getExternalStorageDirectory().getAbsolutePath(); try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path + "/" + filename))); String line = null; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line + "\n"); tv.setText(sb.toString()); } name.setText(""); pwd.setText(""); } catch (FileNotFoundException e) { e.printStackTrace(); } } else { Toast.makeText(this, "SD 卡不可用", 0).show(); } }

效果圖:

 

第三種:SharedPreferences 存儲數據

適用範圍:保存少量的數據,且這些數據的格式非常簡單——字串型、基本類型的值。例如應用的各種配置資訊(如是否打開音效、是否使用震動效果、小遊戲的玩家積分等)、解鎖口令密碼等。

核心原理:以 XML 文件形式存儲的 key-value 鍵值對數據,通常用來存儲一些簡單的配置資訊。透過 DDMS 的 File Explorer 面板展開文件浏覽樹,可以明顯看到 SharedPreferences 數據總是存儲在 /data/data/<package name>/shared_prefs 目錄下。SharedPreferences 物件本身只能獲取數據而不支持存儲和修改,存儲與修改是透過 SharedPreferences.edit() 獲得的內部介面 Editor 物件實現的。SharedPreferences 本身是一個介面,程式無法直接建立其例項,只能透過 Context 提供的 getSharedPreferences(String name, int mode) 方法來獲取,其中 name 表示要操作的 xml 文件名,第二個參數具體如下:

Context.MODE_PRIVATE:指定該 SharedPreferences 數據只能被本應用讀、寫。

Context.MODE_WORLD_READABLE:指定該數據能被其他應用讀,但不能寫。

Context.MODE_WORLD_WRITEABLE:指定該數據能被其他應用讀、寫。

Editor 有以下主要方法:

SharedPreferences.Editor clear():清空 SharedPreferences 裡所有數據。

SharedPreferences.Editor putXxx(String key, xxx value):向 SharedPreferences 存入指定 key 對應的數據,其中 xxx 可以是 boolean、float、int 等各種基本類型。

SharedPreferences.Editor remove():刪除 SharedPreferences 中指定 key 對應的數據項。

boolean commit():Editor 編輯完成後,使用該方法提交修改。

實例:

版面配置:用上面第一種的程式碼

activity 中:

保存:

 public void mybtn1(View view){ String Name = name.getText().toString(); String Pwd = pwd.getText().toString(); editor.putString("name", Name); editor.putString("pwd", Pwd); editor.putInt("count", 100); editor.putBoolean("sound", true); // 提供修改之後的數據 editor.commit(); name.setText(""); pwd.setText(""); }

讀取:

 public void mybtn2(View view){ String n = sp.getString("name", ""); String p = sp.getString("pwd", ""); int c = sp.getInt("count", 0); boolean b = sp.getBoolean("sound", false); tv.setText("姓名:" + n + "\n" + "密碼:" + p + "\n" + "次數:" + c + "\n" + "sound:" + b + "\n"); }

效果圖:

 

第四種:SQLite 存儲數據

 

SQLite 是輕量級嵌入式數據庫引擎,支援 SQL 語言,並且只利用很少的記憶體就有很好的性能。現在的主流移動設備如 Android、iPhone 等都使用 SQLite 作為複雜數據的存儲引擎。在我們為移動設備開發應用程式時,往往需要用到 SQLite 來存儲大量數據,因此必須掌握移動設備上的 SQLite 開發技巧。

SQLiteDatabase 類為我們提供了很多種方法,上面的程式碼基本上囊括了大部分的數據庫操作。這裡還寫了數據庫幫助類,實現了數據庫的建立和更新。

 

實例:

版面配置:

 

 <LinearLayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools"> <EditText android:hint="請輸入用戶名" android:id="@+id/name" android:layout_height="wrap_content" android:layout_width="match_parent"> <EditText android:hint="請輸入密碼" android:id="@+id/pwd" android:layout_height="wrap_content" android:layout_width="match_parent"> <LinearLayout android:layout_height="wrap_content" android:layout_width="wrap_content" android:orientation="horizontal"> <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:onClick="mybtn1" android:text="保存"> </Button> <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:onClick="mybtn2" android:text="讀取"> <ListView android:id="@+id/lv" android:layout_height="wrap_content" android:layout_width="match_parent"> </ListView> </Button> </LinearLayout> </EditText> </EditText> </LinearLayout>

 

activity:

 

 package com.example.fileapp; import android.os.Bundle; import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; public class FourActivity extends Activity { private EditText nameEt, pwdEt; private ListView lv; private MyOpenHelper helper; // 代表數據庫對象 private SQLiteDatabase db; public void mybtn1(View view){ String name = nameEt.getText().toString(); String pwd = pwdEt.getText().toString(); insert(db, name, pwd); } private void create(SQLiteDatabase db) { String sql = "create table s_user(_id integer primary key autoincrement,name text,pwd text)"; db.execSQL(sql); } public void insert(SQLiteDatabase db, String name, String pwd){ // 使用特定的方法:insert ContentValues values = new ContentValues(); // key 是字段名,value 是插入的名字 values.put("name", name); values.put("pwd", pwd); db.insert("s_user", null, values); nameEt.setText(""); pwdEt.setText(""); } public void mybtn2(View view){ Cursor cursor = db.query("s_user", null, null, null, null, null, null); refresh(cursor); } private void refresh(Cursor cursor){ SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.activity_item, cursor, new String[]{"_id", "name", "pwd"}, new int[]{R.id.id, R.id.name, R.id.pwd}, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); lv.setAdapter(adapter); } protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_four); nameEt = (EditText) findViewById(R.id.name); pwdEt = (EditText) findViewById(R.id.pwd); lv = (ListView) findViewById(R.id.lv); lv.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { TextView tv = (TextView) view.findViewById(R.id.id); String pid = tv.getText().toString(); // 使用特定方法 db.delete("s_user", "_id=?", new String[]{pid}); refresh(db.rawQuery("select * from s_user", null)); return true; } }); // 第二種方式:獲取數據庫對象(方式更好) helper = new MyOpenHelper(this, "user.db", null, 1); db = helper.getReadableDatabase(); } @Override protected void onDestroy() { super.onDestroy(); // 關閉數據庫 helper.close(); } }

 

幫助類 MyOpenHelper:

 

 package com.example.fileapp; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; // 數據庫的幫助類:創建數據庫表和數據庫的更新 public class MyOpenHelper extends SQLiteOpenHelper{ // 定義該程式中每張表的建表語句 private String sql1 = "create table s_user(_id integer primary key autoincrement,name,pwd)"; // 第二個參數是數據庫的名字,第三個是游標工廠對象,第四個參數當前數據庫使用版本號 public MyOpenHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } // 用於創建數據庫表,第一次創建數據庫文件時被回調 @Override public void onCreate(SQLiteDatabase db) { db.execSQL(sql1); } // 用於數據庫的更新,舊版本號和新版本號不一致會被回調 @Override public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { } }

 

效果圖:


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved