I am creating an Android application that takes user input, tries to connect to the API URL with the specified input and retrieve the data and display it. Now I was able to do everything above, but there is a potential chance that if the user enters something, and he does not exist, my application will fail due to NPE (Null Pointer exception).
The API that I use shows me a list of response errors that may occur, but I'm not sure how I should handle or implement a function that takes into account these response errors.
Currently, my AsyncTask extended class has the following 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 cannot return a String because my AsyncTask parameter returns a JSONObject. I can change it so that it returns a string, but I believe that this is not the right logical way to handle response errors.
Now, if the API response code was 404 (no data found), I do not want the application to crash because it cannot return a JSONObject, instead I would like it to continue moving on to the next fragment and display the minimum information.
So, how do I handle error response handling when my method returns a JSONObject?