implement AsyncTask in Fragment android
Asked Answered
B

1

11

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?

Edited: New

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



           }
        }
    }

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

Borrego answered 1/9, 2013 at 11:44 Comment(4)
Perhaps post some code? Any number of problems can cause this.Renal
post your implemented code here............Leong
@ Piyush Gupta & blaffie: the code added now. I want to do the same thing as activity in fragment.Borrego
@Borrego so means Like in SalesActivity the functions which are performed,YOu want to it Fragment?Leong
S
24

There is easy step to crate asyntask within fragment

in your fragment place code on activityCreateview

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

getActivity() is method to communicate with fragment and activity

in asynstak on post

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

here is

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

before fetching data make it model like

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

Slideaction answered 2/9, 2013 at 5:45 Comment(5)
Thanks. Your code helped for my question, but now I've new issue. How could I call 'shop_image' to a gridview? I edited my post, Please see above code.Borrego
you can pass image or multiple images in constructor of adapter i have edited the code see aboveSlideaction
it's not worked. getting redflags on mcontext and ImageAdapter.Borrego
@Sumeetkumar @Borrego I cant use mContext.mGridView.setAdapter() there is no mGridView in mContext obviously. How should I deel with it?Untoward
This code is great! But I am not sure its going to work without having leak memory (OOM) error, because you are using a non static inner class (which is MyAsyncTask) inside a fragment. I recommend you try static inner class and pass context, gridView to contructor using weakReferenceFroh

© 2022 - 2024 — McMap. All rights reserved.