I’m not getting the inclusion of the bank

Asked

Viewed 70 times

-1

I’m studying android and I’m doing the bank’s CRUD... only I made the code and put to run it does not work. It has the layout with a field to write what you want to save and on the side a button, below it has the listview to show the saved items of the bank... When I click the button it does not happen anything, nor the Toast I put to inform if you need to type something or if it was saved successfully. I reviewed the code and found nothing, someone could help me?

Mainactivity.java

package com.nathan.listanewn;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {

    private Button adicionar;
    private EditText caixa;
    private ListView lista;
    private SQLiteDatabase banco;


    private ArrayAdapter<String> itensAdptador;
    private ArrayList<String> itens;
    private ArrayList<Integer> ids;


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

        try{
            adicionar = (Button) findViewById(R.id.btnAdds);
            caixa = (EditText) findViewById(R.id.edtPeca);
            lista = (ListView) findViewById(R.id.listAdd);

            //Criando banco
            banco = openOrCreateDatabase("apptarefas", MODE_PRIVATE,null);

            //tabela tarefas
            banco.execSQL("CREATE TABLE IF NOT EXISTS tarefas(id INTEGER PRIMARY KEY AUTOINCREMENT, tarefa VARCHAR)");


            //evento de click
            adicionar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String textodigitado = caixa.getText().toString();
                    salvarTarefa(textodigitado);
                }
            });


            //habilitando o toque longo para exclusao
            lista.setLongClickable(true);
            lista.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                    removeTarefa( ids.get(position));
                    return false;
                }
            });


            //recuperar tarefas
            recuperarTarefa();

        }catch (Exception e){
            e.printStackTrace();
        }
    }


    private void salvarTarefa(String texto){
        try{
            if(texto.equals(" ")){
                Toast.makeText(getApplicationContext(), "O campo não pode estar vazio", Toast.LENGTH_SHORT).show();
            }else{
                banco.execSQL("INSERT INTO tarefas (terafa) VALUES('"+ texto +"')");
                Toast.makeText(getApplicationContext(), "Tarefa foi salva com sucesso", Toast.LENGTH_SHORT).show();
                recuperarTarefa();
                caixa.setText("");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void recuperarTarefa(){
        try{
            //recuperar as tarefas
            Cursor cursor = banco.rawQuery("SELECT * FROM tarefas ORDER BY id DESC", null);

            //recuperar os ids da coluna
            int indiceColunmId = cursor.getColumnIndex("id");
            int indiceColunmTarefa = cursor.getColumnIndex("tarefa");


            //criado list
            itens = new ArrayList<String>();
            ids = new ArrayList<Integer>();

            //criado adptet
            itensAdptador = new ArrayAdapter<String>(
                    getApplicationContext(),
                    android.R.layout.simple_list_item_2,
                    android.R.id.text2,
                    itens) {
                @Override
                public View getView(int position, View convertView, ViewGroup parent) {

                    View view = super.getView(position, convertView, parent);
                    TextView text = (TextView) view.findViewById(android.R.id.text2);
                    text.setTextColor(Color.BLACK);
                    return view;

                }
            };

            //inserindo no adpter
            lista.setAdapter(itensAdptador);

            //listar as tarefas
            cursor.moveToFirst();
            while (cursor != null){
                Log.i("Resultado - ", "tarefa: " + cursor.getString(indiceColunmTarefa));
                itens.add(cursor.getString(indiceColunmTarefa));
                ids.add(Integer.parseInt(cursor.getString(indiceColunmId)));
                cursor.moveToNext();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void removeTarefa(Integer id){
        try{
            banco.execSQL("DELETE FROM tarefas WHERE id="+id);
            recuperarTarefa();
            Toast.makeText(MainActivity.this, "Tarefa removida com sucesso!", Toast.LENGTH_SHORT).show();

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.nathan.listanewn.MainActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/linearLayout"
        android:layout_marginTop="5dp">

        <EditText
            android:id="@+id/edtPeca"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textPersonName"
            android:text="" />


        <Button
            android:id="@+id/btnAdds"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Adicionar"
            android:layout_weight="1"
            android:background="@drawable/redondo_salvar"
            android:textColor="#fff"/>
    </LinearLayout>

    <ListView
        android:id="@+id/listAdd"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="80dp"
        android:layout_centerHorizontal="true" />
</RelativeLayout>
  • This line is right: database.execSQL("INSERT INTO tasks (terafa) VALUES('"+ text +"')"); ?

1 answer

1


You are trying to insert into a column that has a typo ("terafa") in the INSERT query. The application should crash on this line, but as you wrapped the code with a Try-catch block, it simply closes the "save Arefa" method and keeps running normally and you don’t see the error (because there is no treatment in "catch". Try putting a Toast in there and take the exception of the variable "and"), but if you run with the mobile connected via USB in Android Studio, you can see the exception generated in logcat.

A suggestion, exchange the.execSQL() database per.Insert() database, because execSQL does not give any confirmation that any record has been entered in the database, while Insert() returns the number of rows entered, as it may be that your query is correct and even then nothing is inserted if some restriction of the bank is not satisfied, such as integrity violations, for example, where the execSQL will simply try to insert, the bank will not let and will stand for it.

Browser other questions tagged

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