Search code examples
androidsqlitesql-updateandroid-sqlite

SQLite on android studio assigns random numbers to ID and doesn'tt update


been trying for the past hour to find the problem but it's getting out of hands, my app can read the data, I use display all info to get it into an ArrayList of strings, that seems accurate, then when I tried updating new data is when problems started appearing, the biggest of them is that when I see what's actually inside the DBDatabase showing random IDs

EDIT: The real problem is that they dont start as ID 1, 2, 3, 4, 5

As you can see they are not really "random" but the jump they make from id is, or at least seem to be, cause they started at 21, maybe it's my delete method?

  public void deleteAll()
{
    SQLiteDatabase db = this.getWritableDatabase();
    // db.delete(TABLE_NAME,null,null);
    //db.execSQL("delete * from"+ TABLE_NAME);
    db.execSQL("delete from "+ TABLE_NAME);
}

Here is my code, maybe someone can help me out here, thanks, sorry if this question annoys you, I always try to ask on here as the last resource.

public class AmmunitionDbHelper extends SQLiteOpenHelper {
/*
Nombre de la BBDD
 */
private static final String DATABASE_NAME = "ammunition.db";
/*
Version actual de la BBDD
Si cambiamos el esquema actualizamos el numero
 */
private static final int DATABASE_VERSION = 3;

public AmmunitionDbHelper(@Nullable Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}



@Override
public void onCreate(SQLiteDatabase db) {
    String SQL_CREATE_PETS_TABLE = "CREATE TABLE " + TABLE_NAME +
            "("
            + AmmunitionEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + AmmunitionEntry.COLUMN_TORPEDO_QUANTITY + " TEXT NOT NULL);";
    db.execSQL(SQL_CREATE_PETS_TABLE);
}
public ArrayList<String> displayDatabaseInfo() {
    SQLiteDatabase db = this.getReadableDatabase();
    ArrayList<String> ammunition = new ArrayList<String>();
    //La projection nos indica las columnas que consultamos
    String[] projection = {
            _ID,
            AmmunitionEntry.COLUMN_TORPEDO_QUANTITY
    };
    Cursor cursor = db.query(
            TABLE_NAME,
            projection,
            null,
            null,
            null,
            null,
            null
    );
    //obtenemos indices de las columnas
    int quantityColumn = cursor.getColumnIndex(AmmunitionEntry.COLUMN_TORPEDO_QUANTITY);

    //Con cada uno de los indices ya podemos recorrer las filas
    while(cursor.moveToNext()) {
        String currentQuantity = cursor.getString(quantityColumn);

            ammunition.add(currentQuantity);


    }
    return ammunition;

}
  public long insertAmmunition(String quantity) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues contentValues = new ContentValues();
    contentValues.put(AmmunitionEntry.COLUMN_TORPEDO_QUANTITY, quantity);

    long newRowId = db.insert(TABLE_NAME, null, contentValues);
    return newRowId;
}
public String insertOneAmmunition(String quantity, String id) {
    SQLiteDatabase db = this.getReadableDatabase();

    // New value for one column
    ContentValues values = new ContentValues();
    values.put(AmmunitionEntry.COLUMN_TORPEDO_QUANTITY, quantity);

    // Which row to update, based on the ID
    String selection = _ID + " LIKE ?";
    String[] selectionArgs = { id };

    try {
        int count = db.update(
                TABLE_NAME,
                values,
                selection,
                selectionArgs);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return id;
}
public String displayAmmo(String id) {
    String dbString = "";
    SQLiteDatabase db = getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_NAME + " WHERE "+_ID + " = '" + id +"'";
    //Cursor point to a location in your results
    Cursor c = db.rawQuery(query, null);
    //Move to the first row in your results
    c.moveToFirst();
    dbString = c.getString(c.getColumnIndex(AmmunitionEntry.COLUMN_TORPEDO_QUANTITY));

    return dbString;

}

public void deleteAll()
{
    SQLiteDatabase db = this.getWritableDatabase();
    // db.delete(TABLE_NAME,null,null);
    //db.execSQL("delete * from"+ TABLE_NAME);
    db.execSQL("delete from "+ TABLE_NAME);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

}

Here is where im trying to update some values

 switch (v.getId()) {
      case R.id.plusammunition1:

          valor = Integer.parseInt(torpedo1.getText().toString());
          valor++;
          if (valor >= 10) {
              torpedo1.setText("10");
          } else {
              torpedo1.setText(String.valueOf(valor));
          }
          String test =  mDbHelper.insertOneAmmunition(String.valueOf(valor), "51");
          Log.e("Value info 1", "Hey " + test);
          Log.e("INFO 1", "Hoy " + mDbHelper.displayDatabaseInfo().get(0));
          valor = 0;
          break;

This is the Contract just in case.

 public static final class AmmunitionEntry implements BaseColumns {
        public final static String TABLE_NAME = "Torpedo";
        public final static String _ID = BaseColumns._ID;
        public final static String COLUMN_TORPEDO_QUANTITY  = "quantity";


    }

I'm guessing that the problem with updating is because of the IDs


Solution

  • When you define a column like this:

    ID INTEGER PRIMARY KEY 
    

    then this column will be auto incremented, but if you delete any rows then the missing ids of the table may be refilled by insertions in the future.
    If you also add the keyword AUTOINCREMENT at the end of the definition like this:

    ID INTEGER PRIMARY KEY AUTOINCREMENT 
    

    this prevents the reuse of any deleted values of the id so you will have permanent gaps.
    You can find more here: SQLite Autoincrement