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

前端之家收集整理的这篇文章主要介绍了将本地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,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();


搞定!!!

原文链接:https://www.f2er.com/sqlite/201196.html

猜你在找的Sqlite相关文章