我正在制作一个应用程序,JsonObjectRequest
使用适用于Android的Volley Networking Library从URL获取并检索JSON数据.
AppController.java
public class AppController extends AppCompatActivity { public static final String TAG = AppController.class.getSimpleName(); private RequestQueue mRequestQueue; private static AppController mInstance; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mInstance = this; } public static synchronized AppController getInstance(){ return mInstance; } public RequestQueue getRequestQueue(){ if(mRequestQueue == null){ mRequestQueue = Volley.newRequestQueue(getApplicationContext()); } return mRequestQueue; } publicvoid addToRequestQueue(Request req) { req.setTag(TAG); getRequestQueue().add(req); } }
MainActivity.class中的方法
private void makeJSONObjectRequest() { showDialog(); JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, urlJsonObj, (String) null, new Response.Listener() { @Override public void onResponse(JSONObject response) { Log.d(TAG, response.toString()); try { //Parsing JSON Object response String name = response.getString("name"); String email = response.getString("email"); JSONObject phone = response.getJSONObject("phone"); String home = phone.getString("home"); String mobile = phone.getString("mobile"); jsonResponse = ""; jsonResponse += "Name: " + name + "\n\n"; jsonResponse += "Email: " + email + "\n\n"; jsonResponse += "Home: " + home + "\n\n"; jsonResponse += "Mobile: " + mobile + "\n\n"; txtResponse.setTag(jsonResponse); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show(); } hideDialog(); } }, new ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { VolleyLog.d(TAG+"Error:"+ volleyError.getMessage()); Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_SHORT).show(); hideDialog(); } }); /*THE ERROR OCCURS HERE! */ //adding request to the RequestQueue AppController.getInstance().addToRequestQueue(jsonObjReq); }
它给出以下错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.h8pathak.volleyjson.AppController.addToRequestQueue(com.android.volley.Request)' on a null object reference
我该如何纠正这段代码?
您AppController class
需要扩展Application类而不是AppCompatActivity类.
并记住也要更新你的清单.即.使用
tag的name属性在AndroidManifest.xml中添加此类.