Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I created a tabbedlayout and i have three different fragments. however i would like to execute an async task in each of the fragments but i have failed to execute the async task within the fragment.

One of my fragments looks like this:

Java
package...................;

imports...........;

public class TabFragmentNews extends Fragment {
    private static final String ARG_EXAMPLE = "this_is_a_constant";
    private String example_data;

    public TabFragmentNews() {
    }

    public static TabFragmentNews newInstance(String example_argmument) {
        TabFragmentNews tabFragmentNews = new TabFragmentNews();
        Bundle args = new Bundle();
        args.putString(ARG_EXAMPLE, example_argmument);
        tabFragmentNews.setArguments(args);
        return tabFragmentNews;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        example_data = getArguments().getString(ARG_EXAMPLE);
        Log.i("Fragment created with ", example_data);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_news, container, false);
    }


        @Override
        public int getItemViewType(int position) {
            if (position == 0)
                return TYPE_HEAD;
            return TYPE_LIST;
        }
    }

<pre>    class BackgroundTask extends AsyncTask <.....>{
...................
.....................
        }


        class RecyclerViewHolder extends RecyclerView.ViewHolder {
            ..........................
...........................
        }

}

What I have tried:

I tried executing the Backgroundtask as below: I tried doing it as it would be down in a class activity.


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

//Executing Async Task(BackgroundTask)
BackgroundTask backgroundTask = new BackgroundTask(TabFragmentNews.this);
backgroundTask.execute();
}

but the IDE(Android studio) shows me errors.

Can you please help me on how the async task is executed within the class that extends a fragment?? thanks
Posted
Updated 4-Mar-16 22:48pm
v2
Comments
Richard MacCutchan 5-Mar-16 5:47am    
What errors?
Arindam Tewary 8-Mar-16 10:00am    
What error do you get? Any null exception ?
Arindam Tewary 8-Mar-16 10:01am    
Please refer here for an example of Async Task:
http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900