Удалить ListiView и строку SQLite в Android - PullRequest
0 голосов
/ 26 июня 2019

Я разрабатываю приложение в Android Studio с использованием этой библиотеки: com.daimajia.swipelayout: library: 1.2.0@aar.Мой пользователь использует базу данных SQLite со следующими классами:

BDSQLiteHelper.java

public class BDSQLiteHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "ExtraOficial";
    private static final String TABELA_VAZAMENTOS = "VazamentosToSQL";

    private static final String vazID = "VazID";
    private static final String nomeServico = "nomeServico";
    private static final String[] VAZ_COLUNAS = {vazID, nomeServico};

 public BDSQLiteHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

@Override
    public void onCreate(SQLiteDatabase db) {
String CREATE_VAZAMENTOTABLE = "CREATE TABLE VazamentosToSQL ("+
                "vazID          INTEGER PRIMARY KEY AUTOINCREMENT,"+
                "nomeServico)";
        db.execSQL(CREATE_VAZAMENTOTABLE);
 }

@Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        db.execSQL("DROP TABLE IF EXISTS VazamentosToSQL");
        this.onCreate(db);

    }
public void addVazamentos(VazamentosToSQL VazamentosToSQL) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(nomeServico, VazamentosToSQL.getNomeServico());
        db.insert(TABELA_VAZAMENTOS, null, values);
        db.close();
    }
public VazamentosToSQL getVazamentos (int vazID) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABELA_VAZAMENTOS,
                VAZ_COLUNAS,
                " vazID = ?",
                new String[] {String.valueOf(vazID)},
                null,
                null,
                null,
                null);
        if (cursor == null) {
            return null;
        } else {
            cursor.moveToFirst();
            VazamentosToSQL VazamentosToSQL = cursorTovazamentos(cursor);
            return VazamentosToSQL;
        }
    }


private VazamentosToSQL cursorTovazamentos(Cursor cursor) {
        VazamentosToSQL VazamentosToSQL = new VazamentosToSQL();
        VazamentosToSQL.setVazID(Integer.parseInt(cursor.getString(0)));
        VazamentosToSQL.setNomeServico(cursor.getString(1));
        return VazamentosToSQL;
    }


public ArrayList<VazamentosToSQL> getAllVazamentos() {
        ArrayList<VazamentosToSQL> listaVazamentos = new ArrayList<VazamentosToSQL>();
        String query = "SELECT * FROM " + TABELA_VAZAMENTOS + " ORDER BY "+ vazID + " DESC";

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(query, null);

        if (cursor.moveToFirst()) {
            do {
                VazamentosToSQL VazamentosToSQL = cursorTovazamentos(cursor);
                listaVazamentos.add(VazamentosToSQL);
            } while (cursor.moveToNext());

        }
        return listaVazamentos;
    }

[...]

public int deleteVazamentos(VazamentosToSQL VazamentosToSQL) {
        SQLiteDatabase db = this.getWritableDatabase();

        int i = db.delete(TABELA_VAZAMENTOS,
                vazID+" =?",
                new String[] { String.valueOf(VazamentosToSQL.getVazID())});
        db.close();
        return i;
    }

VazamentosToSQL.java

public class VazamentosToSQL {
    private int vazID;
    private String nomeServico;
  public int getVazID() { return vazID; }
    public void setVazID(int vazID) {
        this.vazID = vazID;
    }


    public String getNomeServico() { return nomeServico; }
    public void setNomeServico(String nomeServico) { this.nomeServico = nomeServico; }

}

ListViewActivity.java:

[...]
//variables
private BDSQLiteHelper bd;
ArrayList<VazamentosToSQL> listaVazamentos;
SwipeLayout swipeLayout;
private final static String TAG = ListViewActivity.class.getSimpleName();
vazamentosAdapter adapter;
ListView lista;
[...]
@Override
    protected void onCreate(Bundle savedInstanceState) 
{super.onCreate(savedInstanceState);

[...]

 bd = new BDSQLiteHelper(this);
        lista = (ListView) findViewById(R.id.lvdenuncias);
        listaVazamentos = bd.getAllVazamentos();
        setListViewHeader();
        setListViewAdapter();

lista.setOnItemClickListener(new AdapterView.OnItemClickListener() { //aqui é o vazamentosAdapter
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Intent intent = new Intent(ExibeVazamentosActivity.this, DetalhesVazamentosActivity.class);
                intent.putExtra("vazID", listaVazamentos.get(position).getVazID());
                startActivity(intent);

            }
        });
@Override
    protected void onStart() {
        super.onStart();
        updateAdapter(); //Refresh ListView items

    }
private void setListViewHeader() {
        LayoutInflater inflater = getLayoutInflater();
        View header = inflater.inflate(R.layout.header_listview, lista, false);
        totalClassmates = (TextView) header.findViewById(R.id.total);
        swipeLayout = (SwipeLayout)header.findViewById(R.id.swipe_layout);
        setSwipeViewFeatures();
        //UNNECESSARY for me: lista.addHeaderView(header);
    }
private void setSwipeViewFeatures() {
        swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);

        //add drag edge.(If the BottomView has 'layout_gravity' attribute, this line is unnecessary)
        swipeLayout.addDrag(SwipeLayout.DragEdge.Left, findViewById(R.id.bottom_wrapper));

        swipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() {
            @Override
            public void onClose(SwipeLayout layout) {
                Log.i(TAG, "onClose");
            }

            @Override
            public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {
                Log.i(TAG, "on swiping");
            }

            @Override
            public void onStartOpen(SwipeLayout layout) {
                Log.i(TAG, "on start open");
            }

            @Override
            public void onOpen(SwipeLayout layout) {
                Log.i(TAG, "the BottomView totally show");
            }

            @Override
            public void onStartClose(SwipeLayout layout) {
                Log.i(TAG, "the BottomView totally close");
            }

            @Override
            public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {
                //when user's hand released.
            }
        });
    }

private void setListViewAdapter() {
          adapter = new vazamentosAdapter(this, listaVazamentos);
          lista.setAdapter(adapter);
    }


    public void updateAdapter() {
        listaVazamentos.clear();
        listaVazamentos.addAll(bd.getAllVazamentos());
        adapter.notifyDataSetChanged(); //update adapter
        lista.invalidateViews();
        lista.refreshDrawableState();
    }
}

vazamentosAdapter.java:

public class vazamentosAdapter extends ArrayAdapter<VazamentosToSQL> {
    private final Context context;
    private final ArrayList<VazamentosToSQL> elementos;
    File imgFile;
    private Bitmap bitmap;
    private ExifInterface exifObject;
    private ExibeVazamentosActivity activity;
    int vazID;
    private SQLiteDatabase bd;

public vazamentosAdapter(Context context, ArrayList<VazamentosToSQL> elementos) {
        super(context, R.layout.linha, elementos);
        this.context = context;
        this.elementos = elementos;

    }
@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if (convertView == null) {
            // inflate UI from XML file
            convertView = inflater.inflate(R.layout.linha, parent, false);
            // get all UI view
            holder = new ViewHolder(convertView);
            // set tag for holder
            convertView.setTag(holder);
        }else {
            // if holder created, get tag from view
            holder = (ViewHolder) convertView.getTag();
        }
[...]
editText.setText(elementos.get(position).getVaznomeServico());

 holder.btnEdit.setOnClickListener(onEditListener(position, holder));
        holder.btnDelete.setOnClickListener(onDeleteListener(position, holder));

        return convertView;
    }

private View.OnClickListener onDeleteListener(final int position, final ViewHolder holder) {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            /**--------------Tried it, not working =( ---------------*/
                elementos.get(position).getVazID(); 
               //listaVazamentos.remove(position); 
                //activity.listaVazamentos.remove(position); 
                //bd = context.openOrCreateDatabase("DesoExtraOficial", Activity.MODE_PRIVATE, null);
                //bd.execSQL("DELETE from VazamentosToSQL where vazID = '" + elementos.get(position).getVazID() + "'");
                //bd.close();



                //elementos.remove(position);
                Toast.makeText(context, "ID: "+elementos.get(position).getVazID(),Toast.LENGTH_LONG).show();
                bd.deleteVazamentos(VazamentosToSQL);



                holder.swipeLayout.close();
//                activity.updateAdapter(); //Executa o método "updateAdapter()" na Activity "ExibeVazamentos"
        /**--------------Tried it, not working =( ---------------*/
            }
        };
    }


private class ViewHolder {
        private TextView name;
        private View btnDelete;
        private View btnEdit;
        private SwipeLayout swipeLayout;
        private ListView listv;

        public ViewHolder(View v) {
            swipeLayout = (SwipeLayout)v.findViewById(R.id.swipe_layout);
            btnDelete = v.findViewById(R.id.delete);
            btnEdit = v.findViewById(R.id.edit_query);
            listv = (ListView) v.findViewById(R.id.lvdenuncias);
            swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
        }
    }

Упомянутая библиотека прекрасно работает.Но я пытаюсь удалить строку базы данных, когда пользователь нажимает кнопку в соответствии с выбранной строкой списка.С этим кодом: elementos.get (position) .getVazID () Я получаю индекс базы данных.Но я не могу удалить из базы данных.Кто-нибудь может помочь мне с кодом для удаления строки из базы данных и строки из списка просмотра?

1 Ответ

2 голосов
/ 26 июня 2019

Попробуйте изменить это:

public int deleteVazamentos(VazamentosToSQL VazamentosToSQL) { 
    SQLiteDatabase db = this.getWritableDatabase(); 
    int i = db.delete(TABELA_VAZAMENTOS, vazID+" =?", new String[] { String.valueOf(VazamentosToSQL.getVazID())}); 
    db.close(); 
    return i; 
}

На это:

public void deleteVazamentos(int vazID) { 
    SQLiteDatabase db = this.getWritableDatabase(); 
    db.delete(TABELA_VAZAMENTOS, "vazID=" + vazID, null); 
}

Затем, если вы хотите удалить строку, вы можете вызвать: (Inside onDeleteListener)

bd.deleteVazamentos(elementos.get(position).getVazID());
...