1

내 문제는 AsyncTask에서 데이터를 생성 할 수 있지만 데이터를 onCreateView로 다시 전송할 수 없다는 것입니다. 이것은 파편에 대한 첫 번째 다이빙입니다. 죄송합니다. 코드가 추한 경우,이 코드를 작동 시키려하고 있습니다. 또한 Android 프로그래밍을 처음 접해 보았습니다. 어리석은 실수를 저지른 경우 미안해합니다. 글로벌 변수를 게시해야하는지 잘 모르겠습니다. 그리고 내 변수의 일부가 이상하게 명명 된 것을 알고 있습니다.Asyncctask의 데이터가 RecyclerView의 onCreateView로 넘어 가지 않습니다.

onCreateView 부

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    View view = inflater.inflate(R.layout.fragment_news, 
      container, false); 
    pb = (ProgressBar) getActivity().findViewById(R.id.progressBar2); 
    gv = (RecyclerView) view.findViewById(R.id.expandableListView); 
    swp = (SwipeRefreshLayout) getActivity().findViewById(R.id.activity_main_swipe_refresh_layout); 

    gv.setHasFixedSize(true); 
    LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); 
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL); 
    gv.setLayoutManager(layoutManager); 

    swp.setEnabled(false); 

    hadapter = new NewsExpandableAdapter(getActivity(), m_hparts); 

    System.out.println(m_hparts.size()); 
    gv.setAdapter(hadapter); 
    return view; 
} 

RecyclerView 어댑터

public class NewsExpandableAdapter extends RecyclerView.Adapter<NewsExpandableAdapter.ViewHolder> { 

    private Context context; 

    public static class ViewHolder extends RecyclerView.ViewHolder { 
     public TextView nameTextView; 
     public ImageView messageButton; 

     public ViewHolder(View itemView) { 
      super(itemView); 

      nameTextView = (TextView) itemView.findViewById(R.id.title); 
      messageButton = (ImageView) itemView.findViewById(R.id.image); 
     } 
    } 

    private ArrayList<Model> mContacts; 

    public NewsExpandableAdapter(Context c, ArrayList<Model> contacts) { 

     this.context = c; 
     mContacts = (ArrayList<Model>) contacts; 
    } 

    @Override 
    public NewsExpandableAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
     Context context = parent.getContext(); 
     LayoutInflater inflater = LayoutInflater.from(context); 

     View contactView = inflater.inflate(R.layout.expandable_list_item, parent, false); 

     ViewHolder viewHolder = new ViewHolder(contactView); 
     return viewHolder; 
    } 

    @Override 
    public void onBindViewHolder(NewsExpandableAdapter.ViewHolder viewHolder, int position) { 
     Model contact = mContacts.get(position); 

     TextView textView = viewHolder.nameTextView; 
     textView.setText(contact.getTitle()); 

     ImageView image= viewHolder.messageButton; 

     Picasso.with(viewHolder.itemView.getContext()) 
       .load(contact.getLink()) 
       .into(image); 


    } 

    @Override 
    public int getItemCount() { 
     return mContacts.size(); 
    } 
} 

단편 XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="com.example.sample"> 

    <android.support.v7.widget.RecyclerView 
     android:layout_width="match_parent" 
     android:layout_height="100dp" 
     android:id="@+id/expandableListView"> 
    </android.support.v7.widget.RecyclerView> 

</RelativeLayout> 

RecyclerView의 XML

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:padding="8dp"> 


    <ImageView 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:id="@+id/image"/> 

    <TextView 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:id="@+id/title"/> 

</LinearLayout> 

AsyncTask를

public class Directory extends AsyncTask<Void, Void, String> { 
     String desc; 

     @Override 
     protected String doInBackground(Void... params) { 

      try { 
       Document document = Jsoup.connect(url + dateFormatYear.format(date)).get(); 

       listing_latest = document.select(".title.page_title"); 

       for (Element listing0 : listing_latest) { 

        Element hmonth = listing0.select("h3").first(); 
        if(hmonth.text().equals(dateFormatMonth.format(date))){ 
         month = hmonth.text(); 
         hname = hmonth.parent().parent().parent().nextElementSibling(); 
         releaseList = hname.select(".base_header.tc.m6"); 
         for(Element block : releaseList){ 
          name = block.select(".one_line.fs11 a").first(); 
          image = block.select(".base_inner.h244.loading a img").first(); 
          if(name != null){ 
           hn = name.attr("title"); 
          } 
          if(image != null){ 
           hi = image.attr("abs:src"); 
          } 
          m_hparts.add(new Model(hi)); 
         } 
        } 
       } 
      } catch (IOException e1) { 
       e1.printStackTrace(); 
      } 
      return null; 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      super.onPostExecute(result); 
      hadapter.notifyDataSetChanged(); 
      m_hparts.add(new Model(hi)); 
     } 
    } 

편집 : 나는 데이터를 가져올 수 없습니다 아직도 onCreate()new Directory().execute();을 넣어.

+0

내 편집을 참조, 나는 유지하지 않는'onPostExecute' – Asker

+0

에 편집을 추가 조각에있는 활동의 개체 : "pb"및 "swp". 단편은 다른 활동으로 재사용 할 수 있습니다. 필요한 경우 getActivity()를 호출하여 해당 객체가 필요한 위치에 놓습니다. 경우에 따라 getActivity는 null을 반환 할 수 있습니다 (단편이 활동에서 분리 된 경우). 또는 onAttach (활동 활동)에서 pb 및 swp에 쓸 수 있으며 onDetach()에서 null로 설정할 수 있습니다. – babay

답변

3

새 항목을 모두 데이터 소스에 추가 한 다음 데이터 소스가 업데이트 된 후에 notifyDataSetChanged()을 호출해야합니다.

doInBackground()의 반환 값을 상품 목록으로 설정하고 onPostExecute()으로 반환하십시오. AsyncTask 제네릭의 매개 변수를 변경해야하고 onPostExecute()에 전달 된 매개 변수도 변경해야합니다.

List<Model> m_hparts = new ArrayList<>(); 

당신은 같은 것을 할 수있는 : 데이터 소스를 가정

다음과 같습니다

public class Directory extends AsyncTask<Void, Void, List<Model>> { 
    String desc; 

    @Override 
    protected List<Model> doInBackground(Void... params) { 
     //added: 
     List<Model> parts = new ArrayList<>(); 

     try { 
      Document document = Jsoup.connect(url + dateFormatYear.format(date)).get(); 

      listing_latest = document.select(".title.page_title"); 

      for (Element listing0 : listing_latest) { 

       Element hmonth = listing0.select("h3").first(); 
       if(hmonth.text().equals(dateFormatMonth.format(date))){ 
        month = hmonth.text(); 
        hname = hmonth.parent().parent().parent().nextElementSibling(); 
        releaseList = hname.select(".base_header.tc.m6"); 
        for(Element block : releaseList){ 
         name = block.select(".one_line.fs11 a").first(); 
         image = block.select(".base_inner.h244.loading a img").first(); 
         if(name != null){ 
          hn = name.attr("title"); 
         } 
         if(image != null){ 
          hi = image.attr("abs:src"); 
         } 
         //m_hparts.add(new Model(hi)); 
         //do this instead: 
         parts.add(new Model(hi)); 
        } 
       } 
      } 
     } catch (IOException e1) { 
      e1.printStackTrace(); 
     } 
     //return null; 
     //do this instead: 
     return parts; 
    } 

    @Override 
    protected void onPostExecute(List<Model> parts) { 
     super.onPostExecute(result); 
     for (Model h: parts) { 
      m_hparts.add(h); 
     } 

     hadapter.notifyDataSetChanged(); 
    } 
} 
관련 문제