You should create a class that extends from SQLiteOpenHelper
, where it will be responsible for creating your database on the device based on the SQL statements provided by you.
Example:
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "NOME_DO_ARQUIVO_DO_BANCO.db";
private static final int DATABASE_VERSION = 1;
private static DBHelper instance;
private static SQLiteDatabase com;
private Context context;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL("CREATE TABLE IF NOT EXISTS TABELA1 (ID INTEGER, nome varchar(100) PRIMARY KEY ([ID]));");
database.execSQL("CREATE TABLE IF NOT EXISTS TABELA2 (ID INTEGER, nome varchar(100) PRIMARY KEY ([ID]));");
}
@Override
public void onUpgrade(SQLiteDatabase database, int versaoAntiga, int novaVersao) {
}
public static DBHelper getInstance(Context context){
if (instance == null){
instance = new DBHelper(context);
}
return instance;
}
//cria a conexao com o banco de dados
public SQLiteDatabase open() throws SQLException {
if (com == null){
com = this.getWritableDatabase();
if (!com.isReadOnly()) {
// Enable foreign key constraints
com.execSQL("PRAGMA foreign_keys=ON;");
}
}
return com;
}
}
And to access your database simply do the following:
private DBHelper dbHelper;
private SQLiteDatabase connection;
dbHelper = DBHelper.getInstance(context);
connection = dbHelper.open();
Saving a record to the bank:
ContentValues values = new ContentValues();
values.put("ID",1);
values.put("NOME","JOÃO");
connection.insertOrThrow("TABELA1", null,values);