Insert sqlite in android app

Asked

Viewed 276 times

2

I’m developing a sqlite database for the application part. At this time I am using the Sqlitebrowser, and would like to know how to do to grab the database and put to the application read this. I have a slight notion that I have to create a separate class for the database but that’s all I know.

2 answers

2

You must 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 just do the following:

private Dbhelper dbHelper; Private Sqlitedatabase Connection;

dbHelper = DBHelper.getInstance(context);               
connection = dbHelper.open();

Saving a record in the bank:

ContentValues values = new ContentValues();
values.put("ID",1);
values.put("NOME","JOÃO");
connection.insertOrThrow("TABELA1", null,values);

1

The first thing to do is copy your file "meubanco.db" to the android app folder. For this, do the following:

  1. Create a folder called Assets in: Camiodoprojeto/app/src/main
  2. 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();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.