Stole51
Stole51

Reputation: 69

AsyncTask starts again on tab change with SherlockFragments

I have MainActivity which extends SherlockFragmentActivity and two tabs with SherlockFragment. These two tabs have ListView populated by AsyncTask. It all works fine but whenever I switch from tab to tab, AsyncTask triggers again and I want to start it only once.

Here is my MainActivity:

public class MainActivity extends SherlockFragmentActivity {

    private FragmentTabHost mTabHost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.tabcontent);
        mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Tab1"),Tab1.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Tab2"),Tab2.class, null);

}

and here is Tab1:

public class Tab1 extends SherlockFragment {


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.tab1, container, false);
        return v;

    }

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

            new FetchData().execute();

    }

    public class FetchData extends AsyncTask<String, String, String> {
    .....
    }

}

Tab2 contains similar code, just with different mysql select. Everything works fine, data is populated on ListView but each time I switch from tab1 to tab2, AsyncTask triggers again :/ Please help ...

Upvotes: 1

Views: 704

Answers (2)

Stole51
Stole51

Reputation: 69

I solved the problem by downloading all data and storing in local sqlite. That way, there is no need for AsyncTask in each fragment.

Cheers!

Upvotes: 0

Firefly
Firefly

Reputation: 124

The onStart method is called each time a fragment become visible, e.g. when you switch tabs

Source: Android fragment life cycle

I suggest you move:

new FetchData().execute();

into the onCreateView method.

Upvotes: 1

Related Questions