在各个博客网站查询了很多方法,虽然能够导入,但是表是空的,个人判断是外部数据库类型(如后缀为db,sql)的原因,改为sqlite类型的数据库就可以正常导入所有外部数据库的信息了,以下是导入的几个步骤:
方法一是使用虚拟机的目录的upload方法直接导入,具体步骤去查其他博主的吧,这里主要讲使用代码来写入外部的数据库:
方法二,代码导入: 1.创建外部数据库和数据表:
并把该数据库放到项目中的assets或者raw这两个目录中(自行创建的目录) ![在这里插入图片描述](https://img-blog.csdnimg.cn/944d682a2fec453fa1986aaa282abc36.png
2.创建IO流的封装类来写入数据库:
public class NationOpenDB {
private final int BUFFER_SIZE = 400000;
public static final String DB_BANE = "nations.sqlite";
public static final String PACKAGE_NAME = "com.example.test2";
public static final String DB_PATH = "/data" + Environment.getDataDirectory().getAbsolutePath() + "/"
+ PACKAGE_NAME + "/databases";
private Context context;
public NationOpenDB(Context context) {
this.context = context;
}
public SQLiteDatabase openDatabase(){
try {
File myDataPath = new File(DB_PATH);
if (!myDataPath.exists()) {
myDataPath.mkdirs();
}
String dbFile = myDataPath + "/" + DB_BANE;
if (!(new File(dbFile).exists())) {
InputStream is = context.getAssets().open(DB_BANE);
FileOutputStream fos = new FileOutputStream(dbFile);
byte[] buffer = new byte[BUFFER_SIZE];
int count = 0;
while ((count = is.read(buffer)) !=-1) {
Log.e("test2", "写入"+String.valueOf(count));
fos.write(buffer, 0, count);
}
fos.flush();
fos.close();
is.close();
}
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
return db;
} catch (FileNotFoundException e) {
Log.e("test2", "File not found!");
e.printStackTrace();
} catch (IOException e) {
Log.e("test2", "IO exception");
e.printStackTrace();
}
Log.e("test2", "没有??!");
return null;
}
}
注意这些成员变量:DB_NAME(使用sqlite文件类型的数据库),PACKAGE_NAME(应用包名)
3.创建存储各条数据的实体类和实现测试
public class Nations {
public Integer id;
public String nation;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNation() {
return nation;
}
public void setNation(String nation) {
this.nation = nation;
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NationOpenDB nation = new NationOpenDB(this);
List<Nations> nationList = new ArrayList<Nations>();
SQLiteDatabase sqLiteDatabase = nation.openDatabase();
Cursor cursor = sqLiteDatabase.rawQuery("select *from china_nations", null);
Log.e("test2", "cursor:" + String.valueOf(cursor.getCount()));
while (cursor.moveToNext()) {
Nations nations = new Nations();
Integer id = cursor.getInt(cursor.getColumnIndex("id"));
String nationName = cursor.getString(cursor.getColumnIndex("nation"));
nations.setId(id);
nations.setNation(nationName);
nationList.add(nations);
}
for (Nations nations1 : nationList) {
Log.e("test2",nations1.id + " " + nations1.nation);
}
}
4.Log结果
|