简体   繁体   中英

placing existing sqlite database and reading

Where to place existing sqllite database in android folder structure? Is it drawable folder or layout folder?

I am not finding any solution for this.

Any help will be appreciated.

you should put it in the assets folder. This way you can make sure it will be attached to your apk. this is how you can copy the database file from the assets folder to your working directory:

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

//transfer bytes from the inputfile to the 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();

}

now to read the database from the directory:

 public void openDataBase() throws SQLException{

//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

}

As name should indicate drawable or layout are NOT for database. If you want to distribute pre-set database with your app, then it's not relevant where you put it (aside that when you try to put it in drawable or layout you will not be able to build your app). Most sane place is assets folder. And there's quite nice helper that would help you with the task of setting such database for use with the app: https://github.com/jgilfelt/android-sqlite-asset-helper

Path: data -> data -> com.yourcompany.yourappid -> databases or you can use Astro File Manager application to find the database on your device and to browse your device folder structure.

This code presents how to locate sql's DB file on your device:

var dbName = 'dbData';
var dbPath;
var dbFile;
if ( Ti.Platform.osname == 'android' ) {
    dbPath = 'file:///data/data/' + Ti.App.getID() + '/databases/';
    dbFile = Ti.Filesystem.getFile( dbPath + dbName ); 
}
else {
    dbPath = Ti.Filesystem.applicationSupportDirectory + '/database/';
    dbFile = Ti.Filesystem.getFile( dbPath + dbName + '.sql' );
}

Personaly I place the sqllite database in the assets folder. And for use it, you can copy it to "/data/data/your.application.package.name/databases/

you should put your external database file in assets folder :

And after that make a Class for it.

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.appguideextra/databases/"; // path
// of
// your
// datbase
 public static String DB_NAME = "AppGuide.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();
    }
}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM