Android中的存儲詳解
1、存儲在App內(nèi)部
最簡單的一種。在嘗試過程中發(fā)現(xiàn),手機(jī)中很多文件夾都沒有權(quán)限讀寫。我們可以將我們需要寫的文件存放到App中的files文件夾中,當(dāng)然我們有權(quán)限在整個App中讀寫文件

可以通過API獲取一個file對象,這里的this就是MainActivity類
// 獲取當(dāng)前包下的files路徑 /data/data/top.woodwhale.qqlogin/files File filesDir = this.getFilesDir();
之后就可以通過文件輸出流寫入文件:
File filesFile = new File(filesDir,"info.txt"); boolean flag = (filesFile.exists() || filesFile.createNewFile()); FileOutputStream fos = new FileOutputStream(file); fos.write((ac+"***"+pwd).getBytes(StandardCharsets.UTF_8)); fos.close();
寫入成功:

當(dāng)然,我們既然在這個App中都有權(quán)限,那么所有目錄都可以寫:
// 寫入到自己有權(quán)限寫的地方
File file = new File("/data/data/top.woodwhale.qqlogin/info.txt");
2、SD卡外部存儲
雖然現(xiàn)在很多的手機(jī)都不支持SD卡了,但是仍然有平板使用。
直接放出一個Activity類,其中調(diào)用了nvironment.getExternalStorageDirectory();方法類獲取一個sd卡file對象,使用Formatter.formatFileSize(this,externalStorageDirectory.getFreeSpace()));Formatter類中的轉(zhuǎn)化,將long類型轉(zhuǎn)化為大小類型,同時調(diào)用sd卡file對象的getFreeSpace()方法,獲取卡中剩余的空間,之后就是寫入externalStorageDirectory.getPath()卡中的路徑
public class SdcardActivity extends Activity {
private Button btn;
public static String TAG = "SdcardActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sc_card_rw);
btn = this.findViewById(R.id.bt_sdw);
btn.setOnClickListener(view -> {
File externalStorageDirectory = Environment.getExternalStorageDirectory();
Log.d(TAG, "sd卡路徑是:"+externalStorageDirectory.getPath());
Log.d(TAG,"sd卡剩余空間是"+ Formatter.formatFileSize(this,externalStorageDirectory.getFreeSpace()));
File file = new File(externalStorageDirectory,"love.txt");
try {
boolean flag = file.exists() || file.createNewFile();
if (flag) {
FileOutputStream fos = new FileOutputStream(file);
fos.write("woodwhale love sheepbotany".getBytes(StandardCharsets.UTF_8));
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
但是,在此之前,我們需要一個SD卡的讀寫權(quán)限,我們在AndrodiManifest.xml中配置下面的ses-permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
最終,在我們的sd卡中看到如下結(jié)果,證明寫入成功:

3、SharedPreferences存儲
SharedPreferences是android下的一個類,功能就是記錄偏好設(shè)置,形成一個xml文件
我們可以用SharedPreferences來存儲一些信息。
例如常見的這種:

我們勾選之后,再次打開app仍然處于勾選狀態(tài)。
那么這種情況如何實現(xiàn)呢?
通過xml生成上面的布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="80dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_centerVertical="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="未知來源"
android:textColor="@color/teal_200"
android:layout_marginLeft="10dp"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="運(yùn)行安裝未知來源的應(yīng)用"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:textSize="18sp"/>
</LinearLayout>
<Switch
android:id="@+id/sw_source"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginTop="30dp"
android:layout_marginRight="10dp" />
</RelativeLayout>
我們把Switch這個選擇框在activity類中賦予一個變量,給他加上一個OnCheckedChangeListener,再使用SharedPreferences來進(jìn)行設(shè)置偏好,整體代碼如下
package top.woodwhale.qqlogin;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.CompoundButton;
import android.widget.Switch;
import androidx.annotation.Nullable;
public class PreferenceDemoActivity extends Activity {
private Switch sw;
public static String TAG = "PreferenceDemoActivity";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pre_demo);
sw = (Switch) this.findViewById(R.id.sw_source);
SharedPreferences settingInfo = this.getSharedPreferences("settingInfo", MODE_PRIVATE);
SharedPreferences.Editor edit = settingInfo.edit();
sw.setOnCheckedChangeListener(new MyListener(edit));
boolean state = settingInfo.getBoolean("state", true);
Log.d(TAG,"STATE=="+ state);
sw.setChecked(state);
}
}
// 改變狀態(tài)的監(jiān)聽器
class MyListener implements CompoundButton.OnCheckedChangeListener {
SharedPreferences.Editor editor;
public MyListener(SharedPreferences.Editor editor) {
this.editor = editor;
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
Log.d(PreferenceDemoActivity.TAG,"current state : "+ b);
editor.putBoolean("state",b); // 要保存的數(shù)據(jù)類型
editor.commit(); // 保存數(shù)據(jù)
}
}
其中,editor的功能是保存數(shù)據(jù)

其次,為了每次打開App都可以看到我們的配置,通過讀取偏好配置文件,設(shè)置switch框的勾選

這樣就可以同步偏好設(shè)置的勾選啦!
最后我們可以在手機(jī)內(nèi)部看到我們寫入的偏好設(shè)置xml文件了,這樣也屬于存儲在App內(nèi)部


4、使用SQLite數(shù)據(jù)庫存儲
Android設(shè)備自帶SQLite數(shù)據(jù)庫,如果掌握過mysql,那么SQLite非常容易上手,且不說提供了非常簡便的API,就算是自己寫也比JDBC簡單!
首先我們不適用提供的API來實現(xiàn)一次增刪改查!
4.1 自己完成一個BaseDao類
BaseDao類本來是用來連接數(shù)據(jù)庫等基礎(chǔ)的,具體的增刪改查應(yīng)該在service層實現(xiàn),但為了這里測試,我們將crud的方法寫入到BaseDao類中封裝起來。具體架構(gòu)如下:

首先是Constants類,是常量類,其中有我們的數(shù)據(jù)庫名、版本號、表名
public class Constants {
public static final String DATABASE_NAME = "woodwhale.db";
public static final int VERSION_CODE = 1;
public static final String TABLE_NAME = "user";
}
其次是DatabaseHelper類,繼承SQLiteOpenHelper類,用來開啟數(shù)據(jù)庫,其中的onCreate方法是數(shù)據(jù)庫創(chuàng)建時的回調(diào),onUpgrade方法時升級數(shù)據(jù)時的回調(diào),我們在Constans類中寫了一個版本號,爸爸那邊每次升級可以加入新的功能,可以寫在onUpgrade方法中,通過switch實現(xiàn)。不過需要注意,升級只能讓版本號上升,不能降級,否則會報錯!
package top.woodwhale.qqlogin.SQLite.utils;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
public static String TAG = "DatabaseHelper";
/**
* @param context 上下文
*/
public DatabaseHelper( Context context) {
super(context, Constants.DATABASE_NAME, null, Constants.VERSION_CODE);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// 創(chuàng)建時的回調(diào)
Log.d(TAG, "創(chuàng)建數(shù)據(jù)庫");
String sql = "create table " + Constants.TABLE_NAME + " (id integer,name varchar,age integer)";
sqLiteDatabase.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
// 升級數(shù)據(jù)庫的回調(diào)
Log.d(TAG, "升級數(shù)據(jù)庫!");
String sql = null;
switch (i) {
case 1:
sql = "alter table "+ Constants.TABLE_NAME + " add phone integer";
sqLiteDatabase.execSQL(sql);
break;
case 2:
sql = "alter table "+ Constants.TABLE_NAME + " add address varchar";
sqLiteDatabase.execSQL(sql);
break;
}
}
}
最后就是我們封裝好的數(shù)據(jù)庫BaseDao類,通過語句實現(xiàn)了增刪改查
package top.woodwhale.qqlogin.SQLite.dao;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import top.woodwhale.qqlogin.SQLite.utils.Constants;
import top.woodwhale.qqlogin.SQLite.utils.DatabaseHelper;
// BaseDao類
public class BaseDao {
private final DatabaseHelper dbh;
private SQLiteDatabase db;
public static String TAG = "BaseDao";
public BaseDao(Context context) {
dbh = new DatabaseHelper(context);
}
// 增
public void add(int id, String name, int age) {
db = dbh.getWritableDatabase();
String sql = "insert into " + Constants.TABLE_NAME + "(id,name,age) values(?,?,?)";
Object[] params = new Object[]{id,name,age};
db.execSQL(sql,params);
db.close();
}
// 刪
public void free(int id) {
db = dbh.getWritableDatabase();
String sql = "delete from " + Constants.TABLE_NAME + " where id=?";
Object[] params = new Object[]{id};
db.execSQL(sql,params);
db.close();
}
// 改
public void edit(int id, int age) {
db = dbh.getWritableDatabase();
String sql = "update " + Constants.TABLE_NAME +" set age = ? where id = ?";
Object[] params = new Object[]{age,id};
db.execSQL(sql,params);
db.close();
}
// 查
@SuppressLint("Range")
public void show(int id) {
db = dbh.getReadableDatabase();
String sql = "select * from " + Constants.TABLE_NAME +" where id = ?";
String[] params = new String[]{String.valueOf(id)};
Cursor cursor = db.rawQuery(sql, params);
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex("name"));
Log.d(TAG,"name == "+name);
int age = cursor.getInt(cursor.getColumnIndex("age"));
Log.d(TAG,"age == "+age);
}
cursor.close();
db.close();
}
}
接著我們在AndroidTest包下進(jìn)行測試

package top.woodwhale.qqlogin;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
import top.woodwhale.qqlogin.SQLite.dao.BaseDao;
import top.woodwhale.qqlogin.SQLite.utils.DatabaseHelper;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a rel="external nofollow" >Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
public static final String TAG = "ExampleInstrumentedTest";
public static final Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();;
public static final BaseDao dao = new BaseDao(appContext);;
@Test
public void useAppContext() {
// Context of the app under test.
assertEquals("top.woodwhale.qqlogin", appContext.getPackageName());
}
@Test
public void testCreate() {
DatabaseHelper dbh = new DatabaseHelper(appContext);
SQLiteDatabase writableDatabase = dbh.getWritableDatabase();
Log.d(TAG, writableDatabase.getPath());
}
@Test
public void testAdd() {
dao.add(1,"woodwhale",19);
dao.add(2,"sheepbotany",21);
}
@Test
public void testFree() {
dao.free(1);
}
@Test
public void testEdit() {
dao.edit(1,3);
}
@Test
public void testShow() {
dao.show(1);
}
}
增刪改查都成功,成功就如圖所示:

由于只有查詢有l(wèi)og回顯,在logcat中之后show方法出現(xiàn)了log

4.2 使用Google寫的API處理
那么使用Google寫好的增刪改查api可以避免我們sql語句的格式問題和語法錯誤
經(jīng)過測試,如下代碼沒有問題(在BaseDao類中)
// 使用API的添加
public void addByAPI(int id, String name, int age) {
ContentValues contentValues = new ContentValues();
contentValues.put("id",id);
contentValues.put("name",name);
contentValues.put("age",age);
db = dbh.getWritableDatabase();
db.insert(Constants.TABLE_NAME,null,contentValues);
db.close();
}
// 刪除
public void freeByAPI(int id) {
db = dbh.getWritableDatabase();
db.delete(Constants.TABLE_NAME,"id = ?",new String[]{String.valueOf(id)});
db.close();
Log.d(TAG,"API刪除成功!");
}
// 修改
public void editByAPI(int id, String name, Integer age) {
ContentValues contentValues = new ContentValues();
if (name != null) {
contentValues.put("name",name);
}
if (age != null) {
contentValues.put("age",age);
}
db = dbh.getWritableDatabase();
db.update(Constants.TABLE_NAME,contentValues,"id = ?", new String[]{String.valueOf(id)});
db.close();
}
// 查詢
public void showByAPI(int id) {
db = dbh.getReadableDatabase();
Cursor cursor = db.query(false, Constants.TABLE_NAME, new String[]{"id", "name", "age"}, "id = ?", new String[]{String.valueOf(id)}, "id", null, null, null);
while (cursor.moveToNext()) {
int ID = cursor.getInt(0);
Log.d(TAG,"ID == "+ID);
String name = cursor.getString(1);
Log.d(TAG,"name == "+name);
int age = cursor.getInt(2);
Log.d(TAG,"age == "+age);
}
cursor.close();
db.close();
}
4.3 事務(wù)使用
使用db.beginTransaction(); db.setTransactionSuccessful(); db.endTransaction();三個方法來進(jìn)行事務(wù)的處理。
簡單的一個測試類
// 測試一個數(shù)據(jù)庫事物
@Test
public void testTransaction() {
DatabaseHelper dbh = new DatabaseHelper(appContext);
SQLiteDatabase db = dbh.getWritableDatabase();
db.beginTransaction();
Log.d(TAG,"事物開啟!");
try {
db.execSQL("update " + Constants.TABLE_NAME +" set age = 114 where id = 1");
int i = 10 / 0;
db.execSQL("update " + Constants.TABLE_NAME +" set age = 114 where id = 2");
db.setTransactionSuccessful();
Log.d(TAG,"事物成功!");
} catch (Exception e) {
e.printStackTrace();
} finally {
db.endTransaction();
db.close();
Log.d(TAG,"事物關(guān)閉!");
}
dao.showByAPI(1);
dao.showByAPI(2);
}
看看logcat,首先是進(jìn)入了 事物開啟,然后程序進(jìn)入了try中,因為除以了一個0所以報錯,捕獲異常了之后就是進(jìn)入到finally中關(guān)閉了事務(wù),可以發(fā)現(xiàn)我們sql中的信息都回滾了,沒有改變。

我們把int i = 10 / 0;刪了試一試,可以看到成功執(zhí)行事物。

值得注意的是,事物開啟之后,僅有當(dāng)前的db對象可以執(zhí)行sql語句,使用Dao類中的方法是無法進(jìn)行增刪改查的,因為對這些得到的db對象上了鎖!
總結(jié)
到此這篇關(guān)于Android中的存儲詳解的文章就介紹到這了,更多相關(guān)Android存儲內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深入理解Android熱修復(fù)技術(shù)原理之代碼熱修復(fù)技術(shù)
在各種 Android 熱修復(fù)方案中,Andfix的即時生效令人印象深刻,它稍顯另類, 并不需要重新啟動,而是在加載補(bǔ)丁后直接對方法進(jìn)行替換就可以完成修復(fù),然而它的使用限制也遭遇到更多的質(zhì)疑2021-06-06
Android學(xué)習(xí)教程之日歷控件使用(7)
這篇文章主要為大家詳細(xì)介紹了Android學(xué)習(xí)教程之日歷控件操作代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-11-11
Android Intent傳遞大量數(shù)據(jù)出現(xiàn)問題解決
這篇文章主要為大家介紹了Android Intent傳遞大量數(shù)據(jù)出現(xiàn)問題解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
Android中使用ViewStub實現(xiàn)布局優(yōu)化
ViewStub是Android布局優(yōu)化中一個很不錯的標(biāo)簽/控件,直接繼承自View。雖然Android開發(fā)人員基本上都聽說過,但是真正用的可能不多。今天我們就來詳細(xì)探討下ViewStub的使用2016-09-09
Android端實現(xiàn)單點(diǎn)登錄的方法詳解
所謂單點(diǎn)登錄就是指的同一個賬戶(id)不能在一個以上的設(shè)備上登錄對應(yīng)的用戶系統(tǒng)(排除web端和移動端可以同時登錄的情況),例如:用戶m在A設(shè)備登錄并保持登錄狀態(tài),然后又在B設(shè)備登錄,此時A應(yīng)該要強(qiáng)制下線,m無法在A設(shè)備上繼續(xù)執(zhí)行用戶相關(guān)的操作,下面來一起看看吧。2016-11-11

