11

Mam aktywność, która wyprowadza dane json z listy. Ale teraz chcę go wdrożyć w pewien fragment. W tym fragmencie chcę wyświetlić go jako widok siatki. Oba pliki działają dobrze. ale gdy próbowałem zaimplementować AsyncTask, otrzymuję kilka czerwonych znaczników jako nieosiągalny kod. Czy ktoś może mi w tym pomóc?implementacja AsyncTask w Fragmentach android

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



      } 
     } 
    } 

Jak wywołać obrazy w gridview na powyższym zdjęciu? Proszę pomóż.

+1

Być może zamieścić jakiś kod? Może to spowodować dowolna liczba problemów. – blaffie

+1

opublikuj swój zaimplementowany kod tutaj ............ – Piyush

+0

@ Piyush Gupta & blaffie: kod dodany teraz. Chcę zrobić to samo, co działalność fragmentaryczna. – Kabe

Odpowiedz

20

Jest łatwy krok do skrzyni asyntask wewnątrz fragmentu

w swojej fragmentu kodu miejsce na activityCreateview

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

getActivity() jest metoda komunikowania się z fragmentem i aktywności

w asynstak na stanowisku

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

tu jest

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

przed pobierania danych sprawiają, że modelowanie jak listy tablicy

public class ImageModel 
    { 
     String title; 
     String img; 
    } 


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

napełnić wymaganych danych następnie

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 
    } 

użytku mapie hash w adapterze i przypisać obrazy z pozycji ustaw dane i pobierz wartość z modelu

+0

Dzięki. Twój kod pomógł mi w odpowiedzi na moje pytanie, ale teraz mam nowy problem. Jak mogę nazwać "shop_image" widokiem gridview? Edytowałem mój post, patrz powyższy kod. – Kabe

+0

można przekazać obraz lub wiele obrazów w konstruktorze adaptera, który edytowałem kod, patrz powyżej –

+0

to nie działa. uzyskiwanie redflags w mcontext i ImageAdapter. – Kabe

Powiązane problemy