Home > Enterprise >  How to set JSON Array values to seter class in Android Studio with volley
How to set JSON Array values to seter class in Android Studio with volley

Time:01-13

I'm trying to display my row tables on the database in my ListView , However I dont know how to convert JSONObject to JSONArray and set it to my setter class. I get my JSON through Volley String Request

I have the JSON output like this :

{
    "error": false,
    "message": "Status Fetched",
    "status": [
        {
            "OrderCode": "5x2azu",
            "GuestName": "Try",
            "ProductName": "Mie Ayam Super Jumbo Komplit",
            "ProductType": "Kuah",
            "NoTable": 4,
            "Status": "Disiapkan",
            "TotalPrice": "58000"
        },
        {
            "OrderCode": "etent3",
            "GuestName": "Try",
            "ProductName": "Nasi Soto Daging Sapi",
            "ProductType": "Soto",
            "NoTable": 4,
            "Status": "Disiapkan",
            "TotalPrice": "27000"
        },
        {
            "OrderCode": "ro1eyx",
            "GuestName": "Try",
            "ProductName": "Mie Ayam Original",
            "ProductType": "Kuah",
            "NoTable": 4,
            "Status": "Disiapkan",
            "TotalPrice": "23000"
        }
    ]
}

and here is my String Request :

public void StringRequest() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.STATUS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject obj = new JSONObject(response);
                            Toast.makeText(getContext(), response, Toast.LENGTH_SHORT).show();

                            //if no error in response
                            if (!obj.getBoolean("error")) {
                                Toast.makeText(getContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();

                                //getting Status from response
                                JSONObject statusJson = obj.getJSONObject("status");
                                Status status = new Status(
                                        statusJson.getString("OrderCode"),
                                        statusJson.getString("GuestName"),
                                        statusJson.getString("ProductName"),
                                        statusJson.getString("ProductType"),
                                        statusJson.getString("NoTable"),
                                        statusJson.getString("Status"),
                                        statusJson.getString("TotalPrice")
                                );
                            } else {
                                Toast.makeText(getContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void one rrorResponse(VolleyError error) {
                        Toast.makeText(getContext(),error.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> params = new HashMap<>();
                params.put("tablecode",TableCode);
                return params;
            }
        };

        VolleySingleton.getInstance(getContext()).addToRequestQueue(stringRequest);
    }

I dont know how to convert it from JSONObject to JSONArray

here is my Setter and getter class

package com.example.pesanpalgading20.Getter.Status;

import java.util.ArrayList;

public class Status {
    private String OrderCode,Name,FoodName,TypeFood,NoTable,Status,TotalPrice;

    public Status(){

    }

    public Status(String orderCode, String name, String foodName, String typeFood, String noTable, String status, String totalPrice) {
        OrderCode = orderCode;
        Name = name;
        FoodName = foodName;
        TypeFood = typeFood;
        NoTable = noTable;
        Status = status;
        TotalPrice = totalPrice;
    }

    public String getOrderCode() {
        return OrderCode;
    }

    public void setOrderCode(String orderCode) {
        OrderCode = orderCode;
    }

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }

    public String getFoodName() {
        return FoodName;
    }

    public void setFoodName(String foodName) {
        FoodName = foodName;
    }

    public String getTypeFood() {
        return TypeFood;
    }

    public void setTypeFood(String typeFood) {
        TypeFood = typeFood;
    }

    public String getNoTable() {
        return NoTable;
    }

    public void setNoTable(String noTable) {
        NoTable = noTable;
    }

    public String getStatus() {
        return Status;
    }

    public void setStatus(String status) {
        Status = status;
    }

    public String getTotalPrice() {
        return TotalPrice;
    }

    public void setTotalPrice(String totalPrice) {
        TotalPrice = totalPrice;
    }
}

so how do I set the value of the each JSON to SetterandGetter class ?

CodePudding user response:

 try {
        JSONObject obj = new JSONObject(response);

        //if no error in response
        if (!obj.getBoolean("error")) {

            //getting Status from response
            JSONArray statusJson = obj.getJSONArray("status");
            
            for (int i = 0; i < statusJson.length(); i  ) {
                Status status = new Status(
                        statusJson.getJSONObject(i).getString("OrderCode"),
                        statusJson.getJSONObject(i).getString("GuestName"),
                        statusJson.getJSONObject(i).getString("ProductName"),
                        statusJson.getJSONObject(i).getString("ProductType"),
                        statusJson.getJSONObject(i).getString("NoTable"),
                        statusJson.getJSONObject(i).getString("Status"),
                        statusJson.getJSONObject(i).getString("TotalPrice")
                );

                // Add Status In your Array list and enjoy
            }
        } else {
            Toast.makeText(getContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

CodePudding user response:

You can use Gson library and convert your json to a model class

To do it first you have to add gson as a dependancy

implementation "com.google.code.gson:gson:2.8.6"

And then since your status in json is array use it like this

JSONArray status = obj.getJSONArray("status");
//Code to convert json array to arraylist of object
Arraylist<Status> arraylist = Gson().fromJson(
                    status.toString(),
                    new TypeToken<ArrayList<Status>>(){}.getType()
                )

Above code will store your json array status to arraylist variable

CodePudding user response:

so the gettin JSON array is completed but it still display one list from the array this is the code

public void StringRequest() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.STATUS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject obj = new JSONObject(response);
                            Toast.makeText(getContext(), response, Toast.LENGTH_SHORT).show();

                            //if no error in response
                            if (!obj.getBoolean("error")) {
                                Toast.makeText(getContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();





                                //getting Status from response
                                JSONArray statusJson = obj.getJSONArray("status");



                                for (int i = 0; i < statusJson.length(); i  ) {
                                    Status status = new Status(
                                            statusJson.getJSONObject(i).getString("OrderCode"),
                                            statusJson.getJSONObject(i).getString("GuestName"),
                                            statusJson.getJSONObject(i).getString("ProductName"),
                                            statusJson.getJSONObject(i).getString("ProductType"),
                                            statusJson.getJSONObject(i).getString("NoTable"),
                                            statusJson.getJSONObject(i).getString("Status"),
                                            statusJson.getJSONObject(i).getString("TotalPrice")
                                    );
                                    ArrayList<Status> statusList = new ArrayList<Status>();
                                    statusList.add(status);
                                    statusAdapter = new StatusAdapter(getActivity(),statusList);
                                    StatusListView.setAdapter(statusAdapter);

                                }

                            } else {
                                Toast.makeText(getContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void one rrorResponse(VolleyError error) {
                        Toast.makeText(getContext(),error.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> params = new HashMap<>();
                params.put("tablecode",TableCode);
                return params;
            }
        };

        VolleySingleton.getInstance(getContext()).addToRequestQueue(stringRequest);
    }

I dont know where to put the increment in the setting adapter in statusList.add(status);

edit : It solved! Thanks to @Pratik Fagadiya I put the setting adapter outside of the loop and it worked and added more than 1 list

  •  Tags:  
  • Related