The first thing to do is copy your file "meubanco.db" to the android app folder. For this, do the following:
- Create a folder called Assets in: Camiodoprojeto/app/src/main
- Copy the file "meubanco.db" to the folder Assets
Next, you should create a class that will open, read, close, etc. the database. This class should extend SQLiteOpenHelper
. An example would be:
public class Database extends SQLiteOpenHelper{
private static String DB_PATH = "/data/data/pacote.da.aplicaco/databases/";
private static String DB_NAME = "meubanco.db";
private SQLiteDatabase bdQuery;
private final Context bdContext;
public Database(Context context) {
super(context, DB_NAME, null, 1);
this.bdContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
// Utilize este método para criar o banco de dados direto da aplicação
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Atualiza o banco de dados se houver uma versão nova.
}
private void criarBancoDeDados() throws IOException {
boolean dbExist = checarBancoDeDados();
if (!dbExist) {
this.getReadableDatabase();
try {
this.copiarBancoDeDados();
} catch (IOException e) {
throw new Error("Erro ao copiar o Banco de Dados!");
}
}
}
private void copiarBancoDeDados() throws IOException {
InputStream myInput = bdContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
private boolean checarBancoDeDados() {
SQLiteDatabase checkDB = null;
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void abrirBancoDeDados() throws SQLException {
String myPath = DB_PATH + DB_NAME;
bdQuery = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
//Permite que a aplicação reconheça chaves estrangeiras
bdQuery.execSQL("PRAGMA foreign_keys = ON;");
}
public void setBancoDados() {
try {
criarBancoDeDados();
abrirBancoDeDados();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
In this case, when you wanted to "create" the database, you would need to do:
Database mDatabase = new Database(mContext);
mDatabase.setBancoDeDados();