0
我有一個計算銷售額的方法的片段。我在這個Fragment裏面還有一個帶有BaseAdapter的ListView,顯示出售它的售價。在這個ListView中有每行刪除銷售的按鈕。在我的片段中,我有一種方法可以計算出售物品的所有價值。在ListView中刪除銷售項目後,我想重新計算我的銷售,並且我想要刪除包含此項目的ListView行。問題是我不能執行此方法來重新計算我的銷售,並且在刪除項目行後我無法更改我的ListView。刪除項目後更新Fragment和BaseAdapter中的方法?
我該怎麼辦?
片段
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();
}
}
BaseAdapter
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;
}
}
您是否收到任何錯誤? – vinitius 2015-03-13 20:28:54
@vinitius沒有錯誤,cf.calculaValoresCompra()'片段的方法不執行,適配器不更新(刷新)。 – FernandoPaiva 2015-03-13 20:46:33
由於您沒有收到任何錯誤,而且您的方法沒有執行,您是否檢查過'deleteBuilder.delete()'的返回值? – vinitius 2015-03-13 20:53:11