Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

解決 Android 錯誤:database disk image is malformed (code 11)

編輯:關於 Android 程式設計

在實作來電顯示歸屬地與歸屬地查詢功能時,需要從伺服器下載一筆資料庫檔案。然而下載完成後,查詢時卻總是抛出 database disk image is malformed (code 11) 的錯誤。

一開始我以為是查詢語句寫錯,後來才意識到,這其實與先前解析檔案時遇到的問題同源——資料在下載過程中格式已損壞。

問題根源

SQLite 資料庫對檔案完整性相當敏感,只要下載過程中寫入的位元組有損,整份檔案就會無法開啟。這通常是因為下載時使用的緩衝區大小,與底層 socket 讀寫的行為產生了不一致。

解決方案:縮小讀取緩衝區

於是我採取了與先前相同的策略,把每次讀取的陣列調小。以下是下載任務的程式碼:

public class DownloadTask {
    public static File getFile(String path, String filePath, ProgressDialog progressDialog) throws Exception {
        URL url = new URL(path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(2000);
        connection.setRequestMethod("GET");
        if (connection.getResponseCode() == 200) {
            int total = connection.getContentLength();
            progressDialog.setMax(total);
            InputStream is = connection.getInputStream();
            File file = new File(filePath);
            FileOutputStream fos = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int len;
            int progress = 0;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer);
                progress += len;
                progressDialog.setProgress(progress);
            }
            fos.flush();
            is.close();
            fos.close();
            connection.disconnect();
            return file;
        }
        return null;
    }
}

關鍵在於把這行裡的 1024 調小:

byte[] buffer = new byte[1024];

由於錯誤頻繁發生,筆者甚至把緩衝區改成了:

byte[] buffer = new byte[8];

如此一來資料庫檔案就不再損壞了。

取捨與權衡

這個方法有個明顯弊端:緩衝區越小,下載速度越慢。由於該資料庫高達 16MB,用 8 位元組緩衝區下載可說是奇慢無比。因此這只是一個臨時性的解法,後續仍需尋找更根本的最佳化方式,在資料完整性與下載效率之間取得平衡。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved