0

Here is the response that I am receiving from my REST service from a GET Request:

{
  "type": "usersTable",
  "employeeId": 1,
  "employeeName": "Andrew Watson",
  "userPin": "705207"
}

I am trying to retrieve the userPin value from the JSON.

Here is the code I have attempted:

if (con.getResponseCode() == HttpsURLConnection.HTTP_OK 
           || con.getResponseCode() == HttpsURLConnection.HTTP_ACCEPTED ) {
    String line;
    BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
    while ((line=br.readLine()) != null) {
        JSONObject json = new JSONObject(br.toString());
        userPinRetrieved = String.valueOf(json.getInt("userPin"));
    }
}

Can anyone see why I am getting a Null Pointer?

Rohit5k2
  • 17,948
  • 8
  • 45
  • 57

1 Answers1

1

I have not tested this one yet. But I think the problem is userPin is string not an integer value.

 if (con.getResponseCode() == HttpsURLConnection.HTTP_OK 
               || con.getResponseCode() == HttpsURLConnection.HTTP_ACCEPTED ) {
        String line;
        BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
        while ((line=br.readLine()) != null) {
            JSONObject json = new JSONObject(br.toString()); 
            if(json.getString("userPin") == null) {
               //do something here or define the default value
            }else {
                userPinRetrieved = json.getString("userPin");
            }
        }
    }
Lokesh Pandey
  • 1,739
  • 23
  • 50
  • is it weird that it is receiving null at runtime but receiving the correct value at debug? @Lokesh – AndroidBeginner2018 Jun 01 '18 at 09:58
  • can you check that your object's property "userPin" has got the pin value ? – Lokesh Pandey Jun 01 '18 at 09:59
  • @AndroidBeginner2018 I have update my answer. You can define a default value to the userPinRetrieved or do something else, if it's null. It should not throw exception this time – Lokesh Pandey Jun 01 '18 at 10:04
  • yes it is getting the correct pin value at debug mode. Although when I actually run the program it is getting null. very strange. – AndroidBeginner2018 Jun 01 '18 at 10:14
  • @AndroidBeginner2018 Can you try the updated answer ? And can you include the code why is it getting null ? I think the data you are receiving is having null values. If that is the case then you can avoid it using the updated answer – Lokesh Pandey Jun 01 '18 at 11:29
  • this was my problem: see also: https://stackoverflow.com/questions/50642036/asynctask-not-returning-result-quick-enough-to-main-thread – AndroidBeginner2018 Jun 01 '18 at 11:33
  • you may also like this one https://stackoverflow.com/questions/15635436/returning-data-from-asynctask-without-blocking-ui/15635493?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Lokesh Pandey Jun 01 '18 at 11:37