如何導入已有的外部數據庫 – Android移動開發技術文章_手機開發 Android移動開發教學課程

我們平時見到的android數據庫操作一般都是在程序開始時創建一個空的數據庫,然後再進行相關操作。如果我們需要使用一個已有數據的數據庫怎麼辦呢?
我們都知道android系統下數據庫應該存放在 /data/data/com.*.*(package name)/ 目錄下,所以我們需要做的是把已有的數據庫傳入那個目錄下。操作方法是用FileInputStream讀取原數據庫,再用FileOutputStream把讀取到的東西寫入到那個目錄。
操作方法:1. 把原數據庫包括在項目源碼的 res/raw 目錄下,然後建立一個DBManager類,代碼如下:

view plain

package com.android.ImportDatabase; 

 

import java.io.File; 

import java.io.FileNotFoundException; 

import java.io.FileOutputStream; 

import java.io.IOException; 

import java.io.InputStream; 

 

import android.content.Context; 

import android.database.sqlite.SQLiteDatabase; 

import android.os.Environment; 

import android.util.Log; 

 

public class DBManager { 

    private final int BUFFER_SIZE = 400000; 

    public static final String DB_NAME = "countries.db"; //保存的數據庫文件名 

    public static final String PACKAGE_NAME = "com.android.ImportDatabase"; 

    public static final String DB_PATH = "/data" 

            + Environment.getDataDirectory().getAbsolutePath() + "/" 

            + PACKAGE_NAME;  //在手機裡存放數據庫的位置 

 

    private SQLiteDatabase database; 

    private Context context; 

 

    DBManager(Context context) { 

        this.context = context; 

    } 

 

    public void openDatabase() { 

        this.database = this.openDatabase(DB_PATH + "/" + DB_NAME); 

    } 

 

    private SQLiteDatabase openDatabase(String dbfile) { 

        try { 

            if (!(new File(dbfile).exists())) {  //判斷數據庫文件是否存在,若不存在則執行導入,否則直接打開數據庫 

                InputStream is = this.context.getResources().openRawResource( 

                        R.raw.countries); //欲導入的數據庫 

                FileOutputStream fos = new FileOutputStream(dbfile); 

                byte[] buffer = new byte[BUFFER_SIZE]; 

                int count = 0; 

                while ((count = is.read(buffer)) > 0) { 

                    fos.write(buffer, 0, count); 

                } 

                fos.close(); 

                is.close(); 

            } 

            SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, 

                    null); 

            return db; 

        } catch (FileNotFoundException e) { 

            Log.e("Database", "File not found"); 

            e.printStackTrace(); 

        } catch (IOException e) { 

            Log.e("Database", "IO exception"); 

            e.printStackTrace(); 

        } 

        return null; 

    } 

然後在程序的首個Activity中示例化一個DBManager對象,然後對其執行openDatabase方法就可以完成導入瞭,可以把一些要對數據庫進行的操作寫在DBManager類裡,然後通過DBManager類的對象調用;也可以在完成導入之後通過一個SQliteDatabase類的對象打開數據庫,並執行操作。

 

我的做法是 在程序的首個Activity中導入數據庫:

 

view plain

package com.android.ImportDatabase; 

 

import android.app.Activity; 

import android.content.Intent; 

import android.os.Bundle; 

 

public class RootView extends Activity { 

 

    public DBManager dbHelper; 

    @Override 

    public void onCreate(Bundle savedInstanceState) { 

 

        super.onCreate(savedInstanceState); 

        setContentView(R.layout.main); 

 

        dbHelper = new DBManager(this); 

        dbHelper.openDatabase(); 

        dbHelper.closeDatabase(); 

 

    } 

}   

 

此時在DDMS中可以查看到,外部數據庫已經成功導入

在需要使用數據庫的類裡:

 

package com.android.ImportDatabase; 

 

import java.util.ArrayList; 

import android.app.Activity; 

import android.database.Cursor; 

import android.database.sqlite.SQLiteDatabase; 

import android.os.Bundle; 

 

public class TaxiActivity extends Activity { 

 

    private SQLiteDatabase database; 

        ArrayList<CityClass> CITY; 

 

    @Override 

    public void onCreate(Bundle savedInstanceState) { 

 

        super.onCreate(savedInstanceState); 

        setContentView(R.layout.main); 

         

        database = SQLiteDatabase.openOrCreateDatabase(DBManager.DB_PATH + "/" + DBManager.DB_NAME, null); 

 

        CITY = getCity(); 

         

        // do something with CITY 

 

        database.close(); 

    } 

 

    private ArrayList<CityClass> getCity() { 

         

        Cursor cur = database.rawQuery("SELECT city.id_city, city.name FROM taxi, city WHERE city.id_city = taxi.id_city GROUP BY city.id_city", null); 

         

        if (cur != null) { 

            int NUM_CITY = cur.getCount(); 

            ArrayList<CityClass> taxicity = new ArrayList<CityClass>(NUM_CITY); 

            if (cur.moveToFirst()) { 

                do { 

                    String name = cur.getString(cur.getColumnIndex("name")); 

                    int id = cur.getInt(cur.getColumnIndex("id_city")); 

                    CityClass city = new CityClass("", 0); 

                    System.out.println(name);  //額外添加一句,把select到的信息輸出到Logcat 

                    city.city_name = name; 

                    city.city_id = id; 

                    taxicity.add(city); 

                } while (cur.moveToNext()); 

            } 

            return taxicity; 

        } else { 

            return null; 

        } 

    } 

 

 

查看輸出的結果:

 

摘自 wenyizhenglove的專欄

發佈留言