您的位置:首页 > 移动开发 > Android开发

将本地sqlite数据库导入到一个新android项目中

2013-07-12 14:42 309 查看
熊猫猫韩国代购

第一步,创建一个类如下所示,用于将本地数据库文件导入相应的存放数据库的文件夹下面

package com.example.testimportdb;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import android.content.Context;

import android.os.Environment;

public class ImportDB {

public static final String DB_NAME = "benwee_city"; // 保存的数据库文件名

public static final String PACKAGE_NAME = "com.example.testimportdb";// 工程包名

public static final String DB_PATH = "/data"

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

+ PACKAGE_NAME + "/databases"; // 在手机里存放数据库的位置

private Context context;

ImportDB(Context context) {

this.context = context;

}

public void copyDatabase() {

String dbfile = DB_PATH + "/" + DB_NAME;

try {

// 执行数据库导入

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

.open("benwee_city.db"); // 欲导入的数据库

FileOutputStream fos = new FileOutputStream(dbfile);

byte[] buffer = new byte[1024];

int count = 0;

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

fos.write(buffer, 0, count);

}

fos.close();// 关闭输出流

is.close();// 关闭输入流

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

}

第二步,创建一个类DBOpenHelper

public class DBOpenHelper extends SQLiteOpenHelper {

private static String NAME = "benwee_city";

private static final int version = 1;

private static final String CREATE_TABLE_CITY = "create table if not exists city(id text primary key,"

+ "province text,areaname text,cityname text,pyname text)";

/* 创建一个表,将点击过的,在WeatherActivity界面中显示过的城市的信息保存在里面。 */

private static final String CREATE_TABLE_WEATHER = "create table if not exists weather(cityname text,"

+ "tempnow text,weatherstatedetails text,temp text,wind text,time text,rays text,comfortable text,clothes text)";

private static final String DROP_TABLE_CITY = "drop table if exists city";

public DBOpenHelper(Context context) {

super(context, NAME, null, version);

}

@Override

public void onCreate(SQLiteDatabase db) {

db.execSQL(CREATE_TABLE_CITY);

db.execSQL(CREATE_TABLE_WEATHER);

}

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

// db.execSQL(DROP_TABLE_CITY);

}

}

第三步,在合适的地方调用下面语句:

DBOpenHelper dbOpenHelper = new DBOpenHelper(getApplicationContext());

SQLiteDatabase db = dbOpenHelper.getWritableDatabase();

new ImportDB(GuideActivity.this).copyDatabase();

搞定!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐