Android导入已有的SQLite数据库

来源:互联网 发布:淘宝客推广如何收费 编辑:程序博客网 时间:2024/05/19 14:38

1.要在res文件夹下新建一个raw文件夹,把sqlite数据库复制到raw文件夹。新建一个MyDatabaseHelper类,代码如下

package com.example.sqlitetest;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 MyDatabaseHelper {    private final int BUFFER_SIZE = 400000;    public static final String DB_NAME = "test.db"; //保存的数据库文件名    public static final String PACKAGE_NAME = "com.example.sqlitetest";//包名    public static final String DB_PATH = "/data"            + Environment.getDataDirectory().getAbsolutePath() + "/"            + PACKAGE_NAME + "/databases";  //存放数据库的位置    private SQLiteDatabase database;    private Context context;    MyDatabaseHelper(Context context){        this.context = context;    }        public void openDatabase() {        File dFile=new File(DB_PATH);//判断路径是否存在,不存在则创建路径         if (!dFile.exists()) {             dFile.mkdir();            }               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.test); //欲导入的数据库                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;    }    public void closeDatabase() {        this.database.close();    }}

2.在MainActivity中

package com.example.sqlitetest;import android.app.Activity;import android.os.Bundle;public class MainActivity extends Activity {    MyDatabaseHelper myDatabaseHelper;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        myDatabaseHelper=new MyDatabaseHelper(this);        myDatabaseHelper.openDatabase();        myDatabaseHelper.closeDatabase();       }}

3.结果如图
这里写图片描述
附上源码
sqlitetest

0 0
原创粉丝点击