Android資料存放區三劍客——SharedPreferences、File、SQLite,androidsqlite
Android中常用的資料存放區一般有三種方式:SharedPreferences、檔案和SQLite資料庫,用來儲存需要長時間儲存的資料。本文將通過幾個具體的小執行個體來講解這三種方式的具體實現。
資料存放區之SharedPreferences:
SharedPreferences位於android.content包中,用於儲存少量簡單資料。其特點有:
1. 輕型的資料存放區方式
2. 基於xml檔案的儲存方式,以 鍵/值 對的形式儲存資料
3. 儲存簡單的配置資訊,支援的儲存類型有:Boolean、Float、Integer、Long、String等。
SharedPreferences儲存資料流程:
1. 擷取SharedPreferences對象:
private SharedPreferences prefs;
① //不指定隱藏檔名,使用預設的名稱,即活動的類名稱
prefs = getPreferences(MODE_PRIVATE);
② /*
*如果檔案中的資料是Android應用程式中各個活動之間的共用資料,
*每個活動都能訪問,需要使用如下方式,擷取SharedPreferences:
* prefs = getSharedPreferences(“myPrefs”,MODE_PRIVATE);
*/
③ //也可以使用PreferenceManager
//PreferenceManager.setDefaultValues(this,R.xml.preferences,false);
//prefs = PreferenceManager.getDefaultPreferenceManagers(this);
2. 儲存資料(使用Editor對象,儲存key-value值),讀取資料:
Editor editor = prefs.edit();
//儲存各種類型的資料
editor.putString(“name”,”Zhangsan”);
editor.putInt(“age”,18);
editor.putLong(“time”,System.currentTimeMillis);
//讀取資料
String name = prefs.getString(“name”);
int age = prefs.getInt(“age“);
3. 提交設定的資料,使資料儲存到檔案中:
在第2步中使用editor對象設定好key-value值後,資料並未儲存到檔案中,要儲存還需提交
editor.commit();
4. 刪除儲存的資料:
SharedPreferences.Clear();
說了這麼多,可能還是有些朋友說SharedPreferences到底是個什麼東東,下面個大家看看就明白了:
圖1. SharedPreferences隱藏檔的內容
這下知道了吧,<string name=”user”>Zhangsan</string>就是用editor.putString(“user”,”Zhangsan”)設定的內容。使用DDMS可查看該檔案位置,該檔案存放在:
圖2. SharedPreferences檔案位置
資料存放區之檔案(File)儲存
使用SharedPreferences隱藏檔比較方便簡單,但不能指定隱藏檔的位置,儲存的內容也很少,使用檔案儲存體既可儲存到應用程式預設的放置檔案的位置,也可儲存到外部存放裝置中,如外置SD卡中,可以減少佔用手機記憶體,可以儲存比較大的檔案。
檔案的操作模式:
表1. 檔案操作模式及說明
|
常量值 |
說明 |
|
MODE_PRIVATE |
檔案只能讓建立的應用程式訪問 |
|
MODE_WORLD_WRITEABLE |
檔案可讓其他應用程式寫入 |
|
MOED_WORLD_READABLE |
檔案可讓其他應用程式讀取 |
|
MODE_APPEND |
檔案若已存在,則在檔案末尾寫入資料,不覆蓋原來檔案內容 |
使用檔案儲存體的步驟:
1. 寫入檔案
//以字元流的形式寫資料到檔案
FileOutputStream out = openFileOutput(“out.txt”,MODE_PRIVATE);
String data = “123456abcdef”;
out.write(data); //寫資料到檔案
out.close(); //關閉檔案輸出資料流
/*
* 也可使用OutputStreamWriter以位元組流的形式寫入檔案
* OutputStreamWriter writer = new OutputStreamWriter(out);
* writer.write(data);
* writer.flush(); //輸出資料流資料
* writer.close(); //關閉流
*/
2. 讀取檔案
FileInputStream fis = openFileInput("input.txt");
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len=fis.read(buffer))!=-1) {
out.write(buffer,o,len);
}
資料存放區之SQLite
Android使用SQLite資料庫引擎,它是包含的、事務型的資料庫引擎,無需單獨的服務線程。SQLite資料庫資源佔用少、開源、功能強大,有以下特點:
1. 輕量級,使用一個動態庫,單個檔案
2. 獨立性,沒有依賴,無需安裝
3. 隔離性,資料全在一個檔案夾中
4. 跨平台,支援多種作業系統
5. 多語言介面,支援眾多程式設計語言
6. 安全性,支援交易處理。
7. 獨佔性,使用共用鎖定實現獨立交易處理,多個進程可同一時間從同意資料庫讀資料,但只有一個進程可寫資料。
SQLite支援的資料類型有:NULL、INTEGER、REAL、TEXT、BLOB類型。
SQLite儲存資料流程:
1. 擷取SQLiteDatabase資料庫物件
SQLiteDatabase db = openOrCreateDatabase(“user.db”,MODE_PRIVATE,null);
2. 執行增刪查改的資料動作陳述式
//建立一張表
db.execSQL(“create table if not exists contacts_tb(_id integer primary key autoincrement,name text not null,age integer not null)”);
//往資料庫裡插入一條資料
db.execSQL(“insert into contacts_tb(name,age)values(‘abc’,20)”);
db.execSQL(“insert into contacts_tb(name,age)values(‘cde’,18)”);
//查詢所有的資料,返回一個遊標對象
Cursor cursor = db.raw(“select * from contacts_tb”,null);
/*
* 也可使用ContentValues執行SQL操作
* ContentValues values = new ContentValues();
* values.put(“name”,”aaa”);
* values.put(“age”,20);
* db.insert(“contacts_tb”,null,values); //插入資料
* values.clear();
* values.put(“age”,18);
* //更新_id>2的資料項目的屬性值
* db.update(“contactes_tb”,values,”_id>?”,new String[]{“2”});
* //刪除名字中含有’a’的項
* db.delete(“contacts_tb”,”name like ?”,new String[]{“%a%”});
* //查詢_id>0的項,按名字排序
* Cursor cursor = db.query(“contacts_tb”,null,”_id>?”,new String[]{“0”},null,null,name);
*/
/*
* 使用SQLiteOpenHelper對象建立和管理資料庫
* 建立一個類DBOHelper extends SQLiteOpenHelper
* @override onCreate,onUpdate方法
* 使用DBOHelper對象
* DBOHelper helper = new DBOHelper(this,”user.db”);
* //建立或開啟唯讀資料庫
* SQLiteDatabase db = helper.getWriteableDatabase();
* //SQLiteDatabase db = helper.getReadableDatabase();
* 資料的操作和上邊都一樣
*/
3.處理擷取的結果
String name[10] ;
int age[10];
int i=0;
while(cursor.moveToNext()){
name[i] = cursor.getString(cursor.getColumnIndex(“name”));
age[i] = cursor.getInt(cursor.getColumnIndex(“age”));
i++;
}
cursor.close(); //需手動關閉,否則會出現未知的異常
db.close(); //資料庫物件也要手動關閉
下面來個具體的執行個體,簡單實現下SQLite的資料存放區,用到了ListView資料繫結:
DBHelper.java檔案public class DBHelper extends SQLiteOpenHelper{public DBHelper(Context context, String name) {super(context, name, null, 1);}@Overridepublic void onCreate(SQLiteDatabase db) {}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}}Contact.java檔案public class Contact extends Activity{private ListView lists;SimpleAdapter adapter;List<Map<String, Object>> dataList;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.layout_contacts);lists = (ListView) findViewById(R.id.contacts_list);All_Contacts();}public void All_Contacts(){dataList = new ArrayList<Map<String,Object>>();adapter = new SimpleAdapter(Contact.this, dataList, R.layout.layout_contacts, new String[]{"_id","name","sex","phone" }, new int[]{R.id._id,R.id._name,R.id._sex,R.id._phone});DBHelper dbHelper = new DBHelper(Contact.this, "Contacts.db");SQLiteDatabase db = dbHelper.getReadableDatabase();Cursor cursor = db.rawQuery("select * from tb_persons", null);cursor.moveToFirst();do {Map<String, Object> map = new HashMap<String, Object>();map.put("_id", cursor.getInt(cursor.getColumnIndex("_id")));map.put("name", cursor.getString(cursor.getColumnIndex("name")));map.put("sex", cursor.getString(cursor.getColumnIndex("sex")));map.put("phone", cursor.getString(cursor.getColumnIndex("phone")));dataList.add(map);}while(cursor.moveToNext());cursor.close();db.close();lists.setAdapter(adapter);}}MainActivity.java檔案public class MainActivity extends Activity {private Button btn_Add;private Button btn_OK;private Button btn_Cancel;private EditText nameText;private EditText sexText;private EditText phoneText;private LinearLayout info_Layout;private SQLiteDatabase db;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btn_Add = (Button) findViewById(R.id.btn_add);btn_OK = (Button) findViewById(R.id.btn_OK);btn_Cancel = (Button) findViewById(R.id.btn_Cancel);nameText = (EditText) findViewById(R.id.name);sexText = (EditText) findViewById(R.id.sex);phoneText = (EditText) findViewById(R.id.phone);info_Layout = (LinearLayout) findViewById(R.id.info_form);DBHandler();}//輔助方法,開啟新增連絡人...資訊地區public void add_Contact(View v){info_Layout.setVisibility(View.VISIBLE);btn_Add.setEnabled(false);}//跳轉到查詢所有連絡人頁面public void search_All(View v){Intent intent = new Intent(MainActivity.this, Contact.class);startActivity(intent);}//新增連絡人...資訊地區public void insert_Info(View v){long id =0 ;String name = nameText.getText().toString().trim();String sex = sexText.getText().toString().trim();String phone = phoneText.getText().toString().trim();ContentValues values = new ContentValues();values.put("name", name);values.put("sex", sex);values.put("phone", phone);db = openOrCreateDatabase("Contacts.db", MODE_PRIVATE, null);id = db.insert("tb_persons", null, values);values.clear();db.close();nameText.setText("");sexText.setText("");phoneText.setText("");info_Layout.setVisibility(View.INVISIBLE);btn_Add.setEnabled(true);if (id==-1) {Toast.makeText(this, "連絡人添加失敗!", Toast.LENGTH_SHORT).show();return ;}Toast.makeText(this, "連絡人添加成功!", Toast.LENGTH_SHORT).show();}//清空添加資訊框public void cancel_Info(View v){nameText.setText("");sexText.setText("");phoneText.setText("");info_Layout.setVisibility(View.INVISIBLE);btn_Add.setEnabled(true);Toast.makeText(this, "已取消添加!", Toast.LENGTH_SHORT).show();}//建立連絡人資料庫private void DBHandler(){//建立應用程式的資料庫db = openOrCreateDatabase("Contacts.db", MODE_PRIVATE, null);db.execSQL("create table if not exists tb_persons(_id integer primary key autoincrement,name text not null,sex text not null,phone text not null)");}}
應用程式結構圖以及程式的運行效果:
以上就是三種方式的原理,代碼比較淩亂,有空再好好梳理下!相信分享的力量,堅持就是勝利!