Search code examples
javaandroidandroid-fragmentsandroid-intentandroid-activity

How to stop multiple intents from opening sequentially?


I have a list of invoices displayed in one Java activity, and I included the ability to click on one of the invoices to open a new activity that shows its details (using an intent). The issue is, the new activity doesn't open immediately, and if the user clicks on an invoice(s) multiple times before one loads, they all get loaded on the screen and the user has to exit out of all of them.

I have tried fiddling with the intent to fix this but I don't know where to start, I'm looking for some sort of function that can stop any on clicks from doing anything until the first one has loaded. I'll include the code for my method below.

        final ListView listView = root.findViewById(R.id.invoices_list);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent showDetailedInvoice = new Intent(getActivity(), DetailedInvoiceActivity.class);
                try {
                    Invoice invoice = new Invoice(invoices.getJSONObject(position));
                    showDetailedInvoice.putExtra("invoice", invoice);
                    showDetailedInvoice.putExtra("user", user);
                    startActivity(showDetailedInvoice);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

Solution

  • You have some approaches:

    1- Disabling items after the user clicks one time, so he can't click another one until the activity appears (so allowing just one)

    2- Controlling the clicks by time, for example one per second. You will need to save last time user clicked and compare the current time with that and check at least one second passed. Probably the activity will open before 1 second. To do this you can use System.currentTimeInMillis(), so you will have something like:

    private Long lastTimeUserClicked = null;
    
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Long clickTime = System.currentTimeInMillis();
        if(lastTimeUserclicked==null || clickTime - lasTimeUserClicked > 1000) { //1000 millisecs = 1 sec
          //Do your stuff ...
          lastTimeUserClicked = clickTime;   
        }
    }
    

    3- If the activity you are opening is only one and you change its data you can set the intent to be SingleTop with Intent flags:

    Intent showDetailedInvoice = new Intent(getActivity(), DetailedInvoiceActivity.class);
    
    showDetailedInvoice.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
    

    NOTE: Not sure if you will need clear top before. If it doesn't work with SINGLE_TOP only you can try to also add before

    showDetailedInvoice.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)