2016-10-30 2 views
0

Android에서 발리 라이브러리를 사용하고 있지만 JSONArrayRequest를 만들면 null이 자동으로 반환됩니다. 하지만 디버깅을 계속하면 두 번째 시도에서 배열을 채 웁니다. 여기 내 코드는 다음과 같습니다JSON 요청에서 null을 반환합니다.

BackgroundTask.java

public class BackgroundTask{ 

    Context context; 
    ArrayList<Dua> arrayList = new ArrayList<>(); 
    String json_url = "http://www.burakakyalcin.site/getDua.php"; 

    public BackgroundTask(Context context){ 
     this.context = context; 
    } 

    public ArrayList<Dua> getList(){ 
     JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, json_url, (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); 
         Dua dua = new Dua(jsonObject.getString("DuaId"),jsonObject.getString("DuaSender"),jsonObject.getString("DuaHeader"), 
          jsonObject.getString("DuaText"),jsonObject.getString("DuaLike")); 
         arrayList.add(dua); 
         count++; 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 
       } 
      } 
     }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
       Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show(); 
       error.printStackTrace(); 
      } 
     }); 
     MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest); 
     return arrayList; 
    } 

} 

MyFragment.java

public class MyFragment extends Fragment{ 

    RecyclerView recyclerView; 
    RecyclerView.Adapter adapter; 
    RecyclerView.LayoutManager layoutManager; 
    ArrayList<Dua> arrayList = new ArrayList<>(); 

    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.fragment_my, container, false); 
     recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview); 
     layoutManager = new LinearLayoutManager(getActivity().getApplicationContext()); 
     recyclerView.setHasFixedSize(true); 
     BackgroundTask backgroundTask = new BackgroundTask(getActivity().getApplicationContext()); 
     arrayList = backgroundTask.getList(); 
     adapter = new RecyclerAdapter(arrayList); 
     recyclerView.setAdapter(adapter); 
     return rootView; 
    } 


} 

RecyclerAdapter.java

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

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

public RecyclerAdapter(ArrayList<Dua> arrayList){ 
    this.arrayList = arrayList; 
} 


public void setArrayList (ArrayList<Dua> arrayList){ 
    this.arrayList=arrayList; 
    notifyItemRangeChanged(0, arrayList.size()); 
} 

@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.DuaSender.setText(arrayList.get(position).getDuaSender()); 
    holder.DuaHeader.setText(arrayList.get(position).getDuaHeader()); 
    holder.DuaLike.setText(arrayList.get(position).getDuaLike()); 
} 

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

public static class MyViewHolder extends RecyclerView.ViewHolder{ 

    TextView DuaHeader, DuaSender, DuaLike; 

    public MyViewHolder(View itemView) { 
     super(itemView); 
     DuaHeader = (TextView) itemView.findViewById(R.id.duaHeaderRec); 
     DuaSender = (TextView) itemView.findViewById(R.id.duaSenderRec); 
     DuaLike = (TextView) itemView.findViewById(R.id.duaLikeRec); 
    } 
} 
} 
+0

첫 번째 호출에서 null이 반환되고 확실하지 않은 것은 확실합니까? –

+0

@AlexeySoshin 그렇습니다. 빈 목록을 반환합니다. – Burak

답변

2

JsonArrayRequest은 비동기입니다.

모든의

arrayList = backgroundTask.getList(); 

먼저 호출 할 때 빈 목록을 얻을 것이다 :

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

만,이 채워집니다이 성공 HTTP 호출 후를. 따라서 기본적으로 결과를 기다리기 전에 사용해야합니다.

public class BackgroundTask{ 

Context context; 
Fragment fragment; 
ArrayList<Dua> arrayList = new ArrayList<>(); 
String json_url = "http://www.burakakyalcin.site/getDua.php"; 

public BackgroundTask(Context context, MyFragment fragment){ 
    this.context = context; 
    this.fragment = fragment; 
} 

public void getList(){ 
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, json_url, (String)null, new Response.Listener<JSONArray>() { 
     @Override 
     public void onResponse(JSONArray response) { 
       // Map the JSON as you did before 

       // Call your fragment 
       fragment.setList(arrayList); 
     } 
    }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
      Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show(); 
      error.printStackTrace(); 
     } 
    }); 

    MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest); 
} 

조각에는 세터 방법이 필요합니다. 호출 될 때만 목록을 렌더링해야합니다.

public class MyFragment extends Fragment{ 
RecyclerView recyclerView; 
RecyclerView.Adapter adapter; 
RecyclerView.LayoutManager layoutManager; 
ArrayList<Dua> arrayList = new ArrayList<>(); 
@Nullable 
@Override 
public View onCreateView(LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.fragment_my, container, false); 


    recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview); 
    layoutManager = new LinearLayoutManager(getActivity().getApplicationContext()); 
    recyclerView.setHasFixedSize(true); 

    BackgroundTask backgroundTask = new BackgroundTask(getActivity().getApplicationContext(), this); 


    return rootView; 
} 

public void setList(List<Dua> list) { 
    adapter = new RecyclerAdapter(list); 
    recyclerView.setAdapter(adapter); 
} 

} 
+0

좋은 점은 고맙지 만, 처음에는 JSON 배열 요청을 만들 때 오류가 발생합니다. 자동으로 arrayList를 반환하도록 점프합니다.이 배열은 비어 있어도 onError 또는 onResponse 메서드로 이동하지 않습니다. Fragment에 rootview를 반환 한 후 배열을 채 웁니다. 그것이 채워지면 아무 일도 일어나지 않습니다. – Burak

+0

코드에 "return arrayList"가 없어야합니다. 제 예제를 다시 확인하고 솔루션에 통합 해보십시오. –

+0

이제 "E/RecyclerView : 어댑터가 연결되지 않았으며 레이아웃을 건너 뛰고 있습니다."오류가 발생합니다. RecyclerAdapter 클래스를 질문에 추가했습니다. – Burak

관련 문제