以下代码既未显示任何错误,也未提供任何输出。实际上,它似乎并没有进入onResponse(String response)
方法内部。我用来执行PHP代码的URL正常运行,当我在浏览器中加载它时,它会为我提供JSON输出。
我使用一种通用方法通过在println
内放置onResponse(String response)
来检查是否在上述函数中,但是它从未在控制台中提供任何输出。
public class FragmentE extends Fragment {
View view;
private static final String URL_PRODUCTS= "http://hostname.com/appapi.php";
//a list to store all the products
List<Product> productList;
//the recyclerview
RecyclerView recyclerView;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstance) {
view = inflater.inflate(R.layout.fragment_e, container, false);
recyclerView= (RecyclerView) view.findViewById(R.id.recylcerViewE);
// recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
productList = new ArrayList<>();
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject product = array.getJSONObject(i);
//adding the product to product list
productList.add(new Product(
product.getInt("id"),
product.getString("title"),
// product.getString("shortdesc"),
// product.getDouble("rating"),
product.getDouble("price"),
product.getString("image")
));
}
//creating adapter object and setting it to recyclerview
ProductsAdapter adapter = new ProductsAdapter(getActivity(), productList);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(getActivity()).add(stringRequest);
return view;
}
}