嗨,我在 Fragment 中有 AsyncTask,它从 JSON 字符串获取图像 url。现在我想把它们放到一个gridview中。我可以在 Activity 上执行此操作,但不能在 Fragment 中执行此操作。有人可以帮我解决吗?
我在这里发布了类似的问题:implement AsyncTask in Fragment android。并找到了在片段中使用 asynctask 的答案,但不是 GridView。
我的代码:
public class SalesFragment extends Fragment {
GridView gridView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View gv = inflater.inflate(R.layout.hot_sales, null);
gridView = (GridView) gv.findViewById(R.id.grid_view);
bindGridview();
return gv;
}
public void bindGridview() {
new MyAsyncTask(getActivity(),gridView).execute("");
}
class MyAsyncTask extends AsyncTask<String, String, String> {
GridView mGridView;
Activity mContext;
Response response;
public MyAsyncTask(Activity context,GridView gview) {
this.mGridView=gview;
this.mContext=context;
}
protected String doInBackground(String... params) {
if(file.exists()) {
try{
//Parsing data
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (@SuppressWarnings("hiding") IOException e){
e.printStackTrace();
}
}else{
System.out.println("Error");
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(Sales sales : this.response.sales){
HashMap<String, String> hm = new HashMap<String,String>();
if (sales.Categories1){
//Fetching the data
}
}
}
}
}
}
}