Arraylist does not display anything

Issue

I want to know why my Arraylist does not display anything:

{"Friends":[{"name":"Java","age":"18"},{"name":"Python","age":"35"},{"name":"Denis","age":"45"}]}

MainActivity (toast in catch of OnPostExecute appears, named "CATCH OF THE TRY"):

package com.example.parsingjson;

import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    private ListView lv;
    String Friends;
    String namey, age;
    private static String JSON_URL="https://run.mocky.io/v3/9c0d17c6-c9a4-41d9-89cc-ac43e44f2b88";
    ArrayList<HashMap<String,String>> friendsList;

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

        friendsList = new ArrayList<>();
        lv = findViewById(R.id.listview);
        GetData getData = new GetData();
        getData.execute();
    }

    public class GetData extends AsyncTask<String, String, String>{

        @Override
        protected String doInBackground(String... strings) {
            String current = "";

            try {
                URL url;
                HttpURLConnection urlConnection = null;

                try {
                    url = new URL(JSON_URL);
                    urlConnection = (HttpURLConnection) url.openConnection();
                    InputStream in = urlConnection.getInputStream();
                    InputStreamReader isr = new InputStreamReader(in);
                    int data = isr.read();
                    while (data != -1) {
                        current += (char) data;
                        data = isr.read();
                    }

                    return current;
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (urlConnection != null) {
                        urlConnection.disconnect();
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
             return current;
            }

        @Override
        protected void onPostExecute(String s) {
//            Toast.makeText(getApplicationContext(), "POST EXECUTE", Toast.LENGTH_LONG).show();
            try{
 //               Toast.makeText(getApplicationContext(), "TRY", Toast.LENGTH_LONG).show();

                JSONObject jsonObject = new JSONObject(s);
                JSONArray jsonArray = jsonObject.getJSONArray(Friends);
                for (int i = 0; i< jsonArray.length() ; i++){

                    Toast.makeText(getApplicationContext(), "FOR", Toast.LENGTH_LONG).show();
                    JSONObject jsonObject1 = jsonArray.getJSONObject(i);

                namey = jsonObject1.getString("name");
                age = jsonObject1.getString("age");
                //HashMap
                    HashMap<String, String> friends = new HashMap<>();

                    friends.put("name","namey");
                    friends.put("age","age");
                    friendsList.add(friends);
//                    Toast.makeText(getApplicationContext(), "OPERATION SUCCESSFUL", Toast.LENGTH_LONG).show();
                }
 //                   Toast.makeText(getApplicationContext(), "APRES FOR", Toast.LENGTH_LONG).show();

        } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "CATCH OF THE TRY", Toast.LENGTH_LONG).show();
            }
            // Displaying the results
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this,
                    friendsList,
                    R.layout.row_layout,
                    new String[]{"name", "age"},
                    new int []{R.id.textView, R.id.textView2});

            lv.setAdapter(adapter);
        }
    }
}

row_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:fontFamily="sans-serif-black"
        android:text="TextView"
        android:textColor="#000000"
        android:textSize="36sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="24dp"
        android:text="TextView"
        android:textSize="30sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />
</androidx.constraintlayout.widget.ConstraintLayout>

Activity_Main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/listview"
        android:layout_width="409dp"
        android:layout_height="729dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Only toast I’m not able to show is located in for (int i = .... Toast in catch is showing.

 org.json.JSONException: No value for null
     at org.json.JSONObject.get(JSONObject.java:399)
     at org.json.JSONObject.getJSONArray(JSONObject.java:594)
     at com.example.parsingjson.MainActivity$GetData.onPostExecute(MainActivity.java:107)
     at com.example.parsingjson.MainActivity$GetData.onPostExecute(MainActivity.java:52)
     at android.os.AsyncTask.finish(AsyncTask.java:755)
     at android.os.AsyncTask.access$900(AsyncTask.java:192)
     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:772)
     at android.os.Handler.dispatchMessage(Handler.java:107)
     at android.os.Looper.loop(Looper.java:214)
     at android.app.ActivityThread.main(ActivityThread.java:7356)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

@ cactustictacs Thanks to your answer, i discovered that i had forgoten to put the name Friend between the "". Now, the new problem is that i display 3 times NAMEY and AGE instead of Java 18, Python 35 and Denis 45. Do you have any idea? EDIT: I had put the String namey and age between "", it’s why i displayed 3 times namey and age. THANK YOU VERY MUCH

Solution

Here’s the bit in your stacktrace that says where it’s going wrong:

org.json.JSONException: No value for null
     at org.json.JSONObject.get(JSONObject.java:399)
     at org.json.JSONObject.getJSONArray(JSONObject.java:594)
     at com.example.parsingjson.MainActivity$GetData.onPostExecute(MainActivity.java:107)

So at line 107 in MainActivity, in your onPostExecute function, you’re calling getJSONArray(). The exception is no value for null which implies you’re passing null to that call.

I don’t know which is line 107 specifically, but I’m assuming it’s this:

JSONArray jsonArray = jsonObject.getJSONArray(Friends);

and if you’re passing null into that, then Friends must be null. And from the code you’ve posted, that’s true – you create the variable

// no value assigned - null by default
String Friends;

but then you don’t actually assign a String to it anywhere. I’m guessing you meant to assign the JSON key to it

String Friends = "Friends";

Also the variable name should really be friends – only classes and interfaces should start with a capital letter. Just makes it easier to tell what’s happening!

Answered By – cactustictacs

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *