1

this is my error in cosole:

Caused by: android.database.sqlite.SQLiteException: table contato has no column named cpf (code 1): , while compiling: insert into contato (nome, cpf, idade, telefone, email) VALUES (?,?,?,?,?)

This is my DBhelper script:

package bonato.myapplication;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Bonato on 29/06/2017.
 */
public class DBHelper {

    private static final String DATABASE_NAME = "bancodedados.db";
    private static final int DATABASE_VERSION = 2;
    private static final String TABLE_NAME = "contato";

    private Context context;
    private SQLiteDatabase db;

    private SQLiteStatement insertStnt;
    private static final String INSERT = "insert into " + TABLE_NAME + " (nome, cpf, idade, telefone, email) VALUES (?,?,?,?,?)";

    public DBHelper(Context context) {
        this.context = context;
        OpenHelper openHelper = new OpenHelper(this.context);
        this.db = openHelper.getWritableDatabase();
        this.insertStnt = this.db.compileStatement(INSERT);

    }

    // OBJETIVO.......:Ordem nas colunas
    public long insert(String nome, String cpf, String idade, String telefone, String email) {
        this.insertStnt.bindString(1, nome);
        this.insertStnt.bindString(2, cpf);
        this.insertStnt.bindString(3, idade);
        this.insertStnt.bindString(4, telefone);
        this.insertStnt.bindString(5, email);

        return this.insertStnt.executeInsert();
    }

    public void deleteAll() {
        this.db.delete(TABLE_NAME, null, null);
    }


    // OBJETIVO.......: Tratar exceções
    public List<Contato> queryGetAll() {
        List<Contato> list = new ArrayList<Contato>();
        // OBJETIVO.......: Retornar uma lista de objetos contato
        try {
            Cursor cursor = this.db.query(TABLE_NAME, new String[]{"nome", "cpf", "idade", "telefone", "email"},
                    null, null, null, null, null, null);
            int nregistros = cursor.getCount();
            if (nregistros != 0) {
                cursor.moveToFirst();
                do {
                    Contato contato = new Contato(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4));
                    list.add(contato);
                } while (cursor.moveToNext());

                if (cursor != null && !cursor.isClosed())
                    cursor.close();
                return list;

            } else
                return null;

        } catch (Exception erro) {
            return null;
        }

    }

    private static class OpenHelper extends SQLiteOpenHelper {
        OpenHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        public void onCreate(SQLiteDatabase db) {
            String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (id INTEGER PRIMARY KEY AUTO INCREMENT, nome TEXT, cpf TEXT, idade TEXT, telefone TEXT, email TEXT);";
            db.execSQL(sql);
        }

        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
            onCreate(db);

        }
    }
}

package bonato.myapplication;

/**
 * Created by Bonato on 29/06/2017.
 */
public class Contato {

    // OBJETIVO.......: Atributos

    private String nome;
    private String cpf;
    private String idade;
    private String telefone;
    private String email;


    // OBJETIVO.......: Construtor

    public Contato(String nome, String cpf, String idade, String telefone, String email) {
        this.nome = nome;
        this.cpf = cpf;
        this.idade = idade;
        this.telefone = telefone;
        this.email = email;

    }

    // OBJETIVO.......: Informacoes

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getCpf() {
        return cpf;
    }

    public void setCpf(String cpf) {
        this.cpf = cpf;
    }

    public String getIdade() {
        return idade;
    }

    public void setIdade(String idade) {
        this.idade = idade;
    }

    public String getTelefone() {
        return telefone;
    }

    public void setTelefone(String telefone) {
        this.telefone = telefone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }


}

package bonato.myapplication;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.util.List;

public class SecondActivity extends AppCompatActivity {

    // OBJETIVO.......: Ao clicar no botao voltara para a tela inicial e inserir dados no banco de dados

    private DBHelper dh;
    EditText etNome, etCpf, etIdade, etTelefone, etEmail;
    Button btInserir, btListar;


    Button btVoltar;

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

        this.dh = new DBHelper(this);
        etNome = (EditText) findViewById(R.id.etnome);
        etCpf = (EditText) findViewById(R.id.etcpf);
        etIdade = (EditText) findViewById(R.id.etidade);
        etTelefone = (EditText) findViewById(R.id.ettelefone);
        etEmail = (EditText) findViewById(R.id.etemail);

        btInserir = (Button) findViewById(R.id.btinserir);
        btListar = (Button) findViewById(R.id.btlistar);

        // OBJETIVO.......: Metodo que vai inserir no banco de dados
        btInserir.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (etNome.getText().length()>0 && etCpf.getText().length()>0 && etIdade.getText().length()>0 && etTelefone.getText().length()>0 && etEmail.getText().length()>0){
                    dh.insert(etNome.getText().toString(),etCpf.getText().toString(), etIdade.getText().toString(), etTelefone.getText().toString(),etEmail.getText().toString());
                    AlertDialog.Builder adb = new AlertDialog.Builder(SecondActivity.this);
                    adb.setTitle("Sucesso!");
                    adb.setMessage("Cadastro Realizado!");
                    adb.show();

                    etNome.setText("");
                    etCpf.setText("");
                    etIdade.setText("");
                    etTelefone.setText("");
                    etEmail.setText("");
                }else{

                    AlertDialog.Builder adb = new AlertDialog.Builder(SecondActivity.this);
                    adb.setTitle("Erro!");
                    adb.setMessage("Todos os campos devem ser preenchidos!");
                    adb.show();

                    etNome.setText("");
                    etCpf.setText("");
                    etIdade.setText("");
                    etTelefone.setText("");
                    etEmail.setText("");


                }

            }
        });
        // OBJETIVO.......: MOSTRA SE EXISTEM REGISTROS OU NAO, SE HOUVER DEVE LISTA-LOS
        btListar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<Contato> contatos = dh.queryGetAll();
                if (contatos == null){
                    AlertDialog.Builder adb = new AlertDialog.Builder(SecondActivity.this);
                    adb.setTitle("Mensagem");
                    adb.setMessage("Nao ha registros cadastrados!");
                    adb.show();
                    return;
                }
                for (int i =0; i<contatos.size(); i++){
                    Contato contato = (Contato) contatos.get(i);
                    AlertDialog.Builder adb = new AlertDialog.Builder(SecondActivity.this);
                    adb.setTitle("Registro" + i);
                    adb.setMessage("Nome: " +contato.getNome()+"\nCPF: " + contato.getCpf()+"\nIdade: " + contato.getIdade()+"\nTelefone: " +contato.getTelefone()+"\nE-mail: "+contato.getEmail());
                    adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    adb.show();

                }
            }
        });

        btVoltar = (Button) findViewById(R.id.btVoltar);
        btVoltar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                voltarParaPrimeiraTela();
            }
        });
    }

    void voltarParaPrimeiraTela(){

        Intent intent = new Intent();
        intent.setClass(SecondActivity.this, MainActivity.class);
        startActivity(intent);
        finish();

    }
}

I need help finding the error, I have no idea what it can be, because the "cpf" is already there.

3
  • Show the script which creates the table Commented Jun 29, 2017 at 20:12
  • What is the DB structure? Commented Jun 29, 2017 at 20:24
  • Ready, edit the post with more information, I'm still learning, sorry. Commented Jun 29, 2017 at 20:29

1 Answer 1

2

No, "cpf" is not already there. There is no field called "cpf" in the table "contato" in database "bancodedados.db".

That's because the onUpgrade() method is not invoked, so the table is never dropped and never re-created, so you have some old version of the table which does not contain a "cpf" field.

If you believe it does, then prove it.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I deleted all existing dbs and restarted the application, now it worked perfectly!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.