First of all, in your build.gradle
(module: app)
Add the following line:
compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
It will help us connect with the bank.
Synchronize your gradient after that.
Then, in your project, right-click the app
folder, click new > folder > assets folder.
Within the newly created folder, create another folder called "databases". Paste the bank you want to use inside this folder.
Now, create a class called DatabaseOpenHelper
.
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class DatabaseOpenHelper extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "meubd.db";
private static final int DATABASE_VERSION = 1;
public DatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
Now let's instantiate and open the connection.
Create class DatabaseAccess
;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseAccess {
private SQLiteOpenHelper openHelper;
private SQLiteDatabase database;
private static DatabaseAccess instance;
/**
* Construtor privado
* @param context
*/
DatabaseAccess(Context context) {
this.openHelper = new DatabaseOpenHelper(context);
}
/**
* Retorna um singleton de DatabaseAccess
*
* @param context
*/
public static DatabaseAccess getInstance(Context context) {
if (instance == null) {
instance = new DatabaseAccess(context);
}
return instance;
}
/**
* Abre a conexão
*/
public void open() {
this.database = openHelper.getWritableDatabase();
}
/**
* Fecha a conexão
*/
public void close() {
if (database != null) {
this.database.close();
}
}
Create the methods you need within this class (a select
, for example), open the connection in the class you are using
DatabaseAccess db = new DatabaseAccess()
db.open();
Call your method:
db.MetododeSelect();
close the connection:
db.close();