在 Fragment android 中实现 AsyncTask [英] implement AsyncTask in Fragment android

查看:32
本文介绍了在 Fragment android 中实现 AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个活动,它以列表的形式输出 json 数据.但现在我想在一个片段中实现它.在这个片段中,我想将其视为 gridview.并且这两个文件都可以正常工作.但是当我尝试实现 AsyncTask 时,我得到了几个红旗作为无法访问的代码.有人可以帮我吗?

I've an activity which output json data from as a list. But now I want to implement it in a fragment. In this fragment I want to view it as gridview. And both files works fine. but when I tried to implement AsyncTask I gets several redflags as unreachable code. Can someone help me with this please?

    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));
                             }
                    }
                }



           }
        }
    }

如何将图像调用到上图的 gridview 中?请帮忙.

How to call images into gridview on above image? Please help.

推荐答案

在片段中创建异步任务很容易

There is easy step to crate asyntask within fragment

在您的片段中将代码放在 activityCreateview

in your fragment place code on activityCreateview

new MyAsyncTask(getActivity(), mListView).execute("");

getActivity() 是与片段和活动通信的方法

getActivity() is method to communicate with fragment and activity

在 asynstak 上发布

in asynstak on post

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>();

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

fill array list with required data then

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
   }

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

use hash map in adapter and assign images with position set data and fetch value from model

这篇关于在 Fragment android 中实现 AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆