Android:使用.sqlite扩展名访问assets文件夹sqlite数据库文件

时间:2010-04-09 06:47:18

标签: android

如何在我的Android应用程序中使用.sqlite扩展名读取资产文件夹sqlite数据库文件中的数据?

7 个答案:

答案 0 :(得分:33)

试试这段代码:

public class DataBaseHelper extends SQLiteOpenHelper {
    private Context mycontext;

    //private String DB_PATH = mycontext.getApplicationContext().getPackageName()+"/databases/";
    private static String DB_NAME = "(datbasename).sqlite";//the extension may be .sqlite or .db
    public SQLiteDatabase myDataBase;
    /*private String DB_PATH = "/data/data/"
                        + mycontext.getApplicationContext().getPackageName()
                        + "/databases/";*/

    public DataBaseHelper(Context context) throws IOException {
        super(context,DB_NAME,null,1);
        this.mycontext=context;
        boolean dbexist = checkdatabase();
        if (dbexist) {
            //System.out.println("Database exists");
            opendatabase(); 
        } else {
            System.out.println("Database doesn't exist");
            createdatabase();
        }
    }

    public void createdatabase() throws IOException {
        boolean dbexist = checkdatabase();
        if(dbexist) {
            //System.out.println(" Database exists.");
        } else {
            this.getReadableDatabase();
            try {
                copydatabase();
            } catch(IOException e) {
                throw new Error("Error copying database");
            }
        }
    }   

    private boolean checkdatabase() {
        //SQLiteDatabase checkdb = null;
        boolean checkdb = false;
        try {
            String myPath = DB_PATH + DB_NAME;
            File dbfile = new File(myPath);
            //checkdb = SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE);
            checkdb = dbfile.exists();
        } catch(SQLiteException e) {
            System.out.println("Database doesn't exist");
        }
        return checkdb;
    }

    private void copydatabase() throws IOException {
        //Open your local db as the input stream
        InputStream myinput = mycontext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outfilename = DB_PATH + DB_NAME;

        //Open the empty db as the output stream
        OutputStream myoutput = new FileOutputStream("/data/data/(packagename)/databases   /(datbasename).sqlite");

        // transfer byte to inputfile to outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myinput.read(buffer))>0) {
            myoutput.write(buffer,0,length);
        }

        //Close the streams
        myoutput.flush();
        myoutput.close();
        myinput.close();
    }

    public void opendatabase() throws SQLException {
        //Open the database
        String mypath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(mypath, null, SQLiteDatabase.OPEN_READWRITE);
    }

    public synchronized void close() {
        if(myDataBase != null) {
            myDataBase.close();
        }
        super.close();
    }

}

答案 1 :(得分:7)

将旧数据库(old.db)放在资产文件夹中。在您的活动的onCreate()中键入此内容:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
....

//=======Code For copying Existing Database file to system folder for use====//
    // Copying Existing Database into system folder
        try {

            String destPath = "/data/data/" + getPackageName()
                    + "/databases/data.db";

            File f = new File(destPath);
            if(!f.exists()){
            Log.v(TAG,"File Not Exist");
            InputStream in = getAssets().open("old.db");
            OutputStream out = new FileOutputStream(destPath);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            in.close();
            out.close();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            Log.v("TAG","ioexeption");
            e.printStackTrace();
        }

        DBManager dbManager =  new DBManager(this);
        Log.v(TAG,"Database is there with version: "+dbManager.getReadableDatabase().getVersion());
        String sql = "select * from prizes";


        SQLiteDatabase db = dbManager.getReadableDatabase();
        Cursor cursor = db.rawQuery(sql, null);
        Log.v(TAG,"Query Result:"+cursor);


        cursor.close();
        db.close();
        dbManager.close();

....

} 

现在你必须创建一个DBManager类,它是SQLiteOpenHelper的子类。插入抽象方法和构造函数。不要忘记在dbHelper的super()中键入正确的数据库名称。

public class DBManager extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
private static final String TAG = "DATABASES";

public DBManager(Context context) {
    super(context, "data.db", null, DATABASE_VERSION);

}

@Override
public void onCreate(SQLiteDatabase db) {
    Log.v(TAG,"On create Called:"+db.getPath());
}

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

现在您可以通过实例化DBManager来访问数据库。

SQLiteDatabase db = dbManager.getReadableDatabase();
Cursor cursor = db.rawQuery(sql, null);
...

不要忘记关闭数据库,否则你将获得SQLiteDatabaseNotClosed Exception。

db.close();
dbManager.close();

答案 2 :(得分:2)

重要的是,在本教程中,当您调用文件时,请确保传递应用程序上下文getApplicationContext(),以便您可以访问正确的资产,否则可能会出现FileNotFound异常。

答案 3 :(得分:1)

您需要尝试android sqlite asset helper。它为我打开一个预先存在的数据库是一块蛋糕。

我花了3个小时尝试全部手动完成后,大约半小时内完成了工作。有趣的是,我以为我在做同样的事情,图书馆为我做了,但有些东西丢失了!

答案 4 :(得分:0)

如果您打算创建一个新的SQLite数据库,那么请过度使用并实现onCreate()方法,如教程中所示。

但是如果您使用的是由另一个外部源创建的SQLite数据库,并且您要将其拉下来,那么请将onCreate()方法保留为空。

答案 5 :(得分:0)

您只能从资产文件夹中读取数据库,因为资源文件夹是只读的。如果你需要做更多的操作,比如创建,更新,删除,你可以做一些技巧。将数据库从assets文件夹复制到存储,然后您可以执行任何操作。

以下是Working with Android Pre Built Database.

的简要示例

还有一个易于使用的库,用于从assets文件夹访问数据库。您可以查看Android SQLiteAssetHelper(https://github.com/jgilfelt/android-sqlite-asset-helper)。祝好运!

答案 6 :(得分:0)

您需要将.sqlite数据库转换为.db才能适合Android。

在您的应用安装后首次启动

SuperDatabase database=new SuperDatabase(getApplicationContext(),"foods.db", AssetDatabaseMode.COPY_TO_SYSTEM);

随后发布

SuperDatabase database=new SuperDatabase(getApplicationContext(),"foods.db", AssetDatabaseMode.READ_FROM_DEVICE);

简单地触发SQL查询

database.sqlInject("INSERT INTO food VALUES('Banana','Vitamin A');");

以CSV,JSON,XML

获取Array的结果
ArrayList<String> rows=new ArrayList<String>();
rows=database.sqlEjectCSV("SELECT * FROM food;");
for (int i=0;i<rows.size();i++)
{
    //Do stuffs with each row
}

您需要包含我的库。文件在这里:
Ruby on Rails