Where to initialize a BD SQLite on Android?

1

I have created a single row table where the only function will be to update some values. I just have to make an INSERT with default values that run the first time

I do the following but without success. Where can I make this insert so that it only runs the first time I install and open the app?

public class BD extends SQLiteOpenHelper {

    String sqlCreate = "CREATE TABLE jugador (codigo INTEGER PRIMARY KEY AUTOINCREMENT, " +
                         "nombre TEXT DEFAULT 'Jugador')";

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(sqlCreate);
        db.execSQL("INSERT INTO jugador (nombre) VALUES ('jugador') ");

    }
}
    
asked by Antonio Ruiz 21.04.2018 в 23:32
source

2 answers

0

If you are going to add "definitive" data, you do it in onCreate of the SQLiteOpenHelper class. If they are data that you first need to obtain, for example from some EditText (MainActivity), then you must perform in that class.

@Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(sqlCreate);
        ContentValues values = new ContentValues();
        values.put(TuColumnaNombre, "jugador1");
        values.put(TuOtraColumna, "x");
        db.insert(TU_TABLA, null, values);
        // para agregar mas filas:
        values.clear();
        values.put(TuColumnaNombre, "jugador2");
        values.put(TuOtraColumna, "y");
        db.insert(TU_TABLA, null, values);
        }
    }

To see the changes and not show any errors, delete the app of the emulator / device and go to File- Invalidate Caches/restart

    
answered by 22.04.2018 в 04:59
-1
  

Where can I make this insert so that it only runs the first time   to install and open the app?

You can do it in the method onCreate() , you can create a method and call it at this point

   @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(sqlCreate);

         //Realiza insercion de datos, unicamente al iniciar.

    }

in fact you are doing it but probably the table already exists and has an incorrect structure, I suggest 3 options:

1) Delete the application cache.

2) Remove the application.

3) You can change the version you assign to the version of the Database when you call the method:

public BD(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }
    
answered by 21.04.2018 в 23:53