編輯:關於 Android 程式設計
數據的持久化幾乎是每個應用都繞不開的話題。本文系統梳理 Android 中最常用的三類本地存儲方式:SharedPreferences、文件存儲與 SQLite 數據庫,並配以可運行的示例。
當應用只需要保存少量、結構簡單的數據(例如各種配置項、開關狀態等鍵值對)時,SharedPreferences 是最合適的選擇。
SharedPreferences 接口負責讀取數據,常用方法有:
它本身不具備寫入能力,寫入要通過 edit() 拿到的 SharedPreferences.Editor 完成:
SharedPreferences 是接口,需通過 Context 的 getSharedPreferences(String name, int mode) 獲取實例,mode 決定可見性:MODE_PRIVATE(僅本應用讀寫)、MODE_WORLD_READABLE(其他應用可讀)、MODE_WORLD_WRITEABLE(其他應用可讀寫)。
一個簡單的讀寫示例:
public class SharedPreferencesDemo extends Activity {
SharedPreferences preferences;
SharedPreferences.Editor editor;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
preferences = getSharedPreferences("hello", MODE_WORLD_READABLE);
editor = preferences.edit();
Button read = (Button) findViewById(R.id.read);
Button write = (Button) findViewById(R.id.write);
read.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
String time = preferences.getString("time", null);
int randNum = preferences.getInt("random", 0);
String result = time == null ? "您暫時還未寫入數據"
: "寫入時間為:" + time + "\n上次生成的隨機數為:" + randNum;
Toast.makeText(SharedPreferencesDemo.this, result, 5000).show();
}
});
write.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
editor.putString("time", sdf.format(new Date()));
editor.putInt("random", (int) (Math.random() * 100));
editor.commit();
}
});
}
}
寫入完成後,可通過 DDMS 的 File Explorer 找到 /data/data/包名/shared_prefs 目錄,SharedPreferences 數據以 XML 格式保存。
若要讀寫其他應用的 SharedPreferences,前提是對方在創建時授予了相應權限。做法是先用 createPackageContext 拿到對方的 Context,再通過該 Context 的 getSharedPreferences 獲取數據。例如讀取另一個應用記錄的「使用次數」:
public class ReadOtherPreferences extends Activity {
Context useCount;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
useCount = createPackageContext("com.Xxx", Context.CONTEXT_IGNORE_SECURITY);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
SharedPreferences prefs = useCount.getSharedPreferences("count", Context.MODE_WORLD_READABLE);
int count = prefs.getInt("count", 0);
TextView show = (TextView) findViewById(R.id.show);
show.setText("UseCount 應用程序以前被使用了" + count + "次。");
}
}
Context 提供了 openFileInput(String name) 與 openFileOutput(String name, int mode) 來操作應用數據文件夾下的文件。openFileOutput 的 mode 支持 MODE_PRIVATE(僅本程序讀寫)、MODE_APPEND(追加寫入)、MODE_WORLD_READABLE、MODE_WORLD_WRITEABLE 幾種取值。
此外,Context 還提供 getDir()、getFilesDir()、fileList()、deleteFile() 等方法訪問數據文件夾。
下面是一個讀寫私有文件的完整示例:
public class FileTest extends Activity {
final String FILE_NAME = "test.txt";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button read = (Button) findViewById(R.id.read);
Button write = (Button) findViewById(R.id.write);
final EditText edit1 = (EditText) findViewById(R.id.edit1);
final EditText edit2 = (EditText) findViewById(R.id.edit2);
write.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View source) {
write(edit1.getText().toString());
edit1.setText("");
}
});
read.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
edit2.setText(read());
}
});
}
private String read() {
try {
FileInputStream fis = openFileInput(FILE_NAME);
byte[] buff = new byte[1024];
int hasRead = 0;
StringBuilder sb = new StringBuilder("");
while ((hasRead = fis.read(buff)) > 0) {
sb.append(new String(buff, 0, hasRead));
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private void write(String content) {
try {
FileOutputStream fos = openFileOutput(FILE_NAME, MODE_APPEND);
PrintStream ps = new PrintStream(fos);
ps.println(content);
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
該文件會存放在 data/data/包名/files/test.txt。
當數據量較大(如圖片、音頻)時,應用私有空間往往不夠用,這就需要讀寫 SD 卡。步驟是:先用 Environment.getExternalStorageState() 判斷 SD 卡是否已掛載且可讀寫,再用 Environment.getExternalStorageDirectory() 拿到卡目錄,最後通過 FileInputStream/FileOutputStream 等常規 IO 類讀寫。
private String read() {
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File sdCardDir = Environment.getExternalStorageDirectory();
FileInputStream fis = new FileInputStream(sdCardDir.getCanonicalPath() + "/test.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
StringBuilder sb = new StringBuilder("");
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private void write(String content) {
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File sdCardDir = Environment.getExternalStorageDirectory();
File targetFile = new File(sdCardDir.getCanonicalPath() + "/test.txt");
RandomAccessFile raf = new RandomAccessFile(targetFile, "rw");
raf.seek(targetFile.length()); // 指針移到末尾
raf.write(content.getBytes());
raf.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
切記:訪問 SD 卡必須在 AndroidManifest.xml 中申請 MOUNT_UNMOUNT_FILESYSTEMS 與 WRITE_EXTERNAL_STORAGE 權限。
Android 內建了一個輕量的嵌入式數據庫 SQLite,專為資源有限的設備設計,無需安裝或啟動服務進程,整個數據庫就是一個文件。
Android 用 SQLiteDatabase 類代表一個數據庫,可通過 openDatabase() 或 openOrCreateDatabase() 打開或創建。拿到實例後,就能調用 execSQL()、insert()、update()、delete()、query()、rawQuery() 等方法進行增刪改查,並用 beginTransaction()/endTransaction() 管理事務。查詢結果返回一個 Cursor,其移動指針的方法(moveToFirst、moveToNext、moveToPosition 等)與 JDBC 的 ResultSet 頗為相似。
通過 execSQL 執行任意 SQL,即可建表:
db.execSQL("create table user_inf(user_id integer primary key, "
+ "user_name varchar(255), user_pass varchar(255))");
下面是一個結合 ListView 展示新聞列表的示例:
public class DBTest extends Activity {
SQLiteDatabase db;
Button bn;
ListView listView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
db = SQLiteDatabase.openOrCreateDatabase(
this.getFilesDir().toString() + "/test.db3", null);
listView = (ListView) findViewById(R.id.show);
bn = (Button) findViewById(R.id.ok);
bn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View source) {
String title = ((EditText) findViewById(R.id.title)).getText().toString();
String content = ((EditText) findViewById(R.id.content)).getText().toString();
try {
insertData(db, title, content);
Cursor cursor = db.rawQuery("select * from news_inf", null);
inflateList(cursor);
} catch (SQLiteException se) {
db.execSQL("create table news_inf(_id integer primary key autoincrement, "
+ "news_title varchar(50), news_content varchar(255))");
insertData(db, title, content);
Cursor cursor = db.rawQuery("select * from news_inf", null);
inflateList(cursor);
}
}
});
}
private void insertData(SQLiteDatabase db, String title, String content) {
db.execSQL("insert into news_inf values(null, ?, ?)", new String[]{title, content});
}
private void inflateList(Cursor cursor) {
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
DBTest.this, R.layout.line, cursor,
new String[]{"news_title", "news_content"},
new int[]{R.id.my_title, R.id.my_content});
listView.setAdapter(adapter);
}
@Override
public void onDestroy() {
super.onDestroy();
if (db != null && db.isOpen()) {
db.close();
}
}
}
除了直接寫 SQL,SQLiteDatabase 還提供了更安全的包裝方法:
實際開發中更推薦繼承 SQLiteOpenHelper,把建表與版本升級邏輯封裝起來。子類通常重寫 onCreate()(首次建庫時回調)與 onUpgrade()(版本更新時回調),並通過 getReadableDatabase() 或 getWritableDatabase() 獲取數據庫實例。下面是一個經典的「生詞本」例子:
public class MyDatabaseHelper extends SQLiteOpenHelper {
final String CREATE_TABLE_SQL =
"create table dict(_id integer primary key autoincrement, word, detail)";
public MyDatabaseHelper(Context context, String name, int version) {
super(context, name, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_SQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 處理版本升級
}
}
public class Dict extends Activity {
MyDatabaseHelper dbHelper;
Button insert, search;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dbHelper = new MyDatabaseHelper(this, "myDict.db3", 1);
insert = (Button) findViewById(R.id.insert);
search = (Button) findViewById(R.id.search);
insert.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View source) {
String word = ((EditText) findViewById(R.id.word)).getText().toString();
String detail = ((EditText) findViewById(R.id.detail)).getText().toString();
insertData(dbHelper.getReadableDatabase(), word, detail);
Toast.makeText(Dict.this, "添加生詞成功!", 8000).show();
}
});
search.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View source) {
String key = ((EditText) findViewById(R.id.key)).getText().toString();
Cursor cursor = dbHelper.getReadableDatabase().rawQuery(
"select * from dict where word like ? or detail like ?",
new String[]{"%" + key + "%", "%" + key + "%"});
Bundle data = new Bundle();
data.putSerializable("data", converCursorToList(cursor));
Intent intent = new Intent(Dict.this, ResultActivity.class);
intent.putExtras(data);
startActivity(intent);
}
});
}
protected ArrayList<Map<String, String>> converCursorToList(Cursor cursor) {
ArrayList<Map<String, String>> result = new ArrayList<Map<String, String>>();
while (cursor.moveToNext()) {
Map<String, String> map = new HashMap<String, String>();
map.put("word", cursor.getString(1));
map.put("detail", cursor.getString(2));
result.add(map);
}
return result;
}
private void insertData(SQLiteDatabase db, String word, String detail) {
db.execSQL("insert into dict values(null, ?, ?)", new String[]{word, detail});
}
@Override
public void onDestroy() {
super.onDestroy();
if (dbHelper != null) {
dbHelper.close();
}
}
}
借助 SQLiteOpenHelper,數據庫文件會自動保存在應用的 databases 目錄下,版本管理也變得清晰可控。綜合來看,SharedPreferences 適合輕量配置,文件存儲適合較大或靈活的數據,而 SQLite 則勝任結構化、需要條件查詢的複雜場景,三者相輔相成。
Android traces.txt 檔案解析:ANR 與 WatchDog 追蹤
Android 的 traces.txt 檔案記錄了進程的堆棧情況,對於分析應用響應慢以及 ANR 的原因很有幫助。這個檔案通常位於 /data/anr/ 目錄下。 tr
Android 逆向分析案例:地圖定位請求資料加解密
案例背景 許多應用會透過地圖 SDK 取得裝置定位,並將定位相關資料送到伺服器。本文以一個地圖定位請求為例,說明逆向分析的基本思路,涵蓋抓包、靜態分析、動態驗證,以及壓縮
Android 開發實戰:OkHttp 框架詳解與範例
本篇記錄在 Android 開發中如何使用 OkHttp 這個網路框架。文章會從依賴導入講起,並透過一個完整的範例,示範 GET 請求、POST 請求、檔案上傳與下載等常
Android 記事本專案:圖片等比例縮放與為圖片加上邊框
在 Android 的 UI 開發中,圖片縮放是很常見的需求。以記事本為例,現在的圖片普遍尺寸較大,若將原圖未經縮放直接放進畫面,不僅會佔滿整個螢幕,甚至可能比螢幕還大,