First, in your build.gradle
(module:app)
Add the following line:
compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
It’ll help us connect to the bank.
Sync your Radle after this.
Then, in your project, right-click the folder app
, click new > Folder > Assets Folder.
Inside the newly created folder, create another folder called "Databases". Paste the database you want to use inside that 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 the 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();
Did you make the file available where your application would create it? and gave read and write permission?
– Marco Souza