0

I have to populate an activity with up to 100 different fragments to iterate through all fragments i am using a for loop, but instead of it adding a fragment one by one it adds all the fragments at once. till that happens app freezes, sometimes it freezes for 4-5 seconds. How to load them one by one? Heres what i have done till now...

for (i = 0; i < combofinalist.size(); i++) {
    Bundle c = new Bundle();
    fm = getSupportFragmentManager();
    ft = fm.beginTransaction();
    combofrag combofrag = new combofrag();
    int fragdata = combofinalist.get(i);
    c.putInt("combonum", fragdata);
    c.putInt("editable", 1);
    combofrag.setArguments(c);
    ft.replace(combolayouts[y], combofrag, "combo" + y);
    y = y + 1;
    ft.commit();
}
HiDeoo
  • 10,353
  • 8
  • 47
  • 47
VaibhaV Deshmukh
  • 109
  • 1
  • 11

2 Answers2

0

Put delay after replacing fragment

You can use Handler to put delay

Akshay Panchal
  • 695
  • 5
  • 15
0

Try running a new thread for each addition:

fm = getSupportFragmentManager(); 
for (i = 0; i < combofinalist.size(); i++) { 
    new Thread(new Runnable() {
        @Override
        public void run() {
            ft = fm.beginTransaction(); 
            combofrag combofrag = new combofrag();
            int fragdata = combofinalist.get(i);
            Bundle c = new Bundle();
            c.putInt("combonum", fragdata);
            c.putInt("editable", 1);
            combofrag.setArguments(c);
            ft.replace(combolayouts[y], combofrag, "combo" + y);
            y = y + 1; 
            ft.commit(); 
        }
    }).run();
} 

EDIT

After reading through the FragmentManager.class the notes on commit() state:

/**
     * After a {@link FragmentTransaction} is committed with
     * {@link FragmentTransaction#commit FragmentTransaction.commit()}, it
     * is scheduled to be executed asynchronously on the process's main thread.
     * If you want to immediately executing any such pending operations, you
     * can call this function (only from the main thread) to do so.  Note that
     * all callbacks and other related behavior will be done from within this
     * call, so be careful about where this is called from.
     *
     * @return Returns true if there were any pending transactions to be
     * executed.
     */

As it is being scheduled I can only assume all transactions are being committed at once. You can try adding a delay to the Thread or if you have access to the Context can try runOnUiThread(). Can't imagine that will be great for performance though.

danieltnbaker
  • 181
  • 1
  • 1
  • 7