0

我在一个项目中,我有一个包含 2 个或更多表 n 很多条目的数据库。所以我使用 sqlite 来创建这个数据库。正如我在其他几个答案中所读到的,我将不得不将数据库文件复制到资产文件夹中。现在我在资产文件夹中有数据库文件。这是我用于 DataBaseHelperClass 的代码

package com.example.basic;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataBaseHelperClass extends SQLiteOpenHelper {

    private static String TAG = "DataBaseHelperClass";

    //The Android's default system path of your application database.
    private static String DB_PATH = "/data/data/com.example.astro/databases/";
    // Data Base Name.
    private static final String DATABASE_NAME = "MyDatabase.sqlite";
    // Data Base Version.
    private static final int DATABASE_VERSION = 1;
    // Table Names of Data Base.
    static final String TABLE_Name = "Totlist";

    public Context context;
    static SQLiteDatabase sqliteDataBase;

    public DataBaseHelperClass(Context context) {       
        super(context, DATABASE_NAME, null ,DATABASE_VERSION);
        this.context = context;
    }

    public void createDataBase() throws IOException{
        //check if the database exists
        boolean databaseExist = checkDataBase();

        if(databaseExist){
            // Do Nothing.
        }else{
            this.createDataBase();         
            copyDataBase(); 
        }// end if else dbExist
    } // end createDataBase().


    public boolean checkDataBase(){
        File databaseFile = new File(DB_PATH + DATABASE_NAME);
        return databaseFile.exists();        
    }

    private void copyDataBase() throws IOException{ 
        //Open your local db as the input stream
        InputStream myInput = context.getAssets().open(DATABASE_NAME); 
        // Path to the just created empty db
        String outFileName = DB_PATH + DATABASE_NAME; 
        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName); 
        //transfer bytes from the input file to the output file
        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();




    }

    /**
     * This method opens the data base connection.
     * First it create the path up till data base of the device.
     * Then create connection with data base.
     */
    public void openDataBase() throws SQLException{      
        //Open the database
        String myPath = DB_PATH + DATABASE_NAME;
        sqliteDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);  
    }

    /**
     * This Method is used to close the data base connection.
     */
    public synchronized void close() { 
        if(sqliteDataBase != null)
            sqliteDataBase.close(); 
        super.close(); 
    }

    public String getUserNameFromDB(){
        String query = "select desc From "+TABLE_Name;
        Cursor cursor = sqliteDataBase.rawQuery(query, null);
        String description = null;
        if(cursor.getCount()>0){
            if(cursor.moveToFirst()){
        do{
                    description = cursor.getString(0);
                }while (cursor.moveToNext());
            }
        }
        return description;
    }

    public String tot(){
        String rawQuery = "SELECT tot from Totlist WHERE Tid=1";
        Cursor cursor = sqliteDataBase.rawQuery(rawQuery, null);
        String desc=null;
        if(cursor.getCount()>0){
            if(cursor.moveToFirst()){
                do{
                    desc=cursor.getString(0);
                }while(cursor.moveToNext());
                }
            }

        return desc;
    }

    public String chq()
    {
        String q="hee";
        return q;
    }


    public void onCreate(SQLiteDatabase db) {
        // No need to write the create table query.
        // As we are using Pre built data base.
        // Which is ReadOnly.
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // No need to write the update table query.
        // As we are using Pre built data base.
        // Which is ReadOnly.
        // We should not update it as requirements of application.
    }   
}

这在 logcat 中显示了很多错误。其中之一是“错误打开跟踪文件:没有这样的文件或目录 (2)”。问题可能是资产中的文件没有复制到默认位置 n 因此它说没有这样的文件或目录。这是我关于这个数据库的第二个问题,我仍然无法从中得到结果。我的 mainactivity 中的代码是这样的。

package com.example.basic;


import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.text.Editable;
import android.view.Menu;
import android.widget.TextView;

public class Basic extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.basic);


        DataBaseHelperClass db = new DataBaseHelperClass(this);
        String s=db.chq();
        TextView tv=(TextView)findViewById(R.id.TextView1);
        tv.setText(s);



    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.basic, menu);
        return true;
    }

}

我的项目中只有这两个 .java 文件。这有什么问题吗?

4

2 回答 2

1

使用https://github.com/jgilfelt/android-sqlite-asset-helper将使发布预构建的 sqllite 数据库变得超级容易。

您只需将压缩的 sqllite 文件复制到您的资产文件夹中,它将在您第一次需要使用 db 时被复制。

于 2013-09-05T16:17:47.740 回答
0

SqlLiteOpenHelper 旨在支持在第一次打开数据库时创建和/或更新数据库。它将为您创建一个空数据库,并希望您在其中创建表。

那不是你正在做的——你的数据库已经存在。它只需要复制到正确的位置。

因此,您不应尝试扩展 SqlLiteOpenHelper。如有必要,只需将数据库复制到正确的位置并打开它(您已经编写了执行此操作的代码。)

几点建议:

与其将工作目录的路径硬编码为 DB_PATH,不如调用 context.getFilesDir(); 找到应用程序私有目录的路径。(就像您正确使用 context.getAssets() 来查找资产目录一样)。

获得本地目录的名称后,您可以附加数据库目录的名称和实际数据库文件的名称。

您还应该添加错误检查以确保您成功打开文件。

于 2013-09-05T16:10:45.097 回答