Error in Java database

Asked

Viewed 99 times

-1

Hello, I "created" an application with user registration and login, after the login screen that comes the problem, the system to log in is working, started to give problem after I created a screen with a Recyclerview to register some things in the database and they are displayed, when soon the application already error and closes. If anyone can help me I will be very grateful. Below is the screen code and error log.

Code of the class you add to the BD

public class Adicionar extends AppCompatActivity {

    private Senhas senhas;
    private View layout;
    private EditText origem;
    private EditText nome;
    private EditText email;
    private EditText senha;

    private Button salvar;

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

        senhas = getIntent().getParcelableExtra("key");

        layout = findViewById(R.id.ConsLayout);


        origem = findViewById(R.id.txtOrigemAd);
        nome = findViewById(R.id.txtNomeAd);
        email = findViewById(R.id.txtEmailAd);
        senha = findViewById(R.id.txtSenhaAd);

        origem.setText(senhas.getOrigem());
        nome.setText(senhas.getNome());
        email.setText(senhas.getEmail());
        senha.setText(senhas.getSenha());



        salvar = findViewById(R.id.btnSalvar);
        salvar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                senhas.setOrigem(origem.getText().toString());
                senhas.setNome(nome.getText().toString());
                senhas.setEmail(email.getText().toString());
                senhas.setSenha(senha.getText().toString());

                /*if (senhas.getNome().equals("")){
                    Toast.makeText(Adicionar.this, "É necessário um nome para salvar", Toast.LENGTH_SHORT).show();
                    return;
                }*/



                Intent i = new Intent();
                i.putExtra("key", senhas);
                setResult(RESULT_OK, i);
                finish();
            }
        });
    }

Comic book class

public class SqliteHelper extends SQLiteOpenHelper {


    /*BANCO DE DADOS*/

    //Nome do banco de dados
    public static final String BANCO_DADOS = "keyssword.db";

    //Versão do banco de dados
    public static final int VERSAO_BANCODADOS = 1;

    //Nome da tabela usuarios
    public static final String TABELA_USUARIOS = "usuarios";

    //********Campos da tabela de usuários********//

    //Coluna de ID, Chave primária
    public static final String ID = "id";

    //Coluna de nome de usuário
    public static final String NOME_USUARIO = "nomeusuario";

    //Coluna E-mail
    public static final String EMAIL = "email";

    //Coluna senha
    public static final String SENHA = "senha";


    //********Campos da tabela de senhas********//

    //Nome da tabela usuarios
    public static final String TABELA_LISTASENHAS = "listasenhas";

    //Coluna de ID, Chave primária
    public static final String IID = "id";

    //Coluna de nome de onde a senha é
    public static final String NOME_ORIGEM = "origem";

    //Coluna de nome de usuário
    public static final String NOME_USER = "usuario";

    //Coluna E-mail
    public static final String EMAIL_ = "email";

    //Coluna senha
    public static final String SENHA_ = "senha";

    //SQL para criar tabela de usuários
    public static final String SQL_TABELA_USUARIOS = " CREATE TABLE " + TABELA_USUARIOS
            + " ( " + ID + " INTEGER PRIMARY KEY, "
            + NOME_USUARIO + " TEXT, "
            + EMAIL + " TEXT, "
            + SENHA + " TEXT" + " ) ";


    //SQL para criar tabela de usuários
    public static final String SQL_TABELA_LISTASENHAS = " CREATE TABLE " + TABELA_LISTASENHAS
            + " ( " + IID + " INTEGER PRIMARY KEY, "
            + NOME_ORIGEM + " TEXT, "
            + NOME_USER + " TEXT, "
            + EMAIL_ + " TEXT, "
            + SENHA_ + " TEXT " + " ) ";


    public SqliteHelper(Context context) {
        super(context, BANCO_DADOS, null, VERSAO_BANCODADOS);

    }


    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase){

        //Cria uma tabela quando o onCreate é chamado
        sqLiteDatabase.execSQL(SQL_TABELA_USUARIOS);
        sqLiteDatabase.execSQL(SQL_TABELA_LISTASENHAS);
    }


    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int il) {

        //Descarta a tabela para criar uma nova,
        // se a versão do banco de dados for maior
        sqLiteDatabase.execSQL(" DROP TABLE IF EXISTS " + TABELA_USUARIOS);
        sqLiteDatabase.execSQL(" DROP TABLE IF EXISTS " + TABELA_LISTASENHAS);
    }


    public List<Senhas>getList(String order){
        List<Senhas> senhas = new ArrayList<>();

        Cursor cursorsenha = getReadableDatabase().rawQuery("SELECT * FROM " + TABELA_LISTASENHAS + " ORDER BY origem " +
                order + ";", null);

        while (cursorsenha.moveToFirst()){
            Senhas c = new Senhas();

            c.setId(cursorsenha.getLong(cursorsenha.getColumnIndex("id")));
            c.setOrigem(cursorsenha.getString(cursorsenha.getColumnIndex("origem")));
            c.setNome(cursorsenha.getString(cursorsenha.getColumnIndex("nome")));
            c.setEmail(cursorsenha.getString(cursorsenha.getColumnIndex("email")));
            c.setSenha(cursorsenha.getString(cursorsenha.getColumnIndex("senha")));

            senhas.add(c);
        }

        cursorsenha.close();

        return senhas;

    }

    public void inserirSenha(Senhas c){
        ContentValues values = new ContentValues();

        values.put("origem", c.getOrigem());
        values.put("nome", c.getNome());
        values.put("email", c.getEmail());
        values.put("senha", c.getSenha());

        getWritableDatabase().insert(TABELA_LISTASENHAS, null, values);
    }

    public void alteraSenha(Senhas c){
        ContentValues valuessenha = new ContentValues();

        valuessenha.put("id", c.getId());
        valuessenha.put("origem", c.getOrigem());
        valuessenha.put("nome", c.getNome());
        valuessenha.put("email", c.getEmail());
        valuessenha.put("senha", c.getSenha());

        String[] idParaSerAlterado = {c.getId().toString()};
        getWritableDatabase().update(TABELA_LISTASENHAS, valuessenha, "id=?", idParaSerAlterado);
    }


    public void apagarSenha(Senhas c){
        SQLiteDatabase db = getWritableDatabase();
        String[] args = {c.getId().toString()};
        db.delete(TABELA_LISTASENHAS, "id=?", args);
    }



    public Usuarios ValidaUsuario(Usuarios usuario) {
        SQLiteDatabase db = this.getReadableDatabase();
        //Seleciona a tabela
        Cursor cursor = db.query(/*Seleciona a tabela*/ TABELA_USUARIOS,
                new String[]{ID, NOME_USUARIO, EMAIL, SENHA},/*Seleciona as colunas para a query*/
                EMAIL + "=?",
                new String[]{usuario.email},
                null,null,null);

        if (cursor != null && cursor.moveToFirst() && cursor.getCount()>0){
            Usuarios user = new Usuarios(cursor.getString(0),
                    cursor.getString(1), cursor.getString(2),
                    cursor.getString(3));

            if (usuario.senha.equalsIgnoreCase(user.senha)){
                return user;
            }
        }
        return null;
    }


    //Esse método é responsavel por adicionar usuários à tabela
    public void addUser(Usuarios usuario) {

        //Abre o banco de dados para gravação
        SQLiteDatabase db = this.getWritableDatabase();

        //Cria os valores de conteúdo para inserir
        ContentValues inserir = new ContentValues();

        //Coloca o nome de usuário em values
        inserir.put(NOME_USUARIO, usuario.nomeUsuario);

        //Coloca o emial em values
        inserir.put(EMAIL, usuario.email);

        //Coloca a senha em values
        inserir.put(SENHA, usuario.senha);

        //Inserir linha
        long todo_id = db.insert(TABELA_USUARIOS, null, inserir);
    }



    public boolean ValidaEmail(String email) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABELA_USUARIOS,
                new String[]{ID, NOME_USUARIO,EMAIL,SENHA},
                EMAIL + "+?",
                new String[] {email},
                null, null, null);

        if (cursor != null && cursor.moveToFirst() && cursor.getCount()>0){
            return true;
        }

        return false;
    }

Recyclerview layout class

public class Lista extends AppCompatActivity {

    private SqliteHelper helper;
    private RecyclerView SenhasRecy;
    private Adapter adapter;
    private List<Senhas> listaSenhas;
    private final int REQUEST_NEW = 1;
    private final int REQUEST_ALTER = 2;
    private String order = "ASC";

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

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(Lista.this, Adicionar.class);
                i.putExtra("key", new Senhas());
                startActivityForResult(i, REQUEST_NEW);
            }
        });

        helper = new SqliteHelper(this);
        listaSenhas = helper.getList(order);
        SenhasRecy = findViewById(R.id.SenhasRecy);
        SenhasRecy.setHasFixedSize(true);
        LinearLayoutManager linear = new LinearLayoutManager(this);
        linear.setOrientation(LinearLayoutManager.HORIZONTAL);
        SenhasRecy.setLayoutManager(linear);
        adapter = new Adapter(listaSenhas);
        SenhasRecy.setAdapter(adapter);

        SenhasRecy.addOnItemTouchListener(new RecyclerItem(getApplicationContext(),
            new RecyclerItem.OnItemClickListener(){
                @Override
                    public void onItemClick(View view, int position){
                        abrirOpcoes(listaSenhas.get(position));
            }
        }));


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == REQUEST_NEW && resultCode == RESULT_OK){
            Senhas Senhas = data.getParcelableExtra("key");
            helper.inserirSenha(Senhas);
            listaSenhas = helper.getList(order);
            adapter = new Adapter(listaSenhas);
            SenhasRecy.setAdapter(adapter);
        } else if(requestCode == REQUEST_ALTER && resultCode == RESULT_OK){
            Senhas Senhas = data.getParcelableExtra("key");
            helper.alteraSenha(Senhas);
            listaSenhas = helper.getList(order);
            adapter = new Adapter(listaSenhas);
            SenhasRecy.setAdapter(adapter);
        }
    }


    private void abrirOpcoes(final Senhas senhas){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(senhas.getNome());
        builder.setItems(new CharSequence[]{"Editar", "Excluir"},
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        switch (i){
                            case 0:
                                Intent intent1 = new Intent(Lista.this, Adicionar.class);
                                intent1.putExtra("contato", senhas);
                                startActivityForResult(intent1, REQUEST_ALTER);
                                break;
                            case 1:
                                listaSenhas.remove(senhas);
                                helper.apagarSenha(senhas);
                                adapter.notifyDataSetChanged();
                                break;
                        }
                    }
                });
        builder.create().show();
    }

    /*@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.order_az) {
            order = "ASC";
        } else if(id == R.id.order_za){
            order = "DESC";
        }

        listaSenhas = helper.getList(order);
        adapter = new Adapter(listaSenhas);
        SenhasRecy.setAdapter(adapter);

        return true;
    }*/

}

Error log

QLiteLog: (1) table listasenhas has no column named nome
E/SQLiteDatabase: Error inserting origem= senha= nome= email=teste
    android.database.sqlite.SQLiteException: table listasenhas has no column named nome (code 1): , while compiling: INSERT INTO listasenhas(origem,senha,nome,email) VALUES (?,?,?,?)
        at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
        at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
        at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
        at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
        at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
        at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
        at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1472)
        at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1343)
        at com.gnd.keyssword.SQl.SqliteHelper.inserirSenha(SqliteHelper.java:137)
        at com.gnd.keyssword.Lista.onActivityResult(Lista.java:80)
        at android.app.Activity.dispatchActivityResult(Activity.java:7235)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4320)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:4367)
        at android.app.ActivityThread.-wrap19(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1649)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

Log of the new error

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.gnd.keyssword, PID: 4805
    java.lang.OutOfMemoryError: Failed to allocate a 55380616 byte allocation with 6291456 free bytes and 46MB until OOM, max allowed footprint 561962912, growth limit 603979776
        at java.util.Arrays.copyOf(Arrays.java:3139)
        at java.util.Arrays.copyOf(Arrays.java:3109)
        at java.util.ArrayList.grow(ArrayList.java:275)
        at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:249)
        at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:241)
        at java.util.ArrayList.add(ArrayList.java:467)
        at com.gnd.keyssword.SQl.SqliteHelper.getList(SqliteHelper.java:120)
        at com.gnd.keyssword.Lista.onActivityResult(Lista.java:81)
        at android.app.Activity.dispatchActivityResult(Activity.java:7235)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4320)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:4367)
        at android.app.ActivityThread.-wrap19(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1649)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
  • 4

    I think the error is pretty clear. You are trying to insert into a column that does not exist. More specifically, insert into the column nome, which in your script has been declared as NOME_USER = "usuario";. You forgot to use the constants in the methods inserirSenha and alteraSenha. ;)

  • I’m still a beginner in comics, could you be more specific please?

1 answer

1


As the error says: You are trying to insert a value in a column that does not exist in the database, that is, you are trying to insert a value in the column "name", column not existing in your table listpasswords of the database.

In the methods insert No and change No, try to replace "name" with "user" in this way:

  public void inserirSenha(Senhas c){
        ContentValues values = new ContentValues();

        values.put("origem", c.getOrigem());
        values.put("usuario", c.getNome());
        values.put("email", c.getEmail());
        values.put("senha", c.getSenha());

        getWritableDatabase().insert(TABELA_LISTASENHAS, null, values);
    }

    public void alteraSenha(Senhas c){
        ContentValues valuessenha = new ContentValues();

        valuessenha.put("id", c.getId());
        valuessenha.put("origem", c.getOrigem());
        valuessenha.put("usuario", c.getNome());
        valuessenha.put("email", c.getEmail());
        valuessenha.put("senha", c.getSenha());

        String[] idParaSerAlterado = {c.getId().toString()};
        getWritableDatabase().update(TABELA_LISTASENHAS, valuessenha, "id=?", idParaSerAlterado);
    }

OR

    public void inserirSenha(Senhas c){
        ContentValues values = new ContentValues();

        values.put(NOME_ORIGEM, c.getOrigem());
        values.put(NOME_USER, c.getNome());
        values.put(EMAIL_, c.getEmail());
        values.put(SENHA_, c.getSenha());

        getWritableDatabase().insert(TABELA_LISTASENHAS, null, values);
    }

    public void alteraSenha(Senhas c){
        ContentValues valuessenha = new ContentValues();

        valuessenha.put(IID , c.getId());
        valuessenha.put(NOME_ORIGEM , c.getOrigem());
        valuessenha.put(NOME_USER , c.getNome());
        valuessenha.put(EMAIL_ , c.getEmail());
        valuessenha.put(SENHA_ , c.getSenha());

        String[] idParaSerAlterado = {c.getId().toString()};
        getWritableDatabase().update(TABELA_LISTASENHAS, valuessenha, "id=?", idParaSerAlterado);
    }
  • Now you’re returning another mistake

  • I already added the new log

  • I have uninstalled and installed again three times and already tested in another emulator.

  • Take a look at this material https://stackoverflow.com/questions/32244851/androidjava-lang-outofmemoryerror-failed-to-allocate-a-23970828-byte-allocatio

  • I’ll look yes, thank you.

  • I took a look, I disabled all images of my project and the error continues

  • Explain a little more about the problem. When it happens, etc. If possible post the full log here.

  • It’s a logging and logging app, when logging in is redirected to a screen where it has a Recyclerview, and a floating button to add new record, this button redirects to another screen where the logging containing Source is done, name, email and password, when you press the button to save this information in the database is what gives the problem, the screen becomes black and then the app stops and this error. The whole log does not have as it exceeds the character limit.

  • What method does this save button call? This method is in the question ?

  • Ta in the code of the "Add class code in BD" is btnSalvar.

Show 5 more comments

Browser other questions tagged

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