2017-05-15 1 views
0

JSON에서 데이터를 가져 오려고하는데 작동하지 않습니다. OnBindViewHolder는 ... 호출되지 않습니다RecycleView 메서드를 호출하지 않습니다.

어댑터 코드 :

public class AdapterRallye extends RecyclerView.Adapter<AdapterRallye.MyViewHolder> implements View.OnClickListener { 
    private Context context; 
    private View.OnClickListener listener; 
    private List<DataRallye> data; 


    public class MyViewHolder extends RecyclerView.ViewHolder { 

     public TextView Rallye_Nom; 
     public ImageView Rallye_Foto; 
     public TextView Rallye_Provincia; 
     public TextView Rallye_DataI; 
     public TextView Rallye_Tipus; 

     // create constructor to get widget reference 
     public MyViewHolder(final View itemView) { 
      super(itemView); 

      Rallye_Nom = (TextView) itemView.findViewById(R.id.tv_nom); 
      Rallye_Foto = (ImageView) itemView.findViewById(R.id.iv_foto); 
      Rallye_Provincia = (TextView) itemView.findViewById(R.id.tv_provincia); 
      Rallye_DataI = (TextView) itemView.findViewById(R.id.tv_datai); 
      Rallye_Tipus = (TextView) itemView.findViewById(R.id.tv_tipus); 
     } 
    } 

    // create constructor to innitilize context and data sent from MainActivity 
    public AdapterRallye(List<DataRallye> dadesrally) { 
     this.data = dadesrally; 
    } 

    // Inflate the layout when viewholder created 
    @Override 
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
     View view = LayoutInflater.from(context).inflate(R.layout.container_rallye, parent, false); 
     view.setOnClickListener(this); 


     return new MyViewHolder(view); 
    } 

    // Bind data 
    @Override 
    public void onBindViewHolder(MyViewHolder holder, int position) { 

     // Get current position of item in recyclerview to bind data and assign values from list 
     DataRallye current = data.get(position); 
     holder.Rallye_Nom.setText(current.getRallyeNom()); 
     holder.Rallye_Tipus.setText(current.getRallyeTipus()); 
     holder.Rallye_DataI.setText(current.getRallyeDataI()); 
     holder.Rallye_Provincia.setText(current.getRallyeProvincia()); 
     holder.Rallye_Provincia.setTextColor(ContextCompat.getColor(context, R.color.colorAccent)); 

     // load image into imageview using glide 
     Glide.with(context).load("http://rallyecat.esy.es/fotos/" + current.getRallyeFoto()) 
       .placeholder(R.drawable.rallyecatlogo) 
       .error(R.drawable.rallyecatlogo) 
       .into(holder.Rallye_Foto); 

    } 

    public void setOnClickListener(View.OnClickListener listener) { 
     this.listener = listener; 
    } 

    @Override 
    public void onClick(View view) { 
     if (listener != null) 
      listener.onClick(view); 
    } 

    // return total item from List 
    @Override 
    public int getItemCount() { 
     return data.size(); 
    } 


} 

조각 CODE : 나는 문제가 이미 해결 다른 StackOverflow의 게시물을 본 적이 있지만 봤는데

public class FragmentRally extends Fragment { 
    public FragmentRally() { 
     // Required empty public constructor 
    } 

    private List<DataRallye> llistarallyes = new ArrayList<>(); 
    private RecyclerView recyclerView; 
    private AdapterRallye mAdapter; 
    private Intent intent; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.fragment_fragment_rally, container, false); 

     recyclerView = (RecyclerView) rootView.findViewById(R.id.llistarallyes); 

     mAdapter = new AdapterRallye(llistarallyes); 

     recyclerView.setAdapter(mAdapter); 
     RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext()); 
     recyclerView.setLayoutManager(mLayoutManager); 
     recyclerView.setItemAnimator(new DefaultItemAnimator()); 


     new AsyncFetch().execute(); 

     mAdapter.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       intent = new Intent(getActivity(), ActivitatDetalls.class); 
       intent.putExtra("nombarra", llistarallyes.get(recyclerView.getChildAdapterPosition(view)).getRallyeNom()); 
       startActivity(intent); 
      } 
     }); 

     return rootView; 
    } 


    // CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds 
    public static final int CONNECTION_TIMEOUT = 10000; 
    public static final int READ_TIMEOUT = 15000; 

    private class AsyncFetch extends AsyncTask<String, String, String> { 
     ProgressDialog pdLoading = new ProgressDialog(getActivity()); 
     HttpURLConnection conn; 
     URL url = null; 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 

      //this method will be running on UI thread 
      pdLoading.setMessage("\tCarregant..."); 
      pdLoading.setCancelable(false); 
      pdLoading.show(); 

     } 

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

       // Enter URL address where your json file resides 
       // Even you can make call to php file which returns json llistarallyes 
       url = new URL("http://www.rallyecat.esy.es/Obtenir_events.php"); 

      } catch (MalformedURLException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
       return e.toString(); 
      } 
      try { 

       // Setup HttpURLConnection class to send and receive llistarallyes from php and mysql 
       conn = (HttpURLConnection) url.openConnection(); 
       conn.setReadTimeout(READ_TIMEOUT); 
       conn.setConnectTimeout(CONNECTION_TIMEOUT); 
       conn.setRequestMethod("GET"); 

       // setDoOutput to true as we recieve llistarallyes from json file 
       //conn.setDoOutput(true); 

      } catch (IOException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
       return e1.toString(); 
      } 

      try { 

       int response_code = conn.getResponseCode(); 

       // Check if successful connection made 
       if (response_code == HttpURLConnection.HTTP_OK) { 

        // Read llistarallyes sent from server 
        InputStream input = conn.getInputStream(); 
        BufferedReader reader = new BufferedReader(new InputStreamReader(input)); 
        StringBuilder result = new StringBuilder(); 
        String line; 

        while ((line = reader.readLine()) != null) { 
         result.append(line + "\n"); 
        } 

        // Pass llistarallyes to onPostExecute method 
        return (result.toString()); 

       } else { 
        Toast.makeText(getActivity(), "No hi ha connexió a internet.", 
          Toast.LENGTH_LONG).show(); 
        return ("No hi ha connexió a internet."); 
       } 

      } catch (IOException e) { 
       e.printStackTrace(); 
       return e.toString(); 
      } finally { 
       conn.disconnect(); 
      } 


     } 

     @Override 
     protected void onPostExecute(String result) { 

      //this method will be running on UI thread 
      pdLoading.dismiss(); 
      try { 
       JSONArray jArray = new JSONArray(result); 

       // Extract llistarallyes from json and store into ArrayList as class objects 
       for (int i = 0; i < jArray.length(); i++) { 
        JSONObject json_data = jArray.getJSONObject(i); 
        DataRallye dadesrallye = new DataRallye(); 
        dadesrallye.setRallyeNom(json_data.getString("nom")); 
        dadesrallye.setRallyeTipus(json_data.getString("tipus")); 
        dadesrallye.setRallyeDataI(json_data.getString("datai")); 
        dadesrallye.setRallyeProvincia(json_data.getString("provincia")); 
        dadesrallye.setRallyeFoto(json_data.getString("foto")); 
        llistarallyes.add(dadesrallye); 
       } 

      } catch (JSONException e) { 
       Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show(); 
      } 

     } 

    } 

    public static class ViewHolder extends RecyclerView.ViewHolder { 
     public ViewHolder(LayoutInflater inflater, ViewGroup parent) { 
      super(inflater.inflate(R.layout.fragment_fragment_rally, parent, false)); 
      itemView.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        Context context = v.getContext(); 
        Intent intent = new Intent(v.getContext(), ActivitatDetalls.class); 
        context.startActivity(intent); 
       } 
      }); 
     } 
    } 
} 

사용자가 말한 솔루션을 많이 시도했지만 아무도 작동하지 않습니다 ...

감사합니다!

답변

0

mAdapter.notifyDataSetChanged();을 (를) onPostExecute() 메소드로 호출 해보십시오.

변경 한 후 어댑터에 알릴 필요가 있습니다.

+0

절반으로 해결 한 것처럼 보였습니다. 이제 충돌이 발생하여 컨텍스트가 null입니다. –

+0

@FranB. 질문에 오류 로그를 기록하십시오. 이것은 다른 오류입니다. –

+0

그건 내 잘못이야, 내가 null 컨텍스트를 호출했다, 내가 사용하지 않는 코드를 삭제하고, 지금은 작동합니다! 고마워! –

관련 문제