我应该在源android应用程序中放置一个sqlite文件

时间:2013-12-27 08:30:16

标签: android sqlite

我是一名新的Android开发者 我有一个现有的SQLite数据库 我的问题是:我应该把它放在哪里? 而且:我想在安装时将其复制到设备上。

请帮忙

谢谢

4 个答案:

答案 0 :(得分:2)

你做了什么。

您必须将外部sqlite数据库文件放在 资产 文件夹中,然后复制到 SD卡 并访问它

例如,

只创建一个名为

的类

DBConnect.java

package com.appgiudeextra.Database;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

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;

import com.appguideextra.Items.MasterItem;

public class DBConnect extends SQLiteOpenHelper {
public int GetCursor;
// ****************** Declare all the global variable
// ****************************//
private Context myContext;
public String DB_PATH = "data/data/com.xyz/databases/"; // path
// of
// your
// datbase
public static String DB_NAME = "xyz.sqlite";// your database name
static String ASSETS_DB_FOLDER = "db";
private SQLiteDatabase db;

public DBConnect(Context context, String db_name) {
    super(context, db_name, null, 2);
    if (db != null && db.isOpen())
        close();

    this.myContext = context;
    DB_NAME = db_name;

    try {
        createDataBase();
        openDataBase();
    } catch (IOException e) {
        // System.out.println("Exception in creation of database : "+
        // e.getMessage());
        e.printStackTrace();
    }

}

public void createDataBase() throws IOException {
    boolean dbExist = checkDataBase();

    if (dbExist) {
        // System.out.println("Database Exist");
    } else {
        this.getReadableDatabase();

        try {
            copyDatabase();
        } catch (IOException e) {
            throw new Error("Error copying database");
        }
    }
}

private void copyDatabase() throws IOException {
    InputStream input = myContext.getAssets().open(DB_NAME);
    String outputFileName = DB_PATH + DB_NAME;
    OutputStream output = new FileOutputStream(outputFileName);

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

    // Close the streams
    output.flush();
    output.close();
    input.close();
    // System.out.println(DB_NAME + "Database Copied !");
}

@Override
public void onCreate(SQLiteDatabase db) {

}

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

}

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

public boolean isOpen() {
    if (db != null)
        return db.isOpen();
    return false;
}

@Override
public synchronized void close() {
    if (db != null)
        db.close();
    super.close();
}

private boolean checkDataBase() {
    SQLiteDatabase checkDB = null;
    try {
        String myPath = DB_PATH + DB_NAME;
        // System.out.println("My Pathe is:- " + myPath);
        // System.out.println("Open");
        checkDB = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
        // System.out.println("checkDB value:" + checkDB);
        // System.out.println("My Pathe is:- " + myPath);
    } catch (Exception e) {
        // database does't exist yet.
    }

    if (checkDB != null) {
        // System.out.println("Closed");
        checkDB.close();
        // System.out.println("My db is:- " + checkDB.isOpen());
    }

    return checkDB != null ? true : false;
}

public Cursor execCursorQuery(String sql) {
    Cursor cursor = null;
    try {
        cursor = db.rawQuery(sql, null);
        GetCursor = cursor.getCount();
        Log.i("Inside execCursorQuery try", sql);
    } catch (Exception e) {
        Log.i("Inside execCursorQuery exception", e.getMessage());
    }
    return cursor;
}

public void execNonQuery(String sql) {
    try {
        db.execSQL(sql);
        // Log.d("SQL", sql);
    } catch (Exception e) {
        // Log.e("Err", e.getMessage());
    } finally {
        // closeDb();
    }
}


}

将此课程访问您的活动。

答案 1 :(得分:1)

 My question is: where should I put it in my source?

您可以将数据库放入应用程序的assets文件夹中,然后将其复制到SD卡中并使用它。

尝试以下代码将数据库从资产文件夹复制到SD卡。

DataBaseHelper.java

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();
    }

}

 I want copy it to device upon installation.

在启动器活动中创建DataBaseHelper类的实例,如下所示,它将直接复制数据库。

DataBaseHelper dbhelper=new DataBaseHelper(MyActivity.this);

答案 2 :(得分:0)

你可以将你的数据库放在assets文件夹中,然后将这个数据库复制到sdcard并从sdcard中检索该数据库:

复制数据库:

public static void copyDataBase(Context mActivity) throws IOException {
        InputStream myInput = new FileInputStream(new File("/data/data/"
                + mActivity.getPackageName() + "/databases/" + "aman36.sqlite"));
        File files = new File("/sdcard/files/");
        files.mkdirs();
        String outFileName = "/sdcard/files/aman36.sqlite";
        OutputStream myOutput = new FileOutputStream(outFileName);
        byte[] buffer = new byte[1024];
        int bufferLength;
        while ((bufferLength = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, bufferLength);
        }
        myOutput.flush();
        myOutput.close();
        myInput.close();
    }

你可以访问你的路径来检索数据库 - > sdcard-> files-> aman36.sqlite

答案 3 :(得分:0)

将database.sqlite文件放在项目目录的asset文件夹中,并使用this 检索它 链接。