使用Stetho觀察App裡的SharedPreferences與Sqlite資料

當我們想在手機裡暫存一些資料,方便紀錄使用者在App的設定紀錄時,Android官方提供SharedPreferces的方法(存成XML檔案),或是要以資料庫(可以新增/刪除/修改)的方式儲存更多的資料時,Android也提供了Sqlite的方法(存成db檔案)。

但是如果開發者在debug的過程想要查看所存放的資料內容,比較常見的方法是使用adb shell透過下指令的方式,但是這個方式不是很方便也比較不直覺,於是可以使用Facebook所提供第三方的Library讓我們更方便查看資料內容。

使用這個Library的方法非常的簡單,只要依照下列的幾個步驟即可達成:
1.在Gradle加入dependencies
dependencies {
   compile 'com.facebook.stetho:stetho:1.3.1'
}

2.建立Appliction class
public class MyApplication extends Application {
   @Override
   public void onCreate() {
       super.onCreate();
       Stetho.initializeWithDefaults(this);
   }
}

3.設定AndroidManifest.xml
<android:name=".MyApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
     </activity>
</application>

接著打開Chrome瀏覽器,在網址列輸入「chrome://inspect/」之後,會出現能夠透過Stetho Debug的app,按下「inspect」
可以直接看Sqilte裡的資料

可以直接看SharedPreferences裡的資料,而且修改欄位裡的資料就直接寫入手機了

程式碼請參考:
https://github.com/ukyo99999/StethoExample

Reference:
http://facebook.github.io/stetho/

留言

這個網誌中的熱門文章

ISO 27001 LA 主導稽核員 考照心得

Android如何實作強制App版本更新

如何實作從API抓取資料顯示在列表頁(ListView)上