-1

Hello everyone in need to know what is the proper way of using the Async in tab Layout Activity.

In my task there a activity with two tabs.

Tab1 and Tab2

Tab1 Load data from server and show the data.

Tab2 Also load the another data from server and show the data in list view.

im using Async Task in tab1 and tab2 but the problem is when the activity started then the both Async Task class execute at same time that cause the error .

i need how to use it' sapratly when first tab fragment is visable then run the rirst Async Task and when second fragment is visable then run the 2nd Async Task one by one.

sunny
  • 179
  • 2
  • 14

3 Answers3

1

You can use both scenario :

1) You can call both AsyncTasks in your activity and show data in your both tabs.

2) As per issue

im using Async Task in tab1 and tab2 but the problem is when the activity started then the both Async Task class execute at same time that cause the error .

You should execute your AsyncTask in setUserVisibleHint()method which will call when your fragments completely visible.

Use:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    // TODO Auto-generated method stub
    super.setUserVisibleHint(isVisibleToUser);

    if (isVisibleToUser) {
      // execute your asynctask here
    }
}
Piyush
  • 18,895
  • 5
  • 32
  • 63
0

In my opinion, you'd better using only one Async Task to get data from server then handle with tabs one by one

Meo_3_the
  • 11
  • 1
  • 7
  • You could use a bus, for example with the [EventBus](https://github.com/greenrobot/EventBus) library. – manfcas Aug 02 '16 at 10:40
  • Try this http://stackoverflow.com/questions/12739909/send-data-from-activity-to-fragment-in-android and you can either use a bus or static variable – Meo_3_the Aug 02 '16 at 10:51
0

Add OnTabSelectedListener to your TabLayout

// run asynctask 1 first and then
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            if (tab.getPosition() == 0)
                // run asynctask 1
            else // run asynctask2
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });
faranjit
  • 1,567
  • 1
  • 15
  • 22