Insert sqlite into android application

2

I'm developing a database in sqlite part of the application. At this point I am using the SqliteBrowser, and would like to know how to do to get the database and put for the application to read this. I have a slight notion that I have to create a separate class for the database but that's all I know.

    
asked by anonymous 20.08.2015 / 01:01

2 answers

2

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);
    
14.09.2015 / 16:04
1

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

  • Create a folder named assets in: ProjectTree / app / src / main
  • Copy the "meubanco.db" file to the assets
  • Then you should create a class that will open, read, close, and so on. of the database. This class must 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();
    
        
    20.08.2015 / 14:40