0

I'm trying to get a JSON array for ListView on Android, but I couldn't so far.

My JSON is like this

[
   {
      "iD":1,
      "name":"name1"
   },
   {
      "iD":2,
      "name":"name2"
   },
   {
      "iD":3,
      "name":"name3"
   },
   {
      "iD":4,
      "name":"name4"
   }
]

Also Try tried this second JSON format

{
   "userdata":[
      {
         "iD":1,
         "name":"name1"
      },
      {
         "iD":2,
         "name":"name2"
      },
      {
         "iD":3,
         "name":"name3"
      },
      {
         "iD":4,
         "name":"name4"
      }
   ]
}

And my Java looks like

     private void loadIntoListView(String json) throws JSONException {
            Log.e("log1 = ", json);

            JSONArray jsonArray = new JSONArray(json);
            Log.e("log2 = ","5" );  //Integer.toString(jsonArray.length())
            String[] heroes = new String[jsonArray.length()];

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject obj = jsonArray.getJSONObject(i);
                heroes[i] = obj.getString("name");
            }
            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, heroes);
            listView.setAdapter(arrayAdapter);
        }

     private void loadIntoListView(String json) throws JSONException {
        Log.e("result 2 = ", json);

        JSONObject entries = new JSONObject(json);
        JSONArray jsonArray = entries.getJSONArray("userdata");

        Log.e("length = ","5" );  //Integer.toString(jsonArray.length())
        String[] heroes = new String[jsonArray.length()];

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            heroes[i] = obj.getString("name");
        }
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, heroes);
        listView.setAdapter(arrayAdapter);
    }

I see the first log, but I can't see second. Also, I can't get the names for ListView.

require_once('connection.php');

$heroes = array(); 
$sql = "SELECT iD, name FROM valTable;";
$stmt = $conn->prepare($sql);
$stmt->execute();

$stmt->bind_result($id, $name);

while($stmt->fetch()){

    $temp = [
        'iD'=>$id,
        'name'=>$name
    ];

    array_push($heroes, $temp);
}

echo json_encode($heroes);
5
  • What is printed in log 1? Commented Jul 23, 2019 at 10:57
  • @Athira [{"iD":1,"name":"name1"},{"iD":2,"name":"name2"},{"iD":3,"name":"name3"},{"iD":4,"name":"name4"}] I see my JSON string no problem on log1 Commented Jul 23, 2019 at 10:59
  • 2
    Possible duplicate of How to parse JSON Array (Not Json Object) in Android Commented Jul 23, 2019 at 11:43
  • what is your error? Please share your error. Commented Jul 23, 2019 at 13:39
  • I am still searching Commented Jul 23, 2019 at 14:01

3 Answers 3

2

You should use a JSON library such as Gson to parse those objects for your.

Add on your gradle dependencies

  implementation 'com.google.code.gson:gson:2.8.5'

You can create objects like

data class JsonRootObject(val userdata: List<User>)

data class User(val iD:Int, val name:String)

And then parse your object

val myParsedObject = Gson().fromJson(jsonString, JsonRootObject::class.java);

Make sure that your field names are the same as your object being parsed, this also means case sensitive. If you want to change their mapping name you might want to use @SerializedName("id") annotation like

class User {

  @SerializedName("id")
  lateinit var id: Int

  @SerializedName("my_name")
  lateinit var name: String  

}

Consider this answer to your second object

{
   "userdata":[
      {
         "iD":1,
         "name":"name1"
      },
      {
         "iD":2,
         "name":"name2"
      },
      {
         "iD":3,
         "name":"name3"
      },
      {
         "iD":4,
         "name":"name4"
      }
   ]
}

and of course, all this is written in Kotlin.

Sign up to request clarification or add additional context in comments.

4 Comments

Is it possible to give this example in Java?
Here is an example in Java stackoverflow.com/a/23862104/1573036 - Whenever asking a question on stack overflow, make sure that it does not exist one already.
Not success on your both links. The first one is same as mine but I cant understand where is my fault. It seems to ben at JSON array but check my php. I still cant see.
0

Use try catch instead of throws

    try {

        JSONArray jsonArray = new JSONArray(json);
        Log.e("log2 = ", "5");  //Integer.toString(jsonArray.length())
        String[] heroes = new String[jsonArray.length()];

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            heroes[i] = obj.getString("name");
        }
 ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, heroes);
        listView.setAdapter(arrayAdapter);
    }
    catch (Exception e)
    {
        Log.e("log3 = ", ""+e);
    }

4 Comments

I get This on log3 org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray
Check what you have in json, issue must be there in json
[{"iD":1,"name":"name1"},{"iD":2,"name":"name2"},{"iD":3,"name":"name3"},{"iD":4,"name":"name4"}] is there any thing wrong?
Add the part where you get json
0

Try first to convert your String json to JSONObject and then convert that JSONObject to JSONArray. See this answer.

3 Comments

I cant understand getNames function on that page. I think it is not included in JSON library
What is name of the json library you use?
import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.