Ad

Android Alertdialog Doesn't Show After Intent Back To Activity

- 1 answer

I'm making a alertdialog to fill in the receipt item. there is a button in the alertdialog that is used to move to a new activity for scanning QR. The problem is after scanning QR Code and intent back to Receipt Item Activity, the alertdialog doesn't show again so I need to press alertdialog button again. how can I make the alertdialog still show after intent back from QR Scanner to Create Receipt

I already try adding onShowListener but the alertdialog still doesn't show.

final AlertDialog alertDialog = builder.create();
                alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
                    @Override
                    public void onShow(DialogInterface dialog) {

                        Button btnScan = v.findViewById(R.id.alertdialog_receipt_scanqr);
                        btnScan.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent i = new Intent(CreateReceiptActivity.this, QRScannerActivity.class);
                                startActivityForResult(i, QR_REQUEST_CODE);
                                alertDialog.dismiss();
                                finish();
                            }
                        });
                    }
                });
                alertDialog.show(); 

this is the ReceiptActivity full code:

public class CreateReceiptActivity extends AppCompatActivity {

    @BindView(R.id.receipt_date)
    TextView date;
    @BindView(R.id.receipt_invoice)
    TextView invoiceNumber;
    @BindView(R.id.btn_receipt_add_item)
    ImageButton addItem;
    @BindView(R.id.btn_receipt_print)
    ImageButton printItem;
    @BindView(R.id.receipt_view_recycler)
    RecyclerView recyclerView;
    @BindView(R.id.create_receipt_pb_loading)
    ProgressBar pbloading;

    private static final int QR_REQUEST_CODE = 1;
    List<ListAutoComplete> autoCompleteList;
    ListAutoComplete listAutoComplete;


    List<ListReceiptItem> receiptItemList;
    ListReceiptItem listReceiptItem;
    ReceiptItemAdapter adapter;
    public String itemType, itemQty, itemPrice, itemDate, itemInvoice, lastInvoice, qrResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_receipt);
        ButterKnife.bind(this);


        receiptItemList = new ArrayList<>();
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ReceiptItemAdapter(this, receiptItemList);
        recyclerView.setAdapter(adapter);
        itemInvoice = invoiceNumber.getText().toString();
        itemDate = setDate(date);
        date.setText(this.getString(R.string.date, setDate(date)));

        printItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case DialogInterface.BUTTON_POSITIVE:
                                pbloading.setVisibility(View.VISIBLE);
                                cutStock();
                                break;

                            case DialogInterface.BUTTON_NEGATIVE:
                                //No button clicked
                                break;
                        }
                    }
                };

                AlertDialog.Builder builder = new AlertDialog.Builder(CreateReceiptActivity.this);
                builder.setMessage("Print Transaksi ?").setPositiveButton("Ya", dialogClickListener)
                        .setNegativeButton("Tidak", dialogClickListener).show();

            }
        });


        addItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LayoutInflater li = CreateReceiptActivity.this.getLayoutInflater();

                final View v = li.inflate(R.layout.alertdialog_create_receipt, null);
                final AlertDialog.Builder builder = new AlertDialog.Builder(CreateReceiptActivity.this);
                builder.setView(v);
                final EditText addItemType = v.findViewById(R.id.alertdialog_receipt_type);
                final EditText addItemQty = v.findViewById(R.id.alertdialog_receipt_qty);
                final EditText addItemPrice = v.findViewById(R.id.alertdialog_receipt_price);
                Button btnSubmit = v.findViewById(R.id.alertdialog_receipt_submit);
                addItemType.setText(qrResult);

                final AlertDialog alertDialog = builder.create();
                alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
                    @Override
                    public void onShow(DialogInterface dialog) {

                        Button btnScan = v.findViewById(R.id.alertdialog_receipt_scanqr);
                        btnScan.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent i = new Intent(CreateReceiptActivity.this, QRScannerActivity.class);
                                startActivityForResult(i, QR_REQUEST_CODE);
                                alertDialog.dismiss();
                                finish();
                            }
                        });
                    }
                });
                alertDialog.show();
                btnSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        itemType = addItemType.getText().toString().trim();
                        itemQty = addItemQty.getText().toString().trim();
                        itemPrice = addItemPrice.getText().toString().trim();
                        listReceiptItem = new ListReceiptItem(itemType, itemQty, itemPrice, "0");
                        receiptItemList.add(listReceiptItem);
                        recyclerView.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
                        alertDialog.dismiss();
                        Toast.makeText(CreateReceiptActivity.this, "barang tertambah", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        Bundle extras = getIntent().getExtras();
        if(extras != null && extras .containsKey("QRItemtype")){
            qrResult = extras.getString("QRItemtype");
            if (qrResult == null) {
                Toast.makeText(this, "Scan gagal", Toast.LENGTH_SHORT).show();
            } else if (!(qrResult == null)) {
                Toast.makeText(this, qrResult, Toast.LENGTH_SHORT).show();

            }
        }
    }

    private void cutStock() {
        final FirebaseFirestore db = FirebaseFirestore.getInstance();

        for (ListReceiptItem listreceiptItem : receiptItemList) {
            final String soldItemDate = date.getText().toString().trim();
            final String soldItemInvoice = invoiceNumber.getText().toString().trim();
            final String soldItemtype = listreceiptItem.getType();
            final String soldItemQty = listreceiptItem.getQty();
            final String soldItemPrice = listreceiptItem.getPrice();

            db.collection("watchlist").whereEqualTo("type", soldItemtype)
                    .get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            Log.d(Tag.ITEM, document.getId() + "=>" + document.getData());

                            String id = document.getString("id");
                            String oldqty = document.getString("qty");
                            Integer i = Integer.parseInt(oldqty) - Integer.parseInt(soldItemQty);
                            String newQty = String.valueOf(i);

                            Map<Object, String> map = new HashMap<>();
                            map.put("qty", newQty);
                            db.collection("watchlist").document(document.getId()).set(map, SetOptions.merge());

                            ArrayList<Map<String, Object>> list = new ArrayList<>();
                            Map<String, Object> receiptItem = new HashMap<>();
                            receiptItem.put("invoice", soldItemInvoice);
                            list.add(receiptItem);
                            receiptItem.put("date", soldItemDate);
                            list.add(receiptItem);
                            receiptItem.put("type", soldItemtype);
                            list.add(receiptItem);
                            receiptItem.put("qty", soldItemQty);
                            list.add(receiptItem);
                            receiptItem.put("price", soldItemPrice);
                            list.add(receiptItem);


                            final FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
                            firebaseFirestore.collection("sales").add(receiptItem).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                                @Override
                                public void onSuccess(DocumentReference documentReference) {
                                    Toast.makeText(CreateReceiptActivity.this, "Berhasil mencetak transaksi", Toast.LENGTH_SHORT).show();
                                    Integer i = Integer.parseInt(soldItemInvoice) + 1;
                                    String newInvoice = String.valueOf(i);
                                    invoiceNumber.setText(newInvoice);
                                    pbloading.setVisibility(View.GONE);

                                }
                            })
                                    .addOnFailureListener(new OnFailureListener() {
                                        @Override
                                        public void onFailure(@NonNull Exception e) {
                                            Toast.makeText(CreateReceiptActivity.this, "Gagal mencetak", Toast.LENGTH_SHORT).show();
                                            pbloading.setVisibility(View.GONE);
                                        }
                                    });
                        }
                    } else {
                        Toast.makeText(CreateReceiptActivity.this, "Barang tidak terdaftar", Toast.LENGTH_SHORT).show();
                        Log.w(Tag.ITEM, "error getting documents", task.getException());
                        pbloading.setVisibility(View.GONE);
                    }
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(CreateReceiptActivity.this, "Barang tidak terdaftar", Toast.LENGTH_SHORT).show();
                    pbloading.setVisibility(View.GONE);
                }
            });
        }
    }

    public void getTypeList() {

        FirebaseFirestore db = FirebaseFirestore.getInstance();
        CollectionReference documentReference = db.collection("watchlist");
        documentReference.get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                Log.d(Tag.ITEM, document.getId() + "=>" + document.getData());

                                String type = document.getString("type");
                                listAutoComplete = new ListAutoComplete(type);
                                autoCompleteList.add(listAutoComplete);
                            }

                        } else {
                            Log.w(Tag.ITEM, "error getting documents", task.getException());
                        }
                    }
                });
    }

    public String setDate(TextView view) {

        java.util.Date today = Calendar.getInstance().getTime();//getting date
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");//formating according to my need
        String date = formatter.format(today);
        view.setText(date);
        return date;
    }

}
Ad

Answer

You call alertDialog.dismiss() and finish() after clicking on the QR button. Naturally this will close the alert dialog.

Either remove these two calls or open the dialog again in OnResume method.

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

private void openDialog(){
final AlertDialog alertDialog = builder.create();
                alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
                    @Override
                    public void onShow(DialogInterface dialog) {

                        Button btnScan = v.findViewById(R.id.alertdialog_receipt_scanqr);
                        btnScan.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent i = new Intent(CreateReceiptActivity.this, QRScannerActivity.class);
                                startActivityForResult(i, QR_REQUEST_CODE);

                            }
                        });
                    }
                });
                alertDialog.show(); 

}

In case you dont want the alert to pop up when you minimaize and return you can

   if(getIntent() != null){
        isReturnedFromActivity = getIntent.getBooleanExtra(IS_RETURNED_FROM_ACTIVITY ,false);
        if(isReturnedFromActivity){
            openDialog();
        }
    }
}

And of course add IS_RETURNED_FROM_ACTIVITY key set to True when calling this activity.

Ad
source: stackoverflow.com
Ad