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


熊猫猫韩国代购


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

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();


搞定!!!




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值