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

0

I'm having problems with my code, could they help me. Follow the error below and after the codes. But for simplicity, I have a home screen and let me go to another to register and then I can go to another to list in the ListView, but at this point of listing 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 entries 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);
}
}

NORMAL LAUNCH CLASS.

SQLHELPER CLASS:

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);
}
}

CLASS DEFINITION:

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 = ",";
}

CLASS CONTRACT:

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";
}

}

CLASS DAO - AND THIS IS HERE 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;
}
}
    
asked by anonymous 23.11.2016 / 04:21

1 answer

1

The "_id" field is not technically required ( quoting documentation ), but if you use Cursor inheriting from CursorAdapter , you must have a "_id" field in your table.

You can use the method ".

    
23.11.2016 / 10:12