在Android Fragment中实现AsyncTask

11

我有一个活动,它将数据作为列表输出为JSON格式。但现在我想在一个片段中实现它。 在这个片段中,我想将其以网格视图的形式显示。两个文件都能正常工作。但是当我尝试实现AsyncTask时,会出现几个无法访问的代码的错误标志。请问有人可以帮我吗?

编辑:新的

    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)  {

               File file = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/sample.txt");
                if(file.exists()) {
                    try{
                           Reader inputStreamReader = new InputStreamReader(new FileInputStream(file));

                           Gson gson = new Gson();
                           this.response = gson.fromJson(inputStreamReader, Response.class);
                        } 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.getCategories1().contains("12")){
                        //hm.put("sale_title", "" + sales.getShort_title());
                        for(Shop shop : this.response.shops){
                            String image_file = new String( Environment.getExternalStorageDirectory().getAbsolutePath()
                                    + "/images/" + shop.getImage());
                            if(shop.getId().equals(sales.getShop_id())){
                                hm.put("shop_image", image_file );
                                System.out.println(shop_image);
                            }
                        }

                  if(hm.size()>0){
                        gridView.setAdapter(new ImageAdapter(MainActivity.this,R.layout.grid_layout , imgArray, titleArray));
                             }
                    }
                }



           }
        }
    }

如何在图像上方调用图像并将其放入网格视图中?请帮忙。


1
也许可以发布一些代码?任何数量的问题都可能导致这种情况。 - blaffie
1
请在此处发布您实现的代码。 - Piyush
@ Piyush Gupta和blaffie:现在添加了代码。我想在片段中执行相同的操作。 - Kabe
@Kabe,所以意思是在SalesActivity中执行的功能,您想将其放入Fragment中吗? - Piyush
1个回答

24

在片段中创建Asynctask有简单的步骤

在你的片段中,在onCreateView方法中加入代码

new MyAsyncTask(getActivity(), mListView).execute("");
< p > getActivity() 是一个用于在异步任务中与 Fragment 和 Activity 进行通信的方法。

< p >在 asynctask 中使用。

context.mListView.setArrayAdapter(...........)

这里是

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;
        //return super.onCreateView(inflater, container, savedInstanceState);
    }

public void bindGridview()
{

   new MyAsyncTask(getActivity(), gridView).execute("");
}

class MyAsyncTask extends AsyncTask<String, String, String>
{
    GridView mGridView;
    Activity mContex;
   public  MyAsyncTask(Activity contex,GridView gview)
    {
     this.mGridView=gview;
     this.mContex=contex;
    }

   protected String doInBackground(String... params)
    {

       //fetch data
    }

   @Override
    protected void onPostExecute(String result) {
      {   

        for(Sales sales : this.response.sales){
            HashMap<String, String> hm = new HashMap<String,String>();

            if (sales.getCategories1().contains("12")){
                //hm.put("sale_title", "" + sales.getShort_title());
                for(Shop shop : this.response.shops){
                    String image_file = new String(        Environment.getExternalStorageDirectory().getAbsolutePath()
                            + "/images/" + shop.getImage());
                    if(shop.getId().equals(sales.getShop_id())){
                        hm.put("shop_image", image_file );
                        System.out.println(shop_image);
                    }
                }
            }
        }
               if(hm.size()>0)
              mcontext.mGridView.setAdapter(new ImageAdapter(mContext),hm);
      }

在获取数据之前,将其建模

public class ImageModel
    {
        String title;
        String img;
    }


ArrayList<ImageModel> arrayList=new ArrayList<ImageModel>();

用所需的数据填充数组列表,然后

mcontext.mGridView.setAdapter(new ImageAdapter(mContext),hm,arrayList);

//in image adapter

public class ImageAdapter extends ArrayAdapter<String> {

public ImageAdapter(Context context, HashMap<String, String> hm,ArrayList<ImageModel> images ) 
        {
            super(context, R.layout.activity_t);

        }
//--code
   }

在适配器中使用哈希映射,并根据位置分配图像,设置数据并从模型获取值。


1
谢谢。你的代码对我的问题有所帮助,但现在我又遇到了新问题。我该如何将“shop_image”调用到网格视图中?我已经编辑了我的帖子,请查看上面的代码。 - Kabe
你可以在适配器的构造函数中传递图像或多个图像。我已经编辑了代码,请参见上文。 - Sumeet kumar
1
它没有工作。在mcontext和ImageAdapter上出现了红旗。 - Kabe
1
@Sumeetkumar @Kabe 我不能在mContext中使用mGridView.setAdapter(),因为显然mContext中没有mGridView。我该怎么处理? - pavelartlover
这段代码很好!但我不确定它是否会在没有泄漏内存 (OOM) 错误的情况下工作,因为你在片段中使用了一个非静态的内部类 (即 MyAsyncTask)。我建议你尝试使用静态内部类,并使用弱引用将上下文和 gridView 传递给构造函数。 - Long Luong

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接