I am creating an android app which takes user input, attempts to make a connection to the API url with the specified input and retrieve data and display it. Now I've been able to do everything above but there is a potential chance that if a user enters something and it doesn't exist my app will crash because of a NPE (Null Pointer Exception).
The API I am using shows me a list of response errors that can occur but I'm not sure how I should handle or implement a feature that takes these response errors into account.
Currently my extended AsyncTask class has these parameters: String, Void, JSONObject and the following code is what I have in my doInBackground method.
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
int statusCode = urlConnection.getResponseCode();
switch (statusCode) {
case 400:
return "Error 400 - Bad request.";
case 401:
return "Error 401 - Unauthorized request.";
}
I can't return a String because my AsyncTask param returns a JSONObject. I can change it so it does return a String but I believe it's not the proper logical way of handling the response errors.
Now if the API response code was a 404 (No data found), I don't want the app to crash because it can't return the JSONObject, instead I would like it to continue on to the next fragment and display minimal information.
So how do I go about handling response errors when my method returns a JSONObject?