JSON请求返回null

时间:2016-10-30 10:41:09

标签: java android mysql android-fragments android-volley

我在Android上使用Volley库但是当我创建JSONArrayRequest时,它会自动返回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);
    }
}
}

1 个答案:

答案 0 :(得分: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);
}

在你的片段中,你需要一个setter方法。只有在调用它时才应该呈现列表:

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

}