删除项目后更新 Fragment 和 BaseAdapter 中的方法?

Updating a method in Fragment and BaseAdapter after item removed?

我有一个 Fragment 有一个计算销售项目的方法。我在这个 Fragment 中还有一个带有 BaseAdapter 的 ListView,它显示了销售情况。在此 ListView 中,每一行都有删除销售商品的按钮。在我的片段中,我有一种方法可以计算所有商品的销售价值。在 ListView 中删除销售项目后,我想重新计算我的销售,我想删除包含该项目的 ListView 行。问题是我无法执行此方法来重新计算我的销售额,并且在删除项目行后我无法更改我的 ListView。

我该怎么做?

片段

public class CarrinhoFrag extends Fragment implements View.OnClickListener,AdapterView.OnItemClickListener, AdapterView.OnItemSelectedListener{
private final String TAG = getClass().getSimpleName() + "->";
private ProgressDialog progress;
private TextView tvNomeCliente;
private TextView tvTotalProntaEntrega;
private TextView tvTotalEntregaFutura;
private TextView tvValorTotalCompra;

//fields
private ListView lvEntregaFutura;
private ListView lvProntaEntrega;
private ScrollView scrollView;

//buttons
private Button btFinalizar;
private Button btCancelar;

//adapter
private CarrinhoListAdapter carrinhoProntaEntrega;
private CarrinhoListAdapter carrinhoEntregaFutura;

//informacoes venda
private DatabaseHelper dh;
private VendaSQLiteDAO vendaDAO;
private Venda venda;

//formas pagto
private String[] listaFormaPagto;
private FormasPagtoListAdapter formasPagtoLA;
private Spinner spinFormaPagto;
private String formapagto;
private Integer parcelas = 0;

//dialog alerta pagamento cartao de credito
private AlertDialog alertDialogCC;
private TextView tvResult;

//dialog alerta pagamento carteira
private AlertDialog alertDialogCarteira;


//total da compra
private BigDecimal totalCompra;


@Override
public void onCreate(Bundle savedInstanceState) {   
    super.onCreate(savedInstanceState);

    //dao de venda
    try {
        dh = new DatabaseHelper(getActivity());
        vendaDAO = new VendaSQLiteDAO(dh.getConnectionSource());
    } catch (SQLException e) {
        Log.e("SQLException CarrinhoFrag->", e.getLocalizedMessage());
    }

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.carrinho_listview, container, false);

    scrollView = (ScrollView)view.findViewById(R.id.scrollView);
    tvNomeCliente = (TextView)view.findViewById(R.id.tvNomeCliente);
    lvProntaEntrega = (ListView)view.findViewById(R.id.lvProntaEntrega);
    lvEntregaFutura = (ListView)view.findViewById(R.id.lvEntregaFutura);
    tvTotalProntaEntrega = (TextView)view.findViewById(R.id.tvTotalProntaEntrega);
    tvTotalEntregaFutura = (TextView)view.findViewById(R.id.tvTotalEntregaFutura);
    tvValorTotalCompra = (TextView)view.findViewById(R.id.tvValorTotalCompra);

    //buttons
    btFinalizar = (Button)view.findViewById(R.id.btFinalizar);
    btCancelar = (Button)view.findViewById(R.id.btCancelar);
    btFinalizar.setOnClickListener(this);
    btCancelar.setOnClickListener(this);

    //forma pagto
    listaFormaPagto = getResources().getStringArray(R.array.formasPagto);
    spinFormaPagto = (Spinner)view.findViewById(R.id.spinFormaPagto);

    return  view;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if(getVendaSQLite() > 0){
        getVendaSQLite();
        init();
        listener();
    }else{
        btFinalizar.setEnabled(false);
        btCancelar.setEnabled(false);
    }

}

/** begin */
public void init(){
    tvNomeCliente.setText("Cliente: " + venda.getCliente().getNome());

    //lista pronta entrega
    List<ItensVenda> listaProntaEntrega = new ArrayList<ItensVenda>();
    //lista entrega futura
    List<ItensVenda> listaEntregaFutura = new ArrayList<ItensVenda>();
    //cria lista dos itens para exibicao no listview
    for(ItensVenda i : venda.getItens()){
        if(i.getEntregaFutura() == 0){
            listaProntaEntrega.add(i);
        }else{
            listaEntregaFutura.add(i);
        }
    }

    //carrinho pronta entrega listadapter
    if(carrinhoProntaEntrega == null){
        carrinhoProntaEntrega = new CarrinhoListAdapter(getView().getContext(), listaProntaEntrega);
        lvProntaEntrega.setAdapter(carrinhoProntaEntrega);
        carrinhoProntaEntrega.setCarrinhoFrag(CarrinhoFrag.this);
    }else{
        carrinhoProntaEntrega.changeLista(listaProntaEntrega);
    }

    //carrinho entrega futura listadapter
    if(carrinhoEntregaFutura == null){
        carrinhoEntregaFutura = new CarrinhoListAdapter(getView().getContext(), listaEntregaFutura);
        lvEntregaFutura.setAdapter(carrinhoEntregaFutura);
        carrinhoEntregaFutura.setCarrinhoFrag(CarrinhoFrag.this);
    }else{
        carrinhoEntregaFutura.changeLista(listaEntregaFutura);
    }

    //formas pagto
    formasPagtoLA = new FormasPagtoListAdapter(getView().getContext(), listaFormaPagto);
    spinFormaPagto.setAdapter(formasPagtoLA);
    spinFormaPagto.setOnItemSelectedListener(this);

    //calcula valores
    calculaValoresCompra();
}

/** listener listview, ativa o scroll para o listview */
private void listener(){
    lvProntaEntrega.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            scrollView.requestDisallowInterceptTouchEvent(true);
            int action = event.getActionMasked();
            switch (action) {
                case MotionEvent.ACTION_UP:
                    scrollView.requestDisallowInterceptTouchEvent(false);
                    break;
            }
            return false;
        }
    });

    lvEntregaFutura.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            scrollView.requestDisallowInterceptTouchEvent(true);
            int action = event.getActionMasked();
            switch (action) {
                case MotionEvent.ACTION_UP:
                    scrollView.requestDisallowInterceptTouchEvent(false);
                    break;
            }
            return false;
        }
    });
}


/**
 * calcula valores da compra
 * calculate itens of sale
 */
public void calculaValoresCompra(){
    BigDecimal bgTotalPE = new BigDecimal(0);
    BigDecimal bgTotalEF = new BigDecimal(0);
    BigDecimal bgTotalCompra = new BigDecimal(0);
    for(ItensVenda i : venda.getItens()){
        for(Produto p : i.getProdutos()){
            if(i.getEntregaFutura() == 0){
                BigDecimal valor = p.getPreco_venda();
                bgTotalPE = bgTotalPE.add(valor);
            }else{
                BigDecimal valor = p.getPreco_venda();
                bgTotalEF = bgTotalEF.add(valor);
            }
        }
    }
    bgTotalCompra = bgTotalCompra.add(bgTotalPE).add(bgTotalEF);
    totalCompra = bgTotalCompra;

    tvTotalProntaEntrega.setText("R$ " + FormataMonetarios.getMoney(bgTotalPE));
    tvTotalEntregaFutura.setText("R$ " + FormataMonetarios.getMoney(bgTotalEF));
    tvValorTotalCompra.setText("R$" + FormataMonetarios.getMoney(bgTotalCompra));
}


/** retornaa a venda corrente com status = 1 */
private Integer getVendaSQLite(){
    List<Venda> list = new ArrayList<Venda>();
    try {
        QueryBuilder<Venda, Integer> qb = vendaDAO.queryBuilder();
        Where where = qb.where();
        where.eq("status", 1);
        PreparedQuery<Venda> pq = qb.prepare();
        list = vendaDAO.query(pq);
        //se existir venda aberta seta o id da venda, se naum cria novo objeto de venda
        if(list.size() > 0){
            venda = list.get(0);
            Log.i("VENDA ID->", venda.getId() + "");
        }else{
            Toast.makeText(getView().getContext(), "Nenhuma venda corrente encontrada", Toast.LENGTH_SHORT).show();
        }
    } catch (SQLException e) {
        Log.e("SQLException getVendaSQLite CarrinhoFrag->", e.getLocalizedMessage());
    }
    return list.size();
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    if(parent == spinFormaPagto){
        formapagto = listaFormaPagto[position];
        showParcelas(formapagto);
    }
}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}

private void showParcelas(String forma){
    if(forma.equals("CARTÃO-CRÉDITO")){
        parcelas = 1;
        showDialogCC();
    }else if(forma.equals("CARTEIRA")){
        parcelas = 1;
        showDialogCarteira();
    }else if(forma.equals("DINHEIRO")){
        parcelas = 0;
    }
}

@Override
public void onClick(View v) {
    if(v == btCancelar){
        cancelarVenda();
    }
}

/** exibe dialog de pagamento cartao de credito */
private void showDialogCC(){
    LayoutInflater li = LayoutInflater.from(getView().getContext());
    final View promptsView = li.inflate(R.layout.parcelas_cartao_dialog, null);
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getView().getContext());
    alertDialogBuilder.setView(promptsView);

    //componentes
    final TextView tvValorParcela = (TextView)promptsView.findViewById(R.id.tvValorParcela);
    final Button btPlus = (Button)promptsView.findViewById(R.id.btPlus);
    final Button btMinus = (Button)promptsView.findViewById(R.id.btMinus);
    tvResult = (TextView)promptsView.findViewById(R.id.tvResult);

    exibeValoresParcelasCC(parcelas);

    btPlus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            parcelas++;
            if(parcelas > 8){
                parcelas = 8;
            }
            exibeValoresParcelasCC(parcelas);
            tvValorParcela.setText(String.valueOf(parcelas));
        }
    });
    btMinus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            parcelas--;
            if(parcelas < 1){
                parcelas = 1;
            }
            exibeValoresParcelasCC(parcelas);
            tvValorParcela.setText(String.valueOf(parcelas));
        }
    });
    final Button btConfirmar = (Button)promptsView.findViewById(R.id.btConfirmar);
    btConfirmar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            alertDialogCC.dismiss();
        }
    });

    //AlertDialog
    alertDialogCC = alertDialogBuilder.create();
    alertDialogCC.setCancelable(false);
    alertDialogCC.show();
}


/** exibe dialog de pagamento carteira */
private void showDialogCarteira(){
    LayoutInflater li = LayoutInflater.from(getView().getContext());
    final View promptsView = li.inflate(R.layout.parcelas_carteira_dialog, null);
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getView().getContext());
    alertDialogBuilder.setView(promptsView);

    //componentes
    final EditText etP1 = (EditText)promptsView.findViewById(R.id.etP1);
    final EditText etP2 = (EditText)promptsView.findViewById(R.id.etP2);
    final EditText etP3 = (EditText)promptsView.findViewById(R.id.etP3);
    final EditText etDataVencimento = (EditText)promptsView.findViewById(R.id.etDataVencimento);
    final TextView tvP1 = (TextView)promptsView.findViewById(R.id.tvP1);
    final TextView tvP2 = (TextView)promptsView.findViewById(R.id.tvP2);
    final TextView tvP3 = (TextView)promptsView.findViewById(R.id.tvP3);
    final TextView tvTotalCompra = (TextView)promptsView.findViewById(R.id.tvTotalCompra);
    final TextView tvTotalParcela = (TextView)promptsView.findViewById(R.id.tvTotalParcela);

    //
    etP1.setText("0.00");
    etP2.setText("0.00");
    etP3.setText("0.00");
    tvTotalCompra.setText(String.format("Total Compra = %s", FormataMonetarios.getMoney(totalCompra)));


    etP1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(!hasFocus){
                if(etP1.getText().toString().isEmpty()){
                    etP1.setText("0.00");
                }
            }
            tvP1.setText(String.format("1ª Parcela = %s", FormataMonetarios.getMoney(new BigDecimal(etP1.getText().toString()))));
            String p1 = etP1.getText().toString();
            String p2 = etP2.getText().toString();
            String p3 = etP3.getText().toString();
            BigDecimal b1 = new BigDecimal(p1);
            BigDecimal b2 = new BigDecimal(p2);
            BigDecimal b3 = new BigDecimal(p3);
            BigDecimal bgTotal = new BigDecimal(0);
            bgTotal = bgTotal.add(b1).add(b2).add(b3);

            tvTotalParcela.setText(String.format("Total Parcelas = %s", FormataMonetarios.getMoney(bgTotal)));
        }
    });
    etP2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(!hasFocus){
                if(etP2.getText().toString().isEmpty()){
                    etP2.setText("0.00");
                }
            }
            tvP2.setText(String.format("2ª Parcela = %s", FormataMonetarios.getMoney(new BigDecimal(etP2.getText().toString()))));
            String p1 = etP1.getText().toString();
            String p2 = etP2.getText().toString();
            String p3 = etP3.getText().toString();
            BigDecimal b1 = new BigDecimal(p1);
            BigDecimal b2 = new BigDecimal(p2);
            BigDecimal b3 = new BigDecimal(p3);
            BigDecimal bgTotal = new BigDecimal(0);
            bgTotal = bgTotal.add(b1).add(b2).add(b3);

            tvTotalParcela.setText(String.format("Total Parcelas = %s", FormataMonetarios.getMoney(bgTotal)));
        }
    });
    etP3.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(!hasFocus){
                if(etP3.getText().toString().isEmpty()){
                    etP3.setText("0.00");
                }
            }
            tvP3.setText(String.format("3ª Parcela = %s", FormataMonetarios.getMoney(new BigDecimal(etP3.getText().toString()))));
            String p1 = etP1.getText().toString();
            String p2 = etP2.getText().toString();
            String p3 = etP3.getText().toString();
            BigDecimal b1 = new BigDecimal(p1);
            BigDecimal b2 = new BigDecimal(p2);
            BigDecimal b3 = new BigDecimal(p3);
            BigDecimal bgTotal = new BigDecimal(0);
            bgTotal = bgTotal.add(b1).add(b2).add(b3);

            tvTotalParcela.setText(String.format("Total Parcelas = %s", FormataMonetarios.getMoney(bgTotal)));
        }
    });


    final Button btConfirmar = (Button)promptsView.findViewById(R.id.btConfirmar);
    btConfirmar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            BigDecimal total = new BigDecimal(0);
            String p1 = etP1.getText().toString();
            String p2 = etP2.getText().toString();
            String p3 = etP3.getText().toString();
            BigDecimal b1 = new BigDecimal(p1);
            BigDecimal b2 = new BigDecimal(p2);
            BigDecimal b3 = new BigDecimal(p3);
            total = total.add(b1).add(b2).add(b3);

            //tvTotalCompra.setText(String.format("Total Compra = %s", FormataMonetarios.getMoney(total)));
            if(etDataVencimento.getText().toString().trim().isEmpty()){
                Toast.makeText(getView().getContext(), "Informe a data de vencimento", Toast.LENGTH_SHORT).show();
            }else if(totalCompra.compareTo(total) >= 0){
                Toast.makeText(getView().getContext(), "O valor total da compra é maior que o valor das parcelas", Toast.LENGTH_SHORT).show();
            }else {
                alertDialogCarteira.dismiss();
            }
        }
    });

    //AlertDialog
    alertDialogCarteira = alertDialogBuilder.create();
    alertDialogCarteira.setCancelable(false);
    alertDialogCarteira.show();
}


/** exibe os valores para parcela compra cartão */
private void exibeValoresParcelasCC(int parcela){
    //calcula e exibe o valor
    BigDecimal valor = new BigDecimal(0);
    //total compra
    //parcelas
    BigDecimal p = new BigDecimal(parcela);
    valor = totalCompra.divide(p, 2, BigDecimal.ROUND_HALF_UP);
    Log.i("VALOR->", valor + "");
    String resultado = String.format("R$ %s ÷ %s = R$ %s", FormataMonetarios.getMoney(totalCompra), parcelas, FormataMonetarios.getMoney(valor));
    tvResult.setText(resultado);
}



/** cancela a venda e limpa o banco de dados */
private void cancelarVenda(){
    AlertDialog.Builder alert = new AlertDialog.Builder(getView().getContext());
    alert.setCancelable(false);
    alert.setTitle("Kontrole");
    alert.setMessage("Deseja realmente cancelar ?");
    alert.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            getView().getContext().deleteDatabase(DatabaseHelper.databaseName);
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            Fragment frag = new VendasFrag();
            ft.replace(R.id.fl, frag);
            ft.addToBackStack(KontroleConfigs.TAG_TOBACKSTACK);
            ft.commit();
        }
    });
    alert.setNegativeButton("Não", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    AlertDialog dialog = alert.create();
    dialog.show();

}

}

基础适配器

public class CarrinhoListAdapter extends BaseAdapter{
    private Context context;
    private List<ItensVenda> lista;
    private CarrinhoFrag cf;


    public CarrinhoListAdapter(Context context, List<ItensVenda> lista) {
        this.context = context;
        this.lista = lista;
    }

    public void changeLista(List<ItensVenda> lista){
        this.lista = lista;
        notifyDataSetChanged();
    }


    public void setCarrinhoFrag(CarrinhoFrag cf){
        this.cf = cf;
    }


    @Override
    public int getCount() {
        return lista.size();
    }

    @Override
    public Object getItem(int position) {
        return lista.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }



    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ItensVenda iv = lista.get(position);
        final ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.carrinho_listadapter, parent, false);

            holder.llCarrinhoAdapter = (LinearLayout) convertView.findViewById(R.id.llCarrinhoAdapter);
            holder.tvQtd = (TextView)convertView.findViewById(R.id.tvQtd);
            holder.tvProduto = (TextView)convertView.findViewById(R.id.tvProduto);
            holder.tvValorProduto = (TextView)convertView.findViewById(R.id.tvValorProduto);
            holder.ibExcluir = (ImageButton)convertView.findViewById(R.id.ibExcluir);

            convertView.setTag(holder);
        }else{
            holder = (ViewHolder)convertView.getTag();
        }

        holder.tvQtd.setText(FormataQuantidade.getQuantidade(iv.getQuantidade()));
        for(Produto p : iv.getProdutos()){
            holder.tvProduto.setText(p.getNome());
            holder.tvValorProduto.setText(" R$ " + FormataMonetarios.getMoney(p.getPreco_venda()));
        }

        holder.ibExcluir.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ItensVenda item = lista.get(position);
                removeItem(item);
            }
        });

        return convertView;
    }

    /** remove item */
    private void removeItem(ItensVenda item){
        try {
            DatabaseHelper dh = new DatabaseHelper(this.context);
            ItemVendaSQLiteDAO itensVendaDAO = new ItemVendaSQLiteDAO(dh.getConnectionSource()); ;
            DeleteBuilder<ItensVenda, Integer> deleteBuilder = itensVendaDAO.deleteBuilder();
            deleteBuilder.where().eq("id", item.getId());
            int result = deleteBuilder.delete();
            if(result == 1){
                Log.i("REMOVE->", result + "");
                CarrinhoListAdapter.this.notifyDataSetChanged();
                cf.calculaValoresCompra();
            }
        } catch (SQLException e) {
            Log.e("SQLException removeItem", e.getLocalizedMessage());
        }
    }


    /** pattern view holder */
    private static class ViewHolder{
        LinearLayout llCarrinhoAdapter;
        TextView tvQtd;
        TextView tvProduto;
        TextView tvValorProduto;
        ImageButton ibExcluir;
    }

}

我想您只是缺少调用 changeLista 方法来更新适配器的源代码。像这样:

  if(result == 1){
            Log.i("REMOVE->", result + "");
            //after you remove an item, do what you do to retrieve the updated items from venda and pass it to update your adapter.
            changeLista(yourUpdatedList);
            cf.calculaValoresCompra();
        }

现在的样子,您似乎只是从数据库中删除它,但没有刷新适配器的源。