Ajuda para Deletar item do banco de dados. SQLITE help!

2,790 views
Skip to first unread message

BP-Korp

unread,
Apr 29, 2013, 7:22:47 PM4/29/13
to androidb...@googlegroups.com
  Boa noite,

 Ja passei horas estudando e procurando informações mas até agora nao consegui sucesso nessa função.
 Eu estou querendo deletar um item no banco de dados.
  Eu to preenchendo a listview com os registros do banco, mas nao consegui ainda deletar algum registro.
  Eu estou usando um AdapterListView customizado.

Alguem pode me ajudar?? Des de já eu agradeço muito!
Ja procurei algo similar aqui mas ainda nao achei.
Segue abaixo o codigo do meu programa.




 Se alguem precisar do programa eu posto na Aqui pra voces.



-----------------------------------------------------------------------------------------------------------

Classe LISTPERS.

package com.listteste;

import java.util.ArrayList;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ListaPers extends Activity implements OnItemClickListener {

    private ListView listView;
    private AdapterListView AdapterListView;
    private ArrayList<ItemListView> itens;
    SQLiteDatabase bancoDeDados = null; // banco de dados
    Cursor cursor;
    int i;
    int b = 1;
    EditText editText1;
    Button button1;
    TextView text2;

   
    private void setMessage(String message) {
        Log.e(" ListaPersonalisada ", message);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); // identifica a ACTIVITY
                                                    // desse codigo

        editText1 = (EditText) findViewById(R.id.editText1); // identifica o
                                                                // edittext no
                                                                // codigo
        button1 = (Button) findViewById(R.id.button1); // identifica o botao no
                                                        // codigo
        listView = (ListView) findViewById(R.id.listView1); // identifica o
                                                            // ListView
        listView.setOnItemClickListener(this); // recebe o clique do listview
        text2 = (TextView) findViewById(R.id.textView1);
        // //////////// LISTVIEW COMPONENTES //////////////////////////////
        itens = new ArrayList<ItemListView>(); // cria o ArrayList

        // criar o adapter
        AdapterListView = new AdapterListView(this, itens);
        // Define o Adapter
        listView.setAdapter(AdapterListView);
        // cor quando é selecionado
        listView.setCacheColorHint(Color.TRANSPARENT);

        button1.setOnClickListener(new View.OnClickListener() { // recebe o
                                                                // clique do
                                                                // botao.
            @Override
            public void onClick(View v) {

                gravarRegistro();
                atualizaListView();
                editText1.setText("");
            }
        });

        setMessage(" ON CREATE OK!");

    }

    @Override
    protected void onResume() {
        super.onResume();

        try {
            abreOuCriaBanco();
            atualizaListView();

        } catch (Exception e) {
            Toast.makeText(this, "ERRO  " + e.getMessage(), Toast.LENGTH_LONG)
                    .show();
        }

    }

    public boolean atualizaListView() { // metodo que vai consultar e jogar
                                            // tudo na listview

        itens.removeAll(itens); // a cada vez q executa esse metodo ele limpa o
                                // array e acrescenta o resultado do banco

        try {
            cursor = bancoDeDados.query("LISTAPERS", new String[] { "_ID",
                    "NOME", "TIME", "PAGO" }, null,// selection,
                    null,// selectionArgs,
                    null,// groupBy,
                    null,// having,
                    null,// orderBy,
                    null// limit
                    );

            text2.setText("N de Reg: " + cursor.getCount()); // CONTADOR DE
                                                                // REGISTROS

            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
                    .moveToNext()) { // conta quantos registros tem no DB e joga
                                        // no array e mostra na lista

                ItemListView item = new ItemListView(cursor.getString(cursor
                        .getColumnIndex("NOME")), R.drawable.atualiza);
                itens.add(item);
                AdapterListView.notifyDataSetChanged();

            }

            return true;

        } catch (Exception e) {
            Toast.makeText(this,
                    "ERRO AO ADICIONAR NO ITEM LISTVIEW. " + e.getMessage(),
                    Toast.LENGTH_LONG).show();
            return false;
        }
    }

    public void abreOuCriaBanco() { // abre ou cria banco
        try {
            String NOME_BANCO = "LISTAPERSONALISADA";
            String TABELA = "LISTAPERS";
            String COLUNA_NOME = "NOME";
            String COLUNA_TIME = "TIME";
            String COLUNA_PAGO = "PAGO";
            String COLUNA_ID = "_id";

            String sql = "CREATE TABLE IF NOT EXISTS " + TABELA + " ("
                    + COLUNA_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                    + COLUNA_NOME + " text(20) not null," + COLUNA_TIME
                    + " integer(2) default 0," + COLUNA_PAGO
                    + " text(3) default NAO);";

            // cria ou abre o banco de dados
            bancoDeDados = openOrCreateDatabase(NOME_BANCO,
                    MODE_ENABLE_WRITE_AHEAD_LOGGING, null);
            bancoDeDados.execSQL(sql);

            Toast.makeText(this, "BD CRIADO COM SUCESSO! ", Toast.LENGTH_LONG)
                    .show();
        } catch (Exception e) {

            Toast.makeText(this, "BANCO DEU ERRO! ", Toast.LENGTH_LONG).show();
        }
    }

    public void DeletaItemBanco(int rowId) { // abre ou cria banco
        try {
           
           
    ///////////// NAO FUNCIONA NEM A PAU.       

     bancoDeDados.execSQL("DELETE FROM  LISTAPERS" + " where _id="
                        + rowId + ";");
     
     
           
            Toast.makeText(this, "DELETE OK! ", Toast.LENGTH_LONG).show();
        } catch (Exception e) {

            Toast.makeText(this, "DELETE DEU ERRO! ", Toast.LENGTH_LONG).show();
        }
    }


    public void fechaBanco() {
        try {
            bancoDeDados.close();
            cursor.close();

        } catch (Exception e) {
            Toast.makeText(this,
                    "ERRO AO FECHAR BANCO. Exception E " + e.getMessage(),
                    Toast.LENGTH_LONG).show();
        }
    }

    public void gravarRegistro() { // grava registro no banco. captura do
                                    // edittext e joga pro banco

        try {
            String sqlInsert = "INSERT INTO LISTAPERS (nome) values ('"
                    + editText1.getText().toString() + "')";

            bancoDeDados.execSQL(sqlInsert);

            Toast.makeText(this, "Dados Gravados com Sucesso! ",
                    Toast.LENGTH_LONG).show();

        } catch (Exception e) {
            Toast.makeText(this,
                    "ERRO Ao Gravar no BANCO. gravarRegistro()" + e.getMessage(),
                    Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onStop() {

        bancoDeDados.close();
        cursor.close();

        super.onStop();
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // Pega o item que foi selecionado
        // ItemListView item = (ItemListView) AdapterListView.getItem(arg2);
        // Demonstraçao
        // Toast.makeText(this, "clicou " +
        // item.getTexto(),Toast.LENGTH_LONG).show();

        setMessage(" onItemClick(AdapterView<?> ");

    }
}
-------------------------------------------------------------------------------------

Classe AdapterListView


package com.listteste;

import java.util.ArrayList;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class AdapterListView extends BaseAdapter implements Filterable {
    private LayoutInflater mInflater;
    private ArrayList<ItemListView> itens;
    private Context context;

    ListaPers kkk = new ListaPers(); /////////////////////////////////////

    private void setMessage(String message) {
        Log.e(" AdapterListView ", message);
    }

    public AdapterListView(Context context, ArrayList<ItemListView> itens) {
        // Itens que preencheram o listview
        this.itens = itens;
        // responsavel por pegar o Layout do item
        mInflater = LayoutInflater.from(context);
        this.context = context;

        setMessage("AdapterListView OK!");
    }

    @Override
    public int getCount() {
        setMessage("GetCount");

        return itens.size();

    }

    @Override
    public ItemListView getItem(int position) {
        setMessage("get Position ITem clicado???");

        return itens.get(position);
    }

    @Override
    public long getItemId(int position) {

        setMessage("GET ITEM ID " + position);
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {

        // Pega o item de acordo com a posicao
        final ItemListView item = itens.get(position);

        ViewHolder holder;

        convertView = mInflater.inflate(R.layout.item_listview, null);
        // Creates a ViewHolder and store references to the two children views
        // we want to bind data to.

        holder = new ViewHolder();
        holder.textLine = (TextView) convertView.findViewById(R.id.text);
        holder.iconLine = (ImageView) convertView.findViewById(R.id.imagemview);
        holder.buttonLine = (Button) convertView.findViewById(R.id.buttonLine);

        convertView.setOnClickListener(new OnClickListener() {
            public void onClick(View v) { // captura o clique no item da lista.

                Toast.makeText(context,
                        "Click - " + position + " " + item.getTexto(),
                        Toast.LENGTH_SHORT).show();

            }
        });

        holder.buttonLine.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) { // captura o clique no botao(delete)
                                            // do item dentro da lista.

                Toast.makeText(context,
                        "Delete - " + String.valueOf(position) + " ",
                        Toast.LENGTH_SHORT).show();
               
            int rowIdatual =0;
           
                try {

                    ///nao esta funcionando

                    rowIdatual = position+1;
                    kkk.DeletaItemBanco(rowIdatual);       
                   
                } catch (Exception e) {
                    Toast.makeText(context,
                            "ERRO Delete - " + e.getMessage(),
                            Toast.LENGTH_SHORT).show();
                }
                   
                setMessage("Remove OK! " + position);
            }
        });

        convertView.setTag(holder);

        // Bind the data efficiently with the holder.
        holder.iconLine.setImageResource(item.getIconeRid());
        holder.textLine.setText(item.getTexto());
        return convertView;
    }

    protected ItemListView setImageResource(int botaoaddlist) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
    }

    static class ViewHolder {
        TextView textLine;
        ImageView iconLine;
        Button buttonLine;
    }

    @Override
    public Filter getFilter() {

        return null;
    }


}


Lucas Xavier

unread,
Apr 29, 2013, 9:27:48 PM4/29/13
to androidb...@googlegroups.com
public void limparTabelaObjeto() {
        SQLiteDatabase db = this.getWritableDatabase();
        int delete = db.delete(NOME_DA_TABELA, CLASULA_WHERE,
                new String[] {});
        db.close();
}

NOME_DA_TABELA = Tabela onde será deletado o registro, no seu caso "LISTAPERS"
CLAUSULA_WHERE = o where... no seu caso vai ser "_id = "+ rowId

:)

--
Atenciosamente,

Lucas Xavier


2013/4/29 BP-Korp <pai...@gmail.com>



--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Fabiano Soares

unread,
Apr 30, 2013, 7:07:23 AM4/30/13
to androidb...@googlegroups.com
Bom dia.
No meu app eu tbm uso o comando SQL para delete
em meus comandos não existe o ";" no final e funciona perfeitamente!
faz uma teste!
public void limpaTabela() {

SQLiteDatabase db = new DBHelper(ctx).getWritableDatabase();

db.execSQL("DELETE FROM " + TABLE_NAME);
db.close();

Lucas Xavier

unread,
Apr 30, 2013, 7:28:27 AM4/30/13
to androidb...@googlegroups.com
Porque não usar o método delete do SQLiteDatabase? :)

--
Atenciosamente,

Lucas Xavier


2013/4/30 Fabiano Soares <fabian...@gmail.com>

BP-Korp

unread,
Apr 30, 2013, 9:43:59 AM4/30/13
to androidb...@googlegroups.com
Oi Lucas, o primeiro metodo, do qual voce postou nao deu certo.
Fabiano, seu metodo tambem nao deu certo....

 Segue o projeto em anexo para voces darem uma analizada, nao sei mais pra onde correr com esse problema.

=/


ListTeste.rar

Lucas Xavier

unread,
Apr 30, 2013, 9:47:36 AM4/30/13
to androidb...@googlegroups.com
Coloca só o trecho que você implementou o delete e o trecho do ERRO aqui http://pastebin.com/



--
Atenciosamente,

Lucas Xavier


2013/4/30 BP-Korp <pai...@gmail.com>

Bruno Paignez

unread,
Apr 30, 2013, 10:34:59 AM4/30/13
to androidb...@googlegroups.com
  Como eu uso esse pastebin? alguem vai me ajudar através dele? Vlw Abc.


2013/4/30 Lucas Xavier <luca...@gmail.com>

--
You received this message because you are subscribed to a topic in the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/androidbrasil-dev/UioRNsEBJz0/unsubscribe?hl=en-US.
To unsubscribe from this group and all its topics, send an email to androidbrasil-...@googlegroups.com.

For more options, visit https://groups.google.com/groups/opt_out.
 
 



--

Bruno S. Paignez

bru...@brunop.com.br <<Main>>
pai...@hotmail.com <<Skype>>
pai...@gmail.com 

Lucas Xavier

unread,
Apr 30, 2013, 10:38:28 AM4/30/13
to androidb...@googlegroups.com
Pastebin serve para colar código, justamente pra você não ter que enviar todo seu projeto para todo mundo.

Logo quando abre tem uma caixa imensa, você cola o trecho do código que tá dando erro lá!

E cola também a exceção que tá dando :)

--
Atenciosamente,

Lucas Xavier


2013/4/30 Bruno Paignez <pai...@gmail.com>

BP-Korp

unread,
Apr 30, 2013, 11:43:52 AM4/30/13
to androidb...@googlegroups.com
  Alguem mais consegue me dizer mais ou menos oque fazer para solucionar este imenso problema?

Vlw.

Abc

Maicon Strey

unread,
Apr 30, 2013, 12:09:02 PM4/30/13
to androidb...@googlegroups.com
Se tu colocar no paste bin e nos mandar o link gerado pro teu código podemos tentar.


Maicon Strey
Novo Hamburgo - RS - Brasil
------------------
------------------
Linux user: #525086


Bruno Paignez

unread,
Apr 30, 2013, 12:20:15 PM4/30/13
to androidb...@googlegroups.com


2013/4/30 Maicon Strey <mst...@gmail.com>

--
You received this message because you are subscribed to a topic in the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/androidbrasil-dev/UioRNsEBJz0/unsubscribe?hl=en-US.
To unsubscribe from this group and all its topics, send an email to androidbrasil-...@googlegroups.com.

For more options, visit https://groups.google.com/groups/opt_out.
 
 

Bruno Paignez

unread,
Apr 30, 2013, 12:25:16 PM4/30/13
to androidb...@googlegroups.com
ja postei tambem o codigo inteiro (talvez isso é ruim) mas se precisar me avisa que eu disponibilizo novamente



2013/4/30 Bruno Paignez <pai...@gmail.com>

Lucas Xavier

unread,
May 3, 2013, 9:21:09 AM5/3/13
to androidb...@googlegroups.com
Unknown Paste ID!... 

O link que você postou não é válido

--
Atenciosamente,

Lucas Xavier


2013/4/30 Bruno Paignez <pai...@gmail.com>
ja postei tambem o codigo inteiro (talvez isso é ruim) mas se precisar me avisa que eu disponibilizo novamente

Bruno Paignez

unread,
May 3, 2013, 10:13:48 AM5/3/13
to androidb...@googlegroups.com
 Eu havia colocado para expirar.


vou aderir o codigo no pastebin novamente.


http://pastebin.com/A0z591N4 - CLASSE LISTPERSONALISADA
http://pastebin.com/jHVCGs6y - ADAPTERLISTVIEW


Plis helpmeee, eu nao consigo deletar o item do banco....




2013/5/3 Lucas Xavier <luca...@gmail.com>

BP-Korp

unread,
May 3, 2013, 10:16:36 AM5/3/13
to androidb...@googlegroups.com
 Eu havia colocado para expirar. Mas agora eu POstei novamente.



vou aderir o codigo no pastebin novamente.


http://pastebin.com/A0z591N4 - CLASSE LISTPERSONALISADA
http://pastebin.com/jHVCGs6y - ADAPTERLISTVIEW


Plis helpmeee, eu nao consigo deletar o item do banco....

Lucas Xavier

unread,
May 3, 2013, 11:59:51 AM5/3/13
to androidb...@googlegroups.com
Uma coisa que eu notei é que você está tentando deletar de acordo com a POSIÇÃO do item no listView.

Item 1
Item 2
Item 3


Se clicar em deletar Item 2, vai no banco pedir para deletar o objeto com _rowId = 2 (position + 1, de acordo com seu código). É isso mesmo que você quer? 

--
Atenciosamente,

Lucas Xavier


2013/5/3 BP-Korp <pai...@gmail.com>

--

Lucas Xavier

unread,
May 3, 2013, 12:00:25 PM5/3/13
to androidb...@googlegroups.com
Posta no pastebin também o STACKTRACE da exceção.

--
Atenciosamente,

Lucas Xavier

Junior Bindaco

unread,
Jan 16, 2014, 6:11:07 AM1/16/14
to androidb...@googlegroups.com
Use dessa forma 
database.delete(BaseDAO.NOME_DA_TANELA, BaseDAO.NOME_COLUNA_ID + " = " + id, null);

valeu 
Reply all
Reply to author
Forward
0 new messages