我有一个来自网址的json
数据,我想在其中使用排球库获取文本数据。我还有一个片段,其中将显示数据。
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);
}
}
答案 0 :(得分:0)
试试这个:
在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);
请在评论中告知我们进一步的查询