Get id of the last record inserted in the bank

0

I would like to know if you have how to insert a record in the database and already return the id of this record in android sqlite

I use this method to insert

public boolean insertH(HistoricoObjeto historico) {

    /* Mapa com a coluna e os valores de cada coluna. */
    ContentValues values = new ContentValues();
    values.put("datahora", historico.getDatahora());
    values.put("mensagem", historico.getMensagem());


    /* Executa um insert no banco de dados usando o mapa de valores. */
    /* Retorna -1 caso ocorra algum erro no INSERT. */
    long retorno = this.banco.insert("historico", null, values);

    if(retorno != -1)
        return true;
    else
        return false;
}
    
asked by anonymous 09.12.2014 / 19:49

3 answers

1

Try this:

SELECT * 
FROM    TABLE
WHERE   ID = (SELECT MAX(ID)  FROM TABLE);
    
07.07.2015 / 05:14
0
public long insertH(HistoricoObjeto historico) {

/* Mapa com a coluna e os valores de cada coluna. */
ContentValues values = new ContentValues();
values.put("datahora", historico.getDatahora());
values.put("mensagem", historico.getMensagem());


/* Executa um insert no banco de dados usando o mapa de valores. */
/* Retorna -1 caso ocorra algum erro no INSERT. */
long retorno = this.banco.insert("historico", null, values);
return retorno;
}

This return is with the id in the last entered history

    
11.12.2014 / 19:09
0

Well, in fact, the SQLiteDatabase class has its own insertion method that returns the ID of the newly created row. I think this is the best way to get the new ID . You can check your documentation:

link

    
10.12.2014 / 12:21