我正在尝试从另一个类的Volley访问mQueue,然后是MainActivity.java。
MainActivity.java
在MainActivity.java中,我创建RequestQueue实例并插入队列:
private RequestQueue mQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Init queue ( getRequestQueue )
mQueue = MyRequestQueue.getInstance(this.getApplicationContext()).getRequestQueue();
getLights();
initListView();
}getLight()方法在MainActivity.java中将请求添加到队列中:
String url = APIkey + "/lights";
final MyJSONObject request = new MyJSONObject(Request.Method.GET, url, new JSONObject(), this, this);
// Executing the queue
mQueue.add(request);RequestHandler.java
我将put请求移到一个名为RequestHandler.java的单独类中。
public class RequestHandler implements Response.Listener<JSONObject>, Response.ErrorListener {
RequestQueue mQueue;
public void setLightOn(String lightId, boolean lightsOn){
String url = APIkey + "/lights/" + lightId + "/state";
JSONObject json = new JSONObject();
try {
json.put("on", lightsOn);
}
catch (Exception e) {
// Error handling
Log.i("Value was not found", "");
}
final MyJSONObject request = new MyJSONObject(Request.Method.PUT, url, json, this, this);
request.setTag("ONOF");
mQueue.add(request);
}
// Volley error and response handler
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("ERROR REQUEST HANDLER");
}
@Override
public void onResponse(JSONObject response) {
System.out.println("SUCCEED REQUEST HANDLER");
}
}误差
上面的代码将给我一个错误和我的Android应用程序崩溃。说mQueue为空的错误;
com.android.volley.RequestQueue.add(com.android.volley.Request)‘:java.lang.RuntimeException:无法启动活动.DetailActivity}:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法的com.android.volley.Request
在此之前,我还在MainActivity中使用了这些方法,但希望它与我的MainActivity分开。
我错了什么,忘了吧,所以mQueue不再是null了?如果还有什么问题,请告诉我。
提前谢谢你。
发布于 2016-10-17 18:06:29
问题归结到Java的作用域。Activity定义并跟踪mQueue,但是您已经在RequestHandler类中创建了一个受类保护的成员字段mQueue。但是,RequestHandler没有一个以RequestQueue作为参数的构造函数。
或者,如果RequestHandler是Activity的内部类,则不必定义mQueue成员字段,因为内部类将访问父类的成员字段。
https://stackoverflow.com/questions/40092527
复制相似问题