我有一个来自url的json
数据,我想从中使用volley库获取文本数据。我还有一个片段,其中将显示数据。
在获取数据后,Volley给了我一个错误,我不知道出了什么问题。
onErrorResponse
函数被一次又一次地调用,并显示toast消息 - 出错了。
这是Fragment.java
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment, container, false);
final TextView textView = view.findViewById(R.id.event_text);
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Config.events_server, (String) null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
textView.setText(response.getString("trending"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(view.getContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
MySingleton.getmInstance(view.getContext()).addToRequestQueue(jsonObjectRequest;
return view;
}
和MySingleton.java
public class MySingleton {
private static MySingleton mInstance;
private static Context ctx;
private RequestQueue requestQueue;
private MySingleton(Context ctx) {
this.ctx =ctx;
requestQueue = getRequestQueue();
}
private RequestQueue getRequestQueue() {
if(requestQueue == null) {
requestQueue = Volley.newRequestQueue(ctx.getApplicationContext());
}
return requestQueue;
}
public static synchronized MySingleton getmInstance(Context context) {
if(mInstance == null) {
mInstance = new MySingleton(context);
}
return mInstance;
}
public <T>void addToRequestQueue(Request<T> request){
getRequestQueue().add(request);
}
}
试试这个:
在Singleton类中添加:
@Override
public void onCreate() {
super.onCreate();
// initialize the singleton
mInstance = this;
}
:
HashMap<String, String> params = new HashMap<>();
params.put("value","value" );
params.put("value", "value");
JSONObject par = new JSONObject(params);
JsonObjectRequest objectRequest = new JsonObjectRequest("url here", par,
new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response) {
Log.d(" response", response.toString());
}},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
//handle error here
}
});
// Access the RequestQueue through your singleton class.
MyApplication.getInstance().addToRequestQueue(jsObjRequest);
如有任何进一步的疑问,请在评论中告诉我