I am making an app that makes a JsonObjectRequest
and retrieves a JSON data from an URL using the Volley Networking Library for android.
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;
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
}
Method in MainActivity.class
private void makeJSONObjectRequest() {
showDialog();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
urlJsonObj, (String) null, new Response.Listener<JSONObject>() {
@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);
}
It gives the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.h8pathak.volleyjson.AppController.addToRequestQueue(com.android.volley.Request)' on a null object reference
How can I rectify this code?
Your AppController class
needs to extend Application class instead of the AppCompatActivity class.
And remember to update your Manifest as well. ie. Add this class in your AndroidManifest.xml using name attribute for <application>
tag.
<application
android:name=".AppController"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With