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

Android开发点滴(13) -- Android数据库随同Android应用一同发布

2011-10-25 20:29 555 查看
实现方法:将Android数据库文件放到res/raw目录下,然后读取db文件,并且将其写到data/data/pkg_name/databases/目录下,获取SDCard中。

1 package com.sqllite.activity;
2
3 import java.io.File;
4 import java.io.FileNotFoundException;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.io.InputStream;
8
9 import android.app.Activity;
10 import android.content.res.Resources;
11 import android.database.Cursor;
12 import android.database.sqlite.SQLiteDatabase;
13 import android.os.Bundle;
14
15 public class SqlLiteActivity extends Activity {
16 private File file = null;
17 private File dir = null;
18
19 @Override
20 public void onCreate(Bundle savedInstanceState) {
21 super.onCreate(savedInstanceState);
22 setContentView(R.layout.main);
23
24 // 第一次运行应用程序时,加载数据库到data/data/<pkg_name>/database/<db_name>
25 dir = new File("data/data/" + getPackageName() + "/databases");
26 if (!dir.exists() || !dir.isDirectory()) {
27 dir.mkdir();
28 }
29 file = new File(dir, "db.db3");
30
31 if (!file.exists()) {
32 FileUtils.loadDbFile(R.raw.db, file, getResources(),
33 getPackageName());
34 }
35
36 // 读取数据库
37
38 SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(file, null);
39 //SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);
40 Cursor cursor = db.query("people", new String[] { "id", "name", "age", "address" },
41 null, null, null, null, null);
42
43 while(cursor.moveToNext()){
44 System.out.println(cursor.getInt(0));
45 }
46 cursor.close();
47 }
48
49 }
50
51 class FileUtils {
52
53 public static void loadDbFile(int rawId, File file, Resources res,
54 String pkgname) {
55 InputStream dbInputStream = res.openRawResource(R.raw.db);
56 FileOutputStream fos = null;
57
58 try {
59 fos = new FileOutputStream(file);
60
61 byte[] bytes = new byte[1024];
62 int length;
63 while ((length = dbInputStream.read(bytes)) > 0) {
64 fos.write(bytes, 0, length);
65 }
66
67 } catch (FileNotFoundException e) {
68 // TODO Auto-generated catch block
69 e.printStackTrace();
70 } catch (IOException e) {
71 // TODO Auto-generated catch block
72 e.printStackTrace();
73 } finally {
74 try {
75 fos.close();
76 dbInputStream.close();
77 } catch (IOException e) {
78 // TODO Auto-generated catch block
79 e.printStackTrace();
80 }
81 }
82 }
83 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: