no such column _id (code 1) while compiling - SQL

Asked

Viewed 812 times

0

I’m having trouble with my code, could help me. Follow the error below and soon after, the codes. But to simplify, I have a home screen and let me go to another to register and then I can go to another to list in Listview, but at this point to list that happens the problem.

11-23 02:39:40.814 3676-3676/br.com.tatuini.unilasalle.gerenciadorfinanceiro E/AndroidRuntime: FATAL EXCEPTION: main
Process: br.com.tatuini.unilasalle.gerenciadorfinanceiro, PID: 3676
java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.tatuini.unilasalle.gerenciadorfinanceiro/br.com.tatuini.unilasalle.gerenciadorfinanceiro.ListaItemActivity}: android.database.sqlite.SQLiteException: no such column: _id (code 1): , while compiling: SELECT _id, descricao, valor, data_lancamento FROM lancamento ORDER BY descricao ASC
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
   at android.app.ActivityThread.-wrap11(ActivityThread.java)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:148)
   at android.app.ActivityThread.main(ActivityThread.java:5417)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.database.sqlite.SQLiteException: no such column: _id (code 1): , while compiling: SELECT _id, descricao, valor, data_lancamento FROM lancamento ORDER BY descricao ASC
   at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
   at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
   at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
   at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
   at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
   at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
   at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
   at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
   at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1163)
   at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1034)
   at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1202)
   at br.com.tatuini.unilasalle.gerenciadorfinanceiro.model.dataBase.persistencia.LancamentoDAO.selectAll(LancamentoDAO.java:57)
   at br.com.tatuini.unilasalle.gerenciadorfinanceiro.ListaItemActivity.onCreate(ListaItemActivity.java:40)
   at android.app.Activity.performCreate(Activity.java:6237)
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
   at android.app.ActivityThread.-wrap11(ActivityThread.java) 
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
   at android.os.Handler.dispatchMessage(Handler.java:102) 
   at android.os.Looper.loop(Looper.java:148) 
   at android.app.ActivityThread.main(ActivityThread.java:5417) 
   at java.lang.reflect.Method.invoke(Native Method) 
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

Initial class, where we have the menu of registration and listing:

public class InicialActivity extends AppCompatActivity {
private TextView txt_mes;
private TextView saldoAtual;
Calendar calendar;

private static final int COD_RECEITA = 1;
private static final int COD_DESPESA = 2;
private static final int COD_LIST = 3;
private static final int COD_TOP_FIVE = 4;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_inicial);

    // Jogando o mês específico para a tela incial
    Date data = new Date();
    GregorianCalendar dataCal = new GregorianCalendar();
    dataCal.setTime(data);
    int mes = dataCal.get(Calendar.MONTH);

    DateFormatSymbols df = new DateFormatSymbols(new Locale("PT", "br"));
    String[] mesBR = df.getMonths();

    txt_mes = (TextView) findViewById(R.id.txt_mes);
    saldoAtual = (TextView) findViewById(R.id.saldoAtual);
    DecimalFormat fd = new DecimalFormat("0.00");

    calendar=Calendar.getInstance();
    calendar.setTime(new Date());
    Saldo geral = new Saldo();
    saldoAtual.setText("0,00");


    txt_mes.setText(String.valueOf(mesBR[mes]).toUpperCase());
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_inicial, menu);
    return super.onCreateOptionsMenu(menu);
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()){
        case R.id.mni_receita:
            Intent it_receita = new Intent(this, Cad_Receita_Activity.class);
            startActivity(it_receita);
            break;
        case R.id.mni_despesa:
            Intent it_despesa_receita = new Intent(this, Cad_Despesa_Activity.class);
            startActivity(it_despesa_receita);
            break;
        case R.id.mni_lista:
            Intent intent = new Intent(this, ListaItemActivity.class);
            startActivity(intent);
            break;
        case R.id.mni_topFive:
            Intent intent_tf = new Intent(this, Top_Five_Activity.class);
            startActivity(intent_tf);
            break;
    }
    return super.onOptionsItemSelected(item);
}
}

STANDARD LAUNCH CLASS.

CLASS SQLHELPER:

public class LancamentoSqlHelper extends SQLiteOpenHelper {

private static final String SQL_CREATE_ENTRIES =
        "CREATE TABLE " + ClasseContrato.Lancamento.TABLE_NAME + " (" +
                ClasseContrato.Lancamento.COLUMN_ID + " INTEGER PRIMARY KEY," +
                ClasseContrato.Lancamento.COLUMN_NAME_DESCRICAO + DefinicaoDb.TEXT_TYPE + DefinicaoDb.COMMA_SEP +
                ClasseContrato.Lancamento.COLUMN_NAME_VALOR + DefinicaoDb.INTEGER_TYPE + DefinicaoDb.COMMA_SEP +
                ClasseContrato.Lancamento.COLUMN_NAME_PARCELA + DefinicaoDb.INTEGER_TYPE + DefinicaoDb.COMMA_SEP +
                ClasseContrato.Lancamento.COLUMN_NAME_DATA_CRIA + DefinicaoDb.DATETIME_TYPE + DefinicaoDb.COMMA_SEP +
                ClasseContrato.Lancamento.COLUMN_NAME_DATA_LANCA + DefinicaoDb.DATETIME_TYPE + DefinicaoDb.COMMA_SEP +
                ClasseContrato.Lancamento.COLUMN_NAME_CATEGORIA + DefinicaoDb.TEXT_TYPE + DefinicaoDb.COMMA_SEP +
                ClasseContrato.Lancamento.COLUMN_NAME_TIPO_LANCAMENTO + DefinicaoDb.TEXT_TYPE + DefinicaoDb.COMMA_SEP +
                ClasseContrato.Lancamento.COLUMN_NAME_VALOR_PAGAMENTO  + DefinicaoDb.TEXT_TYPE + DefinicaoDb.COMMA_SEP +
                ClasseContrato.Lancamento.COLUMN_NAME_VALOR_RECEBIMENTO  + DefinicaoDb.TEXT_TYPE + " )";

private static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + ClasseContrato.Lancamento.TABLE_NAME;

public LancamentoSqlHelper(Context context){
    super(context, DefinicaoDb.DATABASE_NAME, null, DefinicaoDb.DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase sql_dataBase) {
    sql_dataBase.execSQL(SQL_CREATE_ENTRIES);
}

@Override
public void onUpgrade(SQLiteDatabase sql_dataBase, int oldVersion, int newVersion) {
    sql_dataBase.execSQL(SQL_DELETE_ENTRIES);
    onCreate(sql_dataBase);
}
}

DEFINITION CLASS:

public final class DefinicaoDb {
//Incrementar este número quando modificar o schema
public static final int DATABASE_VERSION = 6;
public static final String DATABASE_NAME = "GERENCIADOR.db";

public static final String TEXT_TYPE = " TEXT";
public static final String INTEGER_TYPE = " INTEGER";
public static final String REAL_TYPE = " REAL";
public static final String DATETIME_TYPE = " DATETIME";
public static final String COMMA_SEP = ",";
}

CONTRACT CLASS:

public class ClasseContrato {
//Evita intanciar um objeto da classe
private ClasseContrato(){  }

//Criação da inner class Aluno definindo a tabela aluno
public static class Lancamento implements BaseColumns {
    public static final String TABLE_NAME="lancamento";
    public static final String COLUMN_ID="id";
    public static final String COLUMN_NAME_DESCRICAO="descricao";
    public static final String COLUMN_NAME_VALOR="valor";
    public static final String COLUMN_NAME_PARCELA="parcela";
    public static final String COLUMN_NAME_DATA_CRIA="data_criacao";
    public static final String COLUMN_NAME_DATA_LANCA="data_lancamento";
    public static final String COLUMN_NAME_CATEGORIA="categoria";
    public static final String COLUMN_NAME_TIPO_LANCAMENTO="tipo_lancamento";
    public static final String COLUMN_NAME_VALOR_PAGAMENTO="valor_pagamento";
    public static final String COLUMN_NAME_VALOR_RECEBIMENTO="valor_recebimento";
}

}

DAO CLASS - AND THIS IS WHERE THE ERROR IS GENERATED...

public class LancamentoDAO {

public void inserir(Lancamento lancamento, Context context){
    LancamentoSqlHelper lancamentoSqlHelper = new LancamentoSqlHelper(context);
    SQLiteDatabase db = lancamentoSqlHelper.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(ClasseContrato.Lancamento.COLUMN_NAME_DESCRICAO, lancamento.getDescribe());
    values.put(ClasseContrato.Lancamento.COLUMN_NAME_VALOR, lancamento.getValor());
    values.put(ClasseContrato.Lancamento.COLUMN_NAME_PARCELA, lancamento.getParcela());
    values.put(ClasseContrato.Lancamento.COLUMN_NAME_DATA_CRIA , lancamento.getDatacria().getTime());
    values.put(ClasseContrato.Lancamento.COLUMN_NAME_DATA_LANCA , lancamento.getDatalanca().getTime());
    values.put(ClasseContrato.Lancamento.COLUMN_NAME_CATEGORIA , lancamento.getCategoria());
    values.put(ClasseContrato.Lancamento.COLUMN_NAME_TIPO_LANCAMENTO , lancamento.getTipo());
    values.put(ClasseContrato.Lancamento.COLUMN_NAME_VALOR_PAGAMENTO , lancamento.getVarPagamento());
    values.put(ClasseContrato.Lancamento.COLUMN_NAME_VALOR_RECEBIMENTO , lancamento.getVarRecebimeto());

    Long id = db.insert(ClasseContrato.Lancamento.TABLE_NAME, null, values);
}

public ArrayList<Lancamento> selectAll(Context context){
    // Obtem a referencia do BD em modo leitura
    LancamentoSqlHelper lancamentoSqlHelper = new LancamentoSqlHelper(context);
    SQLiteDatabase db = lancamentoSqlHelper.getReadableDatabase();

    // Define quais colunas devem ser lidas do BD.
    String[] projection = {
            ClasseContrato.Lancamento._ID,
            ClasseContrato.Lancamento.COLUMN_NAME_DESCRICAO,
            ClasseContrato.Lancamento.COLUMN_NAME_VALOR,
            ClasseContrato.Lancamento.COLUMN_NAME_DATA_LANCA
    };

    ArrayList<Lancamento> lancamentos = new ArrayList<>();

    // Ordenação da consulta
    String sortOrder = ClasseContrato.Lancamento.COLUMN_NAME_DESCRICAO + " ASC";

    //Montagem da Consulta
    Cursor cursorLancamento = db.query(
            ClasseContrato.Lancamento.TABLE_NAME,     // Tabela
            projection,                               // Colunas a serem lidas
            null,                                     // Clausula Where
            null,                                     // Valores da clausula where
            null,                                     // Definição de grupos
            null,                                     // Definição de filtros de grupo
            sortOrder                                 // Ordenação
    );

    if (cursorLancamento.moveToFirst()) {
        while (cursorLancamento.isAfterLast() == false) {
            long itemId = cursorLancamento.getLong(cursorLancamento.getColumnIndexOrThrow(ClasseContrato.Lancamento.COLUMN_ID));
            String descriao = cursorLancamento.getString(cursorLancamento.getColumnIndexOrThrow(ClasseContrato.Lancamento.COLUMN_NAME_DESCRICAO));
            Float valor = cursorLancamento.getFloat(cursorLancamento.getColumnIndexOrThrow(ClasseContrato.Lancamento.COLUMN_NAME_VALOR));
            Date dataLanca = new Date(cursorLancamento.getLong(cursorLancamento.getColumnIndexOrThrow(ClasseContrato.Lancamento.COLUMN_NAME_DATA_LANCA)));

            lancamentos.add(new Lancamento(itemId, descriao, valor, dataLanca));
            cursorLancamento.moveToNext();
        }
    }
    cursorLancamento.close();
    return lancamentos;
}

public void deleteAll(Context context) {
    // Obtem a referencia do BD em modo escrita
    LancamentoSqlHelper lancamentoSqlHelper = new LancamentoSqlHelper(context);
    SQLiteDatabase db = lancamentoSqlHelper.getWritableDatabase();

    //Exclui elementos do BD
    long id = db.delete(ClasseContrato.Lancamento.TABLE_NAME, null, null);
}

public Lancamento getById(Context context, Lancamento lancamento) {
    // Obtem a referencia do BD em modo leitura
    LancamentoSqlHelper lancamentoSqlHelper = new LancamentoSqlHelper(context);
    SQLiteDatabase db = lancamentoSqlHelper.getReadableDatabase();

    // Define quais colunas devem ser lidas do BD.
    String[] projection = {
            ClasseContrato.Lancamento._ID,
            ClasseContrato.Lancamento.COLUMN_NAME_DESCRICAO,
            ClasseContrato.Lancamento.COLUMN_NAME_VALOR,
            ClasseContrato.Lancamento.COLUMN_NAME_DATA_LANCA
    };

    Lancamento lancamentoBd = null;

    //Filtra pelo ID, usando a clausula WHERE
    String selection = ClasseContrato.Lancamento._ID + " = ?";
    String[] selectionArgs = { String.valueOf(lancamento.getId()) };

    // Ordenação da consulta
    String sortOrder = ClasseContrato.Lancamento.COLUMN_NAME_DESCRICAO + " ASC";

    //Montagem da Consulta
    Cursor cursorLancamento = db.query(
            ClasseContrato.Lancamento.TABLE_NAME,         // Tabela
            projection,                               // Colunas a serem lidas
            selection,                                // Clausula Where
            selectionArgs,                            // Valores da clausula where
            null,                                     // Definição de grupos
            null,                                     // Definição de filtros de grupo
            sortOrder                                 // Ordenação
    );

    if (cursorLancamento.moveToFirst()) {
            long itemId = cursorLancamento.getLong(cursorLancamento.getColumnIndexOrThrow(ClasseContrato.Lancamento.COLUMN_ID));
            String descriao = cursorLancamento.getString(cursorLancamento.getColumnIndexOrThrow(ClasseContrato.Lancamento.COLUMN_NAME_DESCRICAO));
            Float valor = cursorLancamento.getFloat(cursorLancamento.getColumnIndexOrThrow(ClasseContrato.Lancamento.COLUMN_NAME_VALOR));
            Date dataLanca = new Date(cursorLancamento.getLong(cursorLancamento.getColumnIndexOrThrow(ClasseContrato.Lancamento.COLUMN_NAME_DATA_LANCA)));

            lancamentoBd = new Lancamento(itemId, descriao, valor, dataLanca);
    }
    cursorLancamento.close();
    return lancamentoBd;
}
}
  • Registration class: The registration class has this fear: Calendar calendar calendar = Calendar.getInstance(); Date data = new java.text.Simpledateformat("dd/MM/yyyy"). parse(validationDataLanca); calendario.setTime(data); calendario.add(Calendar.MONTH, Parcel); New release = new Release(validationDescription,validationValue,Parcel, new Date(), calendario.getTime(),validationCategory, validationType,validationPackage, validationReception); Lancamentoday lancamentoDAO = new Lancamentodao(); lancamentoDAO.insert(new, this);

1 answer

1


The field "_id" is not technically mandatory (documentation citing), however, if you use the Cursor who inherits from CursorAdapter, it will be necessary to have a field "_id" on your table.

You can use the method ".rawQuery(sql, [selectionArgs = default null])" if you do not want to implement _id in your table that will suit you as ". query".

  • I used this ghastly calling to play the launch on Listview... Would you redo this method . rawQuery? I’m new to database and I started learning this week.

  • Taking advantage, if you can help me... I have to do some methods later to get values of each release and deal with the dates. How to work with these freaks, I get confused because mixed with DB. Is it a correct way to do like, Arraylist list = Lancamentodao.insert(this); ?? Excuse anything.

Browser other questions tagged

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