編輯:Android 程式設計入門
這一課把 Android 最基礎的三種資料儲存方式一次做完:SharedPreferences 存鍵值對、內部儲存空間讀寫文字檔、以及把 Assets 中的圖片複製到 App 私有目錄後顯示。
畫面上有兩組「儲存/讀取」按鈕分別對應 SharedPreferences 與文字檔,一組「儲存檔案/讀取檔案」處理圖片,最後用 ImageView 呈現結果。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://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="com.hanqi.test5.DataActivity1"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/et_1"
android:hint="key"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/et_2"
android:hint="value"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="保存"
android:layout_weight="1"
android:onClick="bt1_OnClick"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="讀取"
android:layout_weight="1"
android:onClick="bt2_OnClick"/>
</LinearLayout>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/et_3"
android:hint="要存儲的內容"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/et_4"
android:hint="從文件中讀取的內容"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="保存"
android:layout_weight="1"
android:onClick="bt3_OnClick"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="讀取"
android:layout_weight="1"
android:onClick="bt4_OnClick"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="保存文件"
android:layout_weight="1"
android:onClick="bt5_OnClick"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="讀取文件"
android:layout_weight="1"
android:onClick="bt6_OnClick"/>
</LinearLayout>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/vipflower"
android:id="@+id/iv_4"/>
</LinearLayout>
適合存設定、標記、上一次的登入帳號這類小片段資料。取得實例時就指定檔名與存取模式:
sp = getSharedPreferences("mydata", MODE_PRIVATE);
寫入透過 Editor,最後一定要 commit() 才會落地:
public void bt1_OnClick(View v) {
String key = et_1.getText().toString();
String value = et_2.getText().toString();
if (key.length() == 0 || value.length() == 0) {
Toast.makeText(DataActivity1.this, "key 或 value 不能為空", Toast.LENGTH_SHORT).show();
} else {
SharedPreferences.Editor editor = sp.edit();
editor.putString(key, value);
boolean b = editor.commit();
Toast.makeText(DataActivity1.this, b ? "保存成功" : "保存失敗", Toast.LENGTH_SHORT).show();
}
}
讀取時帶入預設值,找不到 key 時就不會拿到 null:
public void bt2_OnClick(View v) {
String key = et_1.getText().toString();
et_2.setText(sp.getString(key, "沒有發現 key"));
}
openFileOutput() 與 openFileInput() 會自動把檔案放進 App 的私有目錄,其他應用程式無法存取。這裡用 MODE_APPEND 做到「追加」而非覆寫:
final String FILENAME = "test.txt";
public void bt3_OnClick(View v) {
String content = et_3.getText().toString();
try {
FileOutputStream fos_1 = openFileOutput(FILENAME, MODE_APPEND);
PrintStream pm = new PrintStream(fos_1);
pm.println(content);
pm.close();
fos_1.close();
Toast.makeText(DataActivity1.this, "保存成功", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(DataActivity1.this, "保存失敗", Toast.LENGTH_SHORT).show();
}
}
public void bt4_OnClick(View v) {
try {
FileInputStream fis = openFileInput(FILENAME);
byte[] b = new byte[1024];
int i = 0;
StringBuilder sb_1 = new StringBuilder();
while ((i = fis.read(b)) > 0) {
sb_1.append(new String(b, 0, i));
}
fis.close();
et_4.setText(sb_1);
Toast.makeText(DataActivity1.this, "讀取成功", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(DataActivity1.this, "讀取失敗", Toast.LENGTH_SHORT).show();
}
}
assets 目錄裡的檔案是唯讀的,若要讓 ImageView 直接指向它並不方便,常見做法是先用串流複製一份到 getFilesDir() 底下:
public void bt5_OnClick(View v) {
AssetManager am = getAssets();
try {
InputStream is = am.open("yuantu.png");
FileOutputStream fos = openFileOutput("yuantu.png", MODE_PRIVATE);
byte[] b = new byte[1024];
int i = 0;
while ((i = is.read(b)) > 0) {
fos.write(b, 0, i);
}
fos.close();
is.close();
Toast.makeText(DataActivity1.this, "保存成功", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(DataActivity1.this, "保存失敗", Toast.LENGTH_SHORT).show();
}
}
讀取時組出絕對路徑,用 BitmapFactory 解碼後塞給 ImageView:
public void bt6_OnClick(View v) {
String filepath = getFilesDir().getAbsolutePath();
filepath += "/yuantu.png";
Bitmap bm = BitmapFactory.decodeFile(filepath);
iv_4.setImageBitmap(bm);
}
SharedPreferences 體積最小、讀寫最快,適合少量結構化設定;內部檔案適合較長的文字或自訂格式資料;assets 則是打包在 APK 內的唯讀資源,需要修改就得先複製出來。資料量大、需要查詢條件時,才需要再往 SQLite 或 ORM 框架邁進。
資料儲存體系總覽:

Android 訊息推送的常見方案與實作思考
在行動應用中,推送通知是讓使用者即時掌握伺服器變更的重要機制。相較於由客戶端定時拉取資料,推送能降低流量與電力消耗,也能提升即時性。拉取與推送的差異拉取模式由客戶端固定時
Android 自訂 View 三步曲終章:從零打造全新控件
在 Android 裡打造自訂控件,實務上離不開三條路徑。 其一,繼承既有的控件,在原有能力上做功能擴展;其二,把現成的控件靈活組合,拼出功能更強的複合控件;其三,直接重
Mac 上下載並安裝 Android Studio 全流程實戰
今天把公司閒置的一台 Mac mini 重裝了系統,用起來速度出乎意料地順暢。平日辦公的那台機器 USB 有些毛病,我便打算改用這台 Mac。以往開發用 IntelliJ
Android 自動連線指定 Wi-Fi:免密碼與指定密碼都能搞定
接到一個需求:不掃描、不跳出系統選單,直接連上指定的 Wi-Fi(而且是這台裝置從沒連過的)。於是動手寫了個 Demo 驗證。 一、先看運行結果 畫面上兩個輸入框,上面