Do proper parsing of the JSON as , you see yours response:-

 { "Details":[{"Status":"NO UPDATES"}]}

So Firstly try to make the object of the JSONObject than after the JSONArray , look at below example:-

JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray detailsArray = jsonObject.getJSONArray("Details");

String status = dataArray.getJSONObject(0).getString("status");

 Toast.makeText(getBaseContext(), "Please wait...",100+status).show();
Answer from Ravindra Kushwaha on Stack Overflow
Top answer
1 of 3
6

First problem

You're passing the wrong value into the JSONObject constructor. Look at this piece of code:

String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
    System.out.println(inputLine);
}

JSONObject obj = new JSONObject(inputLine);

The while loop is only going to complete when inputLine is null - so your final line is equivalent to:

JSONObject obj = new JSONObject(null);

... which obviously isn't what you want. I think you want:

JSONObject obj = new JSONObject(response.toString());

Note that you probably want to use StringBuilder rather than StringBuffer as well, to avoid pointless synchronization.

Next problem

If your JSON is actually of the form [ ... ] then it's an array, not an object at the top level. So you probably want:

JSONArray arr = new JSONArray(response.toString());
for (int i = 0; i < arr.length(); i++)
{
    String drzava = arr.getJSONObject(i).getString("Država");
    System.out.println(drzava);
}

After all, if you look at your JSON, it doesn't have Država as the name of a property with an array as the value.

2 of 3
1

I think you are using wrong input for your JSonObject:

double responseCode = conn.getResponseCode();
try (InputStreamReader  sr =new InputStreamReader(conn.getInputStream());
     BufferedReader in = new BufferedReader(sr)){  
// ^ this is Jdk7+, will close your streams after the block exists, like in finally block 

...

JSONObject obj = new JSONObject(response.toString()); // pass the input as a String

....
}catch (IOException | JSONException e) {
    e.printStackTrace();
}

Your response variable holds the input in a form of a String, whereas inputLine holds only single line. And after the last iteration, it's set to null. Which will cause an NPE.

🌐
Stack Overflow
https://stackoverflow.com › questions › 69950444 › java-null-pointer-exception-for-json-object
Java Null Pointer Exception for JSON Object - Stack Overflow
This is my code and it throws java null pointer exception at a particular JSON Object in my code, named "films". I don't understand why it deems this as "null". Where the error is being given, is where the code should read the contents of the txt file based on the method "readJSONFile".
Top answer
1 of 2
2

Key to the answer : Gson or not, parsing the json string is the key to the answer.

From the comments by Siddharth below.

JsonParser parser = new JsonParser();
JsonObject json = parser.parse(jsonResults.toString()).getAsJsonObject() ; 
JsonArray results = json.getAsJsonArray("results");
JsonObject result = results.get(0).getAsJsonObject(); 
customerAddress = result.get("formatted_address").getAsString(); 

Alternative :

I failed to read the edit 3 part of the question and failed to look at the gson tag. So i ended up providing the below alternative.

JSONObject jsono = new JSONObject (myjsonstring);
JSONArray myListsAll= new JSONArray(jsono.getString("results"));
for(int i=0;i<myListsAll.length();i++){
JSONObject jsonObject1 = (JSONObject) myListsAll.get(i);
JSONArray myarray= new JSONArray(jsonObject1.getString("address_components"));
for(int i1=0;i1<myarray.length();i1++)
{
JSONObject jsonobject2 =  myarray.getJSONObject(i1);                     
System.out.println(""+jsonobject2.getString("long_name"));                  
System.out.println(""+jsonobject2.getString("short_name"));
System.out.println(""+jsonobject2.getString("types"));
}
}

Output

Towards Wadgao Sheri
Towards Wadgao Sheri
["route"]
Sainikwadi
Sainikwadi
["neighborhood","political"]
Wadgaon Sheri
Wadgaon Sheri
["sublocality","political"]
Pune
Pune
 ["locality","political"]
 Pune
 Pune
 ["administrative_area_level_2","political"]
Maharashtra
MH
["administrative_area_level_1","political"]
India
IN
["country","political"]
411014
411014
["postal_code"]
 Sainikwadi
 Sainikwadi
 ["neighborhood","political"]
 Wadgaon Sheri
 Wadgaon Sheri
 ["sublocality","political"]
 Pune
 Pune
 ["locality","political"]
 Pune
 Pune
 ["administrative_area_level_2","political"]
 Maharashtra
 MH
 ["administrative_area_level_1","political"]
 India
 IN
 ["country","political"]
 411014
 411014
 ["postal_code"]
 Wadgaon Sheri
 Wadgaon Sheri
 ["sublocality","political"]
 Pune
 Pune
 ["locality","political"]
 Pune
 Pune
 ["administrative_area_level_2","political"]
 Maharashtra
 MH
 ["administrative_area_level_1","political"]
 India
 IN
 ["country","political"]
 411014
 411014
 ["postal_code"]
 Pune
 Pune
 ["administrative_area_level_2","political"]
 Maharashtra
 MH
 ["administrative_area_level_1","political"]
 India
 IN
 ["country","political"]
 Pune
 Pune
 ["locality","political"]
 Pune
 Pune
 ["administrative_area_level_2","political"]
 Maharashtra
 MH
 ["administrative_area_level_1","political"]
 India
 IN
 ["country","political"]
 Pune
 Pune
 ["administrative_area_level_2","political"]
 Maharashtra
 MH
 ["administrative_area_level_1","political"]
 India
 IN
 ["country","political"]
 Maharashtra
 MH
 ["administrative_area_level_1","political"]
 India
 IN
 ["country","political"]
 India
 IN
 ["country","political"]
2 of 2
1

You start off with ...

JsonObject response = new JsonObject().getAsJsonObject(jsonResults.toString());

This makes no sense. You've created a new, empty JsonObject then attempt to retrieve an element from it using your entire JSON string as the property name. Therefore, yes ... response is null.

Your JSON is an object. It contains two fields; results which is an array of objects and status which is a String.

Normally when using Gson you'd create matching Java classes and use a Gson instance to deserialize to them. If you don't want to do that, then you'd Gson's JsonParser to parse the Json and then access it through the various Json* classes:

/// jsonResuts is a String containing the JSON you list.
JsonObject obj = new JsonParser().parse(jsonResults).getAsJsonObject();
JsonArray resultsArray = obj.getAsJsonArray("results");

Now you have the array of objects and can delve deeper into that using the same methods/classes from Gson I used above.

for (JsonElement e : resultsArray) {
    JsonObject resultsObj = e.getAsJsonObject();
    JsonElement formattedAddress = resultsObject.get("formatted_address");
    String addressAsString = formattedAddress.getAsString();
    System.out.println(addressAsString);
    // The above can be chained and reduced to one line:
    // System.out.println(e.getAsJsonObject().get("formatted_address").getAsString());
}  
Top answer
1 of 3
7

There's a couple of things you could do better here. But your main problem is that you are doing async tasks(backgroundtask) and not handling a proper callback.

What happens in the following:

  1. Starting of the async task.
  2. You sleep for 3 seconds (Which is probably to try to make the async finish before the code continues.)
  3. The Async task might not have finish have finished in the 3 seconds.
  4. Your try to parse the JSON that has not been received yet.
  5. This throws a nullpointer.

Now while crashing the async task still runs and finishes. I'm not sure if you save this JSON and then it becomes readable while completing and becomes available the second time, or that the second time the task might finish within 3 seconds.

What you should do

  1. Starting of the async task.
  2. Do Not let the thread sleep.
  3. In the async task onPostExecute have a callback to your main thread.
  4. Have the callback return the JSON obtained from the task.
  5. Now parse the JSON you will have, if the call itself did succeed.

To achieve this look here https://developer.android.com/training/best-background.html

It should provide enough information to get this piece of code stable.

2 of 3
1

Another way you can place intent inside your post execute. in your Activity's onCreate method

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

    new RetrieveGamesBGTask(Splash.this).execute();

}

now in your RetrieveGamesBGTask's onPostExecute method

@Override
protected void onPostExecute(String result) {
    Log.d("haha", "hehe");
    json_result = result;
    Intent intent = new Intent(context, Games.class);
                intent.putExtra("json_data", json_string);
                intent.putExtra("json_data",json_result);
                context.startActivity(intent);
}
Find elsewhere
🌐
CodingTechRoom
https://codingtechroom.com › question › resolve-null-pointer-exceptions-json-conversion
How to Resolve Null Pointer Exceptions When Converting to JSON? - CodingTechRoom
Solution: Implement @JsonInclude(JsonInclude.Include.NON_NULL) to ignore null fields during serialization. null pointer exception · JSON conversion issues · Jackson JSON · JSON serialization errors · Java object to JSON · ›How to Resolve JavaCV Issues After a Successful Clean and Build?
🌐
Stack Overflow
https://stackoverflow.com › questions › 24084145 › how-to-solve-getting-null-pointer-exception-in-json-parsing
java - how to solve getting null pointer exception in JSON parsing? - Stack Overflow
There could be many statements in this that might result in NullPointer. As the comments suggest its difficult to identify without the trace. However the most probable place would be · // Getting JSON Array node contacts = jsonStr.getJSONArray(TAG_CONTACTS); // looping through All Contacts for (int i = 0; i < contacts.length(); i++) { ...
🌐
Stack Overflow
https://stackoverflow.com › questions › 32632303 › error-java-lang-nullpointerexception-in-json-parsing
Error java.lang.NullPointerException in JSON parsing - Stack Overflow
July 11, 2016 - I am new to Java,and using below code to parse JSON,but I am getting java.lang.NullPointerException error when the offers {} node is coming with empty values ,which is public class in my code. ... The code is able to parse JSON if there is data under "offers" like "info",but exiting with NULL exception error when JSON returns and empty as shown below.
🌐
Stack Overflow
https://stackoverflow.com › questions › 29400796 › jsonobject-throwing-nullpointerexception
java - JSONObject Throwing NULLPOINTEREXCEPTION - Stack Overflow
I activate the piece of code under an action of a button but everything else works fine except these specific lines of code. jsonobject giving error for don't know what reason. ... It looks like your json parser choked and returned null. Check for null before you try to run toString() on json. ... json.toString() ¿¿?? it's null, check your json string response and put string inside parenthesis, example json.toString("name"); then it reports name from json string ... org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject check that you are not receiving html/xml instead of json