2016-12-17 2 views
0

Я пытаюсь получить массив JSON с помощью Android Volley, но мой RecyclerView не отображает данные. recyclerView пуст. Я проверил свой URL, нет проблем.RecyclerView не показывает данные из массива JSON после разбора

BackgroundTask.java

public class BackgroundTask { 

    Context context; 
    String jsonURL = "my url"; 
    ArrayList<Contact> arrayList = new ArrayList<>(); 

    public BackgroundTask(Context ctx){ 

     this.context = ctx; 
    } 

    public ArrayList<Contact> getList(){ 

     final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, jsonURL, (String) null, 
       new Response.Listener<JSONArray>() { 
        @Override 
        public void onResponse(JSONArray response) { 
         int count = 0; 
         while (count > response.length()){ 
          try { 
           JSONObject jsonObject = response.getJSONObject(count); 
           Contact contact = new Contact(jsonObject.getString("Name"),jsonObject.getString("Email")); 
           arrayList.add(contact); 
           count++; 

          } catch (JSONException e) { 

           Toast.makeText(context,"Error",Toast.LENGTH_SHORT).show(); 
           e.printStackTrace(); 
          } 
         } 

        } 
       }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 

      } 
     } 
     ); 
     Singletone.getSingletone(context).addToRequest(jsonArrayRequest); 
     return arrayList; 
    } 
} 

MySingletone.java

public class Singletone { 

    private static Singletone singletone; 
    private RequestQueue requestQueue; 
    private static Context context; 

    private Singletone(Context ctx){ 
     context = ctx.getApplicationContext(); 
     requestQueue = getRequestQueue(); 
    } 

    public RequestQueue getRequestQueue(){ 

     if(requestQueue == null){ 
      requestQueue = Volley.newRequestQueue(context); 
     } 
     return requestQueue; 
    } 

    public static synchronized Singletone getSingletone(Context ctx){ 

     if(singletone == null){ 
      singletone = new Singletone(ctx.getApplicationContext()); 
     } 

     return singletone; 
    } 

    public<T> void addToRequest(Request<T> request){ 

     requestQueue.add(request); 
    } 

} 

RecyclerAdapter.java

public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.MyViewHolder> { 

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

    public RecycleAdapter(ArrayList<Contact> array){ 

     this.arrayList = array; 
    } 

    @Override 
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 

     View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item,parent,false); 
     MyViewHolder myViewHolder = new MyViewHolder(view); 
     return myViewHolder; 
    } 

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

     holder.Name.setText(arrayList.get(position).getName().toString()); 
     holder.Email.setText((arrayList.get(position).getEmail().toString())); 

    } 

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


    public static class MyViewHolder extends RecyclerView.ViewHolder{ 

     TextView Name, Email; 
     public MyViewHolder(View itemView) { 
      super(itemView); 

      Name = (TextView) itemView.findViewById(R.id.txt_name); 
      Email = (TextView) itemView.findViewById(R.id.txt_email); 
     } 
    } 
} 

ответ

1

запрос асинхронный. Вы не можете просто вернуть ArrayList от getList. Вы должны заполнить RecyclerView внутри метода обратного вызова onResponse по телефону adapter.notifyDataSetChanged().

Также ваша петля while никогда не запускается, потому что count никогда не превышает response.length();

@Override 
public void onResponse(JSONArray response) { 
    if(response != null && response.length() > 0){ 
     for (int count = 0; count < response.length(); count++) { 
      try { 
       JSONObject jsonObject = response.getJSONObject(count); 
       Contact contact = new Contact(jsonObject.getString("Name"), jsonObject.getString("Email")); 
       arrayList.add(contact); 
      } catch (JSONException e) { 
       Toast.makeText(context,"Error",Toast.LENGTH_SHORT).show(); 
       e.printStackTrace(); 
      } 
     } 
     yourAdapter.notifyDataSetChanged(); 
    } 
} 
+0

большое спасибо ... проблема был в состоянии цикла ... –

+0

как вызвать adpter.notifyDataSetChanged внутри onResponse()? –

+0

Как вызвать adpter.notifyDataSetChanged внутри onResponse()? мой объект адаптера внутри другого действия, и я вызываю BackgroundTask из этой активности. Спасибо. –

0

Вам необходимо позвонить notifyDataSetChanged(); после обновления arrayList

1

Попробуйте это изменить:

int count = 0; 
while (count > response.length()){ 
    try { 
     JSONObject jsonObject = response.getJSONObject(count); 
     Contact contact = new Contact(jsonObject.getString("Name"),jsonObject.getString("Email")); 
     arrayList.add(contact); 
     count++; 

    } catch (JSONException e) { 

     Toast.makeText(context,"Error",Toast.LENGTH_SHORT).show(); 
     e.printStackTrace(); 
    } 
} 

в

for(int count=0;count<response.length();count++){ 
    try { 
     JSONObject jsonObject = response.getJSONObject(count); 
     Contact contact = new Contact(jsonObject.getString("Name"),jsonObject.getString("Email")); 
     arrayList.add(contact); 

    } catch (JSONException e) { 

     Toast.makeText(context,"Error",Toast.LENGTH_SHORT).show(); 
     e.printStackTrace(); 
    } 
} 
+0

Спасибо .. проблема была в то время как условие цикла ... –

+0

@SabirHossain вы всегда можете ... не забудьте upvote или принять ответ – rafsanahmad007