简体   繁体   中英

how do i create the database in my android app?

I'm trying to use SQLite in my android app. I've created the helper class like this:

public class EventoSQLHelper {

    // Configuração da base(nome e versão)
    private static final int DB_VERSAO = 1;
    private static final String DB_NOME = "pacixDB";

    // Configuração da tabela (nome, colunas, tag para log)
    private static final String tabela_nome = "eventos";
    private static final String coluna_id = "id";
    private static final String coluna_desc = "descricao";
    private static final String coluna_data = "dataEvento";
    private static final String TAG = EventoSQLHelper.class.getSimpleName();

    // Comando sql para criação da tabela
    private static final String DATABASE_CREATE = "create table if not exists eventos (id integer primary key autoincrement, "
            + "descricao VARCHAR not null, dataEvento date);";

    // Contexto para o qual vai passar as informações
    private final Context context = null;

    private DataBaseHelper DBHelper;
    private SQLiteDatabase database;

    // Helper que extende de SQLiteOpenHelper - implementa práticas para salvar,
    // criar, etc
    private static class DataBaseHelper extends SQLiteOpenHelper {

        DataBaseHelper(Context context) {
            super(context, DB_NOME, null, DB_VERSAO);
        }

        // executado quando cria a classe: cria a base se não existir
        @Override
        public void onCreate(SQLiteDatabase db) {
            try {
                db.execSQL(DATABASE_CREATE);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // método para upgrade da base
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Atualizando base da versão " + oldVersion
                    + " para a versão " + newVersion
                    + ", que irá destruir todos os dados.");
            db.execSQL("DROP TABLE IF EXISTS eventos");
            onCreate(db);
        }
    }

    public EventoSQLHelper Open() throws SQLException {
        this.database = DBHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        DBHelper.close();
    }

    public long inserirRegistro(String descricao, String data) {
        ContentValues valoresIniciais = new ContentValues();
        valoresIniciais.put(coluna_desc, descricao);
        valoresIniciais.put(coluna_data, data);
        return database.insert(tabela_nome, null, valoresIniciais);
    }

    public boolean deletarRegistro(long id) {
        return database.delete(tabela_nome, coluna_id + " = " + id, null) > 0;
    }

    public Cursor getRegistros() {
        return database.query(false, tabela_nome, new String[] { coluna_id,
                coluna_desc, coluna_data }, null, null, null, null, null, null);
    }

I've followed some tutorials on the internet and i've understand the sqlhelper class. But now, how do i create the database? It's a file, right? Do i have to create it on onCreate method of my main activity?

How do i do this?

Well, let's quote the Docs :

A helper class to manage database creation and version management.

You create a subclass implementing onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int) and optionally onOpen(SQLiteDatabase), and this class takes care of opening the database if it exists, creating it if it does not, and upgrading it as necessary. Transactions are used to make sure the database is always in a sensible state.

So what this means is, that you don't have to explicity create the "database-file" it's done for you by the SQLiteOpenHelper . So the first time you're opening your Database it will be created. (It will automatically run through onCreate in your DataBaseHelper)

You typically use a SQLiteOpenHelper from within a ContentProvider.

http://developer.android.com/guide/topics/providers/content-provider-basics.html

The SQLite database is a file, but normally you needn't care about that.

The database file is indeed created when the helper's onCreate method is called (assuming no exception is thrown.) Remember that, unless you uninstall the app, you shouldn't expect this method to be called again.

During the normal lifetime of an app, you'll probably provide updates and post the new version on the app store where people will either download it for the first time and install it (onCreate called) or update it (onUpgrade called ONLY if you incremented the database version number.)

Since the Google play store currently doesn't provide a way to allow users to go back to an older version of your app, you typically don't have to worry about onDowngrade. If, however, you are providing older versions of your app outside of the Google play store, you should at least override onDowngrade so it doesn't throw a SQLiteException which is what the default implementation does.

Now, back to onUpgrade. Some things you might need to do here are add a table, modify an existing table, drop a table, etc. I have handled this by writing .sql scripts that I put in the assets folder of my app with a name like upgrade_v1_v2.sql.

There are some gotchas with SQLite you should be aware of that are detailed here:

http://www.sqlite.org/omitted.html

There are usually workarounds, however. For example, if you wanted to add a new column with a foreign key constraint to an existing table, you can't use the ALTER TABLE command for this since it is currently not supported by SQLite. Instead, you'll have to make a temporary table with the new set of columns you want, then copy the data from the old table to this temporary table, then drop the old table, and finally rename the temporary table to the old table's name - all preferably within a transaction to guard against something going wrong halfway through.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM