Android: How to create an external Sqlite database dynamically?

Asked

Viewed 695 times

0

I have researched this thoroughly and all the examples I have found and tested have not worked. To make the code more organized I would like to do this using the Openhelper class but I have already tested the openOrCreate () method both in Openhelper and in Activity itself. Below follows my code:

public class CriaBancoApp extends SQLiteOpenHelper {

    private static final String NOME_BANCO = "BD_AppNome.db";
    private static final String CAMINHO_BANCO = Environment.getExternalStorageDirectory() + "/AppNome/Databases/";
    private static final int VERSAO = 1;


    public CriaBancoApp(Context contexto) {
        super(contexto, CAMINHO_BANCO, null, VERSAO); 
       //SQLiteDatabase.openOrCreateDatabase(CAMINHO_BANCO, null); 
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "CREATE TABLE NomeTabela (" 
                + "Id INTEGER PRIMARY KEY AUTOINCREMENT,"
                + "AutorTraducao TEXT)";
                db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS NomeTabela");
        onCreate(db);
    }

}

Then I create the instance in Mainactivity:

CriaBancoApp banco = new CriaBancoApp(this);

And when starting the app closes. Regarding the path the folders of the app are created before creating the database I even commented this line to check if the folders are created and are. The xml Manifest already has write permission which automatically includes read permission.

1 answer

0


Well, after doing a lot of research I decided to study the parent class Sqliteopenhelper and discovered that it uses the context to define the path where the database will be created. Based on this I changed the focus of the search to how to customize a context with the path I want. In this search I got this answer: https://stackoverflow.com/a/9168969/2272934 that solved the problem. As it was all in English, I made my adaptation of this answer to Portuguese was like this:

In the class Criabancoapp I modified the constructor:

    public CriaBancoApp(Context contexto) {
        super(new ContextoBanco(contexto, CAMINHO_BANCO), NOME_BANCO, null, VERSAO);
    }

So I created a class responsible for customizing the context:

public class ContextoBanco extends ContextWrapper {
    private static final String DEPURAR_CONTEXTO = "ContextoBanco";
    private String caminho;

    public ContextoBanco(Context base, String caminho) {
        super(base);
        this.caminho = caminho;
    }

    @Override
    public File getDatabasePath(String name)  {
        String caminho_banco = caminho + name;
        if (!caminho_banco.endsWith(".db")) {
            caminho_banco += ".db" ;
        }

        File result = new File(caminho_banco);

        if (!result.getParentFile().exists()) {

            result.getParentFile().mkdirs();
        }

        if (Log.isLoggable(DEPURAR_CONTEXTO, Log.WARN)) {
         Log.w(DEPURAR_CONTEXTO, "getDatabasePath(" + name + ") = " + result.getAbsolutePath());
        }

        return result;
    }

    /* Esta versão é chamada para dispositivos Android >= api-11. */
    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) {
        return openOrCreateDatabase(name,mode, factory);
    }

    /* Esta versão é chamada para dispositivos Android < api-11 */
    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) {
        SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null);
        if (Log.isLoggable(DEPURAR_CONTEXTO, Log.WARN)) {
         Log.w(DEPURAR_CONTEXTO, "openOrCreateDatabase(" + name + ",,) = " + result.getPath());
        }
        return result;
    }

}

And in Mainactivity besides creating an instance of the Criabancoapp class it is necessary to make a query for the database to be created:

        SQLiteDatabase db;
        CriaBancoApp banco = new CriaBancoApp(this);
        String[] campos = {"Id","Nome","Idade","Etc"};
        String condicao = " Id > 0 ";
        Cursor dados = null;

        db = banco.getReadableDatabase();

        dados = db.query("Nome_da_Tabela", campos, condicao, null, null, null, null);

        if(dados != null) {

            if(dados.moveToNext()) {
                // Registro encontrado
            } else {
                // Não há registros na tabela
            }
        }

Even though I found my answer I felt I had to publish to help others who might need, after all it took me a long time to find.

Browser other questions tagged

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