I can not do the inclusion of the bank

-1

I'm studying android and I'm doing the CRUD from the bank ... only I did the code and put it 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, just below has the listview for me to show the saved items from the bank ... When I click the button it does not happen anything, nor the Toast that I put to enter if you need to type something or if it has been saved successfully. I reviewed the code and found nothing, could anyone 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>
    
asked by anonymous 19.06.2017 / 17:32

1 answer

1

You are trying to insert into a column that is typed ("terafa") in the INSERT query. The application should crash in this line, but as you wrapped the code with a try-catch block, it simply terminates the "save task" method and continues running normally and you do not see the error (because it has no catch handling). put 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, change the database.execSQL () to bank.insert (), because execSQL does not give any confirmation that a record has been inserted in the database, whereas insert () returns the number of rows inserted, be that your query is correct and even if nothing is inserted if some restriction of the bank is not satisfied, such as integrity violations, for example, where execSQL will simply try to insert, the bank will not leave and will stay for it .

    
19.06.2017 / 18:56