0

I can't parse through a json array. When I try to I get an "Not a primitive array error. Could you help me to find my error?

I've been searching for solutions but couldn't find some.

Here is my Code:

    public void tableInit() throws JSONException {
        Log.e("TableInit()", "Start!");
        Log.e("TableInit()", ""+jsonObjectToTable);
        float textSize = 18.0f;
        TableLayout stk = (TableLayout) findViewById(R.id.table_main);
        TableRow tbrow0 = new TableRow(this);

        TextView tv0 = new TextView(this);
        tv0.setText(" ID ");
        tv0.setTypeface(null, Typeface.BOLD); //fett
        tv0.setTextSize(textSize);
        tbrow0.addView(tv0);

       [...]

        stk.addView(tbrow0);


        JSONArray jsonArray = new JSONArray(jsonObjectToTable);

        for(int i = 0; i < jsonArray.length(); ++i)
        {
            // Extract values from JSON row:
            JSONObject jsonObject      = jsonArray.getJSONObject(i);
            Log.e("JsonObject", ""+jsonObject);
            String     id     = jsonObject.has("id")     ? jsonObject.getString("id") : "";
            String     name    = jsonObject.has("name")    ? jsonObject.getString("name") : "";
            String     home = jsonObject.has("home") ? jsonObject.getString("home") : "";
            String     wetsuit     = jsonObject.has("wetsuit")     ? jsonObject.getString("wetsuit") : "";
            String     board     = jsonObject.has("board")     ? jsonObject.getString("board") : "";
            String     rig     = jsonObject.has("rig")     ? jsonObject.getString("rig") : "";
            String     harness     = jsonObject.has("harness")     ? jsonObject.getString("harness") : "";
            String     rent_until     = jsonObject.has("rent_until")     ? jsonObject.getString("rent_until") : "";
            String     renting_date     = jsonObject.has("renting_date")     ? jsonObject.getString("renting_date") : "";

            TableRow tbrow = new TableRow(this);

            TextView textViewId = new TextView(this);
            textViewId.setText(id);
            textViewId.setGravity(Gravity.CENTER);
            tbrow.addView(textViewId);

            [...]
        }

    }

and here is the jsonObjectToTable created:

        @Override
        protected String doInBackground(String... strings) {
            Log.e("Async", "Async starts!");
            try {
                response = RequestHandler.sendGet("http://192.168.122.1/php/renting_private_select.php");
                return response;

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

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        protected void onPostExecute(String s) {
            try {
                JSONObject tableJson = new JSONObject(s);
                jsonObjectToTable = tableJson;
                tableInit();

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

    }
}

I get the following Logs:

E/TableInit(): Start! E/TableInit(): {"equipment_private": [{"id":"1","name":"Name","home":"Unterkunft","wetsuit":"Anzug","board":"Board","rig":"Segel","harness":"Trapetz","renting_date":"23.01.19","rent_until":"23.12.19"},{"id":"2","name":"Name","home":"Unterkunft","wetsuit":"Anzug","board":"Board","rig":"Segel","harness":"Trapetz2","renting_date":"","rent_until":""}]} W/System.err: org.json.JSONException: Not a primitive array: class org.json.JSONObject W/System.err: at org.json.JSONArray.(JSONArray.java:116) at com.example.surftest.MainActivity.tableInit(MainActivity.java:135) W/System.err: at com.example.surftest.MainActivity$RequestSelectAsync.onPostExecute(MainActivity.java:234) at com.example.surftest.MainActivity$RequestSelectAsync.onPostExecute(MainActivity.java:213) at android.os.AsyncTask.finish(AsyncTask.java:695) at android.os.AsyncTask.access$600(AsyncTask.java:180) at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712) W/System.err: at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6669) at java.lang.reflect.Method.invoke(Native Method) W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

SlartiDev
  • 49
  • 1
  • 9

3 Answers3

0

Your overall way of parsing is not quite right.

I would suggest something like GSON for such purposes.

to use it firstly create two model classes.

class Response{

@SerializedName("equipment_private")
public List<Equipment> equipmentPrivate

} 

class Equipment {

public String id;

public String name;

public String home;

public String wetsuit;

public String board;

public String rig;

public String harness;

@SerializedName("renting_date")
public String rentingDate;

@SerializedName("rent_until")
public String rentUntil;

}

And after that you can do something like

 Gson gson = new Gson();
 Response response = gson.fromJson(json_string, Response.class);

Maybe it will require some additional work since I didn't check it in IDE but I think you'll grasp. Hope it will help.

Pavlo Ostasha
  • 14,527
  • 11
  • 35
0

What you are doing wrong is that you are creating object of json array and passing json object itself whereas in your json response json array is embeded in json object related to key "equipment_private".
Wrong way:
JSONArray jsonArray = new JSONArray(jsonObjectToTable);
Correct way:
JSONArray jsonArray = jsonObjectToTable.getJSONArray("equipment_private")
Hope you will understand and this will fix your issue.

0

It's because the table you're getting is an Object itself. Just take a look at this. You only need one line more to complete your code:

This is your Input

{
  "equipment_private": [{
    "id": "1",
    "name": "Name",
    "home": "Unterkunft",
    "wetsuit": "Anzug",
    "board": "Board",
    "rig": "Segel",
    "harness": "Trapetz",
    "renting_date": "23.01.19",
    "rent_until": "23.12.19"
  }, {
    "id": "2",
    "name": "Name",
    "home": "Unterkunft",
    "wetsuit": "Anzug",
    "board": "Board",
    "rig": "Segel",
    "harness": "Trapetz2",
    "renting_date": "",
    "rent_until": ""
  }]
}

So you should Parse as Below :

JSONObject object = new JSONObject(jsonObjectToTable);  // You do need this line
try {
  object.get("equipment_private");


  JSONArray jsonArray = new JSONArray(object);

  for (int i = 0; i < jsonArray.length(); ++i) {
    // Extract values from JSON row:
    JSONObject jsonObject = jsonArray.getJSONObject(i);
    Log.e("JsonObject", "" + jsonObject);
    String id = jsonObject.has("id") ? jsonObject.getString("id") : "";
    String name = jsonObject.has("name") ? jsonObject.getString("name") : "";
    String home = jsonObject.has("home") ? jsonObject.getString("home") : "";
    String wetsuit = jsonObject.has("wetsuit") ? jsonObject.getString("wetsuit") : "";
    String board = jsonObject.has("board") ? jsonObject.getString("board") : "";
    String rig = jsonObject.has("rig") ? jsonObject.getString("rig") : "";
    String harness = jsonObject.has("harness") ? jsonObject.getString("harness") : "";
    String rent_until = jsonObject.has("rent_until") ? jsonObject.getString("rent_until") : "";
    String renting_date = jsonObject.has("renting_date") ? jsonObject.getString("renting_date") : "";

    TableRow tbrow = new TableRow(this);

    TextView textViewId = new TextView(this);
    textViewId.setText(id);
    textViewId.setGravity(Gravity.CENTER);
    tbrow.addView(textViewId);

    [...]
  }


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

Now, let me know if you're getting any error

Also, you can resolve your issue by creating Classes that represent your Json Objects and then use a GSON converter to parse it without writing any of these codes. you can find an example solution in this thread How to parse json parsing Using GSON in android

Shahin
  • 391
  • 3
  • 9