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:
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