javaphpandroidpostmanjsonobjectrequest

Error in passing JSON object response to TextView for Testing purposes


I saw the other posts but its no use and I am still getting error why is it that I keep getting this error. I have been trying to pass my JSONObject response to my TextView to check if it really contains an object before I try and pass it to some tables. and it seems based on the error I am getting no value for Branches? why? I think my JSON Obj matches with my postman result.

Here is my error:

2019-11-10 09:21:51.577 14371-14371/com.example.sample1myapp W/System.err: org.json.JSONException: No value for Branches
2019-11-10 09:21:51.577 14371-14371/com.example.sample1myapp W/System.err:     at org.json.JSONObject.get(JSONObject.java:399)
2019-11-10 09:21:51.577 14371-14371/com.example.sample1myapp W/System.err:     at org.json.JSONObject.getJSONArray(JSONObject.java:594)
2019-11-10 09:21:51.577 14371-14371/com.example.sample1myapp W/System.err:     at com.example.sample1myapp.main.Functions.dash_branch.branch$1.onResponse(branch.java:100)
2019-11-10 09:21:51.577 14371-14371/com.example.sample1myapp W/System.err:     at com.example.sample1myapp.main.Functions.dash_branch.branch$1.onResponse(branch.java:96)
2019-11-10 09:21:51.577 14371-14371/com.example.sample1myapp W/System.err:     at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:90)
2019-11-10 09:21:51.578 14371-14371/com.example.sample1myapp W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
2019-11-10 09:21:51.578 14371-14371/com.example.sample1myapp W/System.err:     at android.os.Handler.handleCallback(Handler.java:883)
2019-11-10 09:21:51.578 14371-14371/com.example.sample1myapp W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:100)
2019-11-10 09:21:51.578 14371-14371/com.example.sample1myapp W/System.err:     at android.os.Looper.loop(Looper.java:214)
2019-11-10 09:21:51.578 14371-14371/com.example.sample1myapp W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:7356)
2019-11-10 09:21:51.578 14371-14371/com.example.sample1myapp W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
2019-11-10 09:21:51.578 14371-14371/com.example.sample1myapp W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
2019-11-10 09:21:51.578 14371-14371/com.example.sample1myapp W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2019-11-10 09:21:51.578 14371-14371/com.example.sample1myapp E/response: {"error":true,"message":"Error Occured 102"}

Main code for this problem:

public class branch extends AppCompatActivity {

    //getting the current sysID use in protected params
    private static final String KEY_SYS_ID = "sys_id";
    private int sys_Id = SharedPrefManager.getInstance(this).getUserid();

    //View Branch
    private static final String KEY_VB_ID = "branchid";
    private static final String KEY_VB_USER = "username";
    private static final String KEY_VB_PASSWORD = "password";
    private static final String KEY_VB_NAME = "branchname";
    private static final String KEY_VB_SYSID = "sys_id";
    private static final String KEY_VB_CREATED = "created";
    private static final String KEY_VB_UT = "user_type";

    private String url = "http://192.168.1.2/sample1/v1/viewBranches.php";

    private TextView testdata;
    private NestedScrollView nestedScrollView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_branch);
        if (!SharedPrefManager.getInstance(this).isLoggedIn()) {
            finish();
            startActivity(new Intent(this, login.class));
            return;
        }

        testdata = findViewById(R.id.testdatatv);
        nestedScrollView = findViewById(R.id.nested);

    }

    public void retrieve() {
         JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("Branches");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject branch = jsonArray.getJSONObject(i);

                                int viewBranchID = branch.getInt(KEY_VB_ID);
                                String viewBranchUser = branch.getString(KEY_VB_USER);
                                String viewBranchPassword = branch.getString(KEY_VB_PASSWORD);
                                String viewBranchName = branch.getString(KEY_VB_NAME);
                                int viewBranchSYSID = branch.getInt(KEY_VB_SYSID);
                                int viewBranchCreated = branch.getInt(KEY_VB_CREATED);
                                String viewBranchUT = branch.getString(KEY_VB_UT);

                                testdata.append(
                                        String.valueOf(viewBranchID)+""+
                                                viewBranchUser+""+
                                                viewBranchPassword+""+
                                                viewBranchName+""+
                                                String.valueOf(viewBranchSYSID)+""+
                                                String.valueOf(viewBranchCreated)+""+
                                                viewBranchUT+"\n\n");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Log.e("response", "" + response);
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("response", "" + error);

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put(KEY_SYS_ID, String.valueOf(sys_Id));
                return params;
            }

        };
        RequestHandler.getInstance(this).addToRequestQueue(jsonObjectRequest);
    }

    /**
     * Show populated Table
     */
    public void onTableshow(View view){
        //tableView = (TableView<String[]>) findViewById(R.id.tableView);
        //new bTSQLClient(branch.this).retrieve(tableView);
        retrieve();
    }

}

XML class

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".main.Functions.dash_branch.branch">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btnBack"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="30sp"
            android:layout_marginTop="30sp"
            android:onClick="onBack"
            android:padding="10sp"
            android:text="Back"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.008"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.0"></Button>

        <Button
            android:layout_toLeftOf="@id/btnAdd"
            android:padding="10sp"
            android:layout_marginTop="30sp"
            android:layout_gravity="center"
            android:onClick="onTableshow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Show">
        </Button>

        <Button
            android:id="@+id/btnAdd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginTop="30sp"
            android:layout_marginRight="30sp"
            android:onClick="onAddBranch"
            android:padding="10sp"
            android:text="+"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.008"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.0"></Button>
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/layoutviewbranch"
        android:padding="8sp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center">

        <androidx.core.widget.NestedScrollView
            android:id="@+id/nested"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/testdatatv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#000">
            </TextView>

        </androidx.core.widget.NestedScrollView>
    </RelativeLayout>
</LinearLayout>

PHP code

<?php
require_once '../DbOperations.php';

$response = array();

if($_SERVER['REQUEST_METHOD']=='POST'){
    if(isset($_POST['sys_id'])){
        $db = new DbOperations();

        if($db->select($_POST['sys_id'])){
            $user = $db->getBranchDataByID($_POST['sys_id']);
            $response['Branches'] = $user;

        }else{
            $response['error'] = true;
            $response['message'] = "Error Occured 101";
        }

    }else{
        $response['error'] = true;
        $response['message'] = "Error Occured 102";
    }
}
echo json_encode($response);

The related codes on db_Operation that were used on the above code

         public function select($sys_id){
            $stmt = $this->con->prepare("SELECT branchid FROM branch_Data WHERE sys_id = ?");
            $stmt->bind_param("i", $sys_id);
            $stmt->execute();
            $stmt->store_result();
            return $stmt->num_rows > 0;
        }
        //System Data
          public function getBranchDataByID($sys_id){
            $stmt = $this->con->prepare("SELECT * FROM branch_Data WHERE sys_id = ?");
            $stmt->bind_param("i",$sys_id);
            $stmt->execute();
            $result = $stmt->get_result();
            while($data = $result->fetch_assoc()){
                $branchinfo[]=$data;
            }
            return $branchinfo;
        }

POSTMAN OUTPUT

{
    "Branches": [
        {
            "branchid": 12,
            "username": "king",
            "password": "202cb962ac59075b964b07152d234b70",
            "branchname": "123branch",
            "sys_id": 8,
            "created": "2019-10-28 20:45:08",
            "user_type": "Branch"
        },
        {
            "branchid": 13,
            "username": "makoy",
            "password": "bda639c314e39023789c37d7a07469f9",
            "branchname": "makoy",
            "sys_id": 8,
            "created": "2019-10-28 20:50:41",
            "user_type": "Branch"
        },
        {
            "branchid": 14,
            "username": "foodbranch",
            "password": "202cb962ac59075b964b07152d234b70",
            "branchname": "foodbranch",
            "sys_id": 8,
            "created": "2019-10-28 22:01:59",
            "user_type": "Branch"
        },
        {
            "branchid": 15,
            "username": "081nao397",
            "password": "7815696ecbf1c96e6894b779456d330e",
            "branchname": "testingbranchname",
            "sys_id": 8,
            "created": "2019-11-08 08:21:01",
            "user_type": "Branch"
        },
        {
            "branchid": 16,
            "username": "testing101",
            "password": "7815696ecbf1c96e6894b779456d330e",
            "branchname": "rest",
            "sys_id": 8,
            "created": "2019-11-08 08:28:55",
            "user_type": "Branch"
        }
    ]
}

I am correct, right? I have one JSON Object, inside of JSON Object there is one array which is Branches which has 5 objects separated with commas? That means I am doing my JSON Object request correct right?

Here is the PostMan screen which sends the request.

enter image description here


Solution

  • UPDATE

    I think you might go for a StringRequest instead of a JsonObjectRequest as follows.

    StringRequest jsonObjReq = new StringRequest(Request.Method.POST, url,
            new com.android.volley.Response.Listener<String>() {
    
                @Override
                public void onResponse(String response) {
    
                    try {
                        JSONObject jsonObject = new JSONObject(response.toString());
    
                        // Parse your JSON data here. 
    
                    } catch (JSONException e) {
    
                    }
                }
            }, new com.android.volley.Response.ErrorListener() {
    
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.println("error:: " + error.toString());
        }
    })
    
    {
        @Override
        public String getBodyContentType() {
            return "application/x-www-form-urlencoded; charset=UTF-8";
        }
    
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put(KEY_SYS_ID, String.valueOf(sys_Id));
            return params;
        }
    };
    

    OLD:

    The setContentType is missing and passing String parameter instead of Integer.

    public void retrieve() {
    
         JSONObject param = new JSONObject();
    
         try {
            param.put("sys_id", sys_Id);
         } catch (JSONException e) {
            e.printStackTrace();
         }
    
         // Pass the param while creating the request
         JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
                Constants.viewbranches_url, param,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("Branches");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject branch = jsonArray.getJSONObject(i);
    
                                int viewBranchID = branch.getInt(KEY_VB_ID);
                                String viewBranchUser = branch.getString(KEY_VB_USER);
                                String viewBranchPassword = branch.getString(KEY_VB_PASSWORD);
                                String viewBranchName = branch.getString(KEY_VB_NAME);
                                int viewBranchSYSID = branch.getInt(KEY_VB_SYSID);
                                int viewBranchCreated = branch.getInt(KEY_VB_CREATED);
                                String viewBranchUT = branch.getString(KEY_VB_UT);
    
                                testdata.append(
                                        String.valueOf(viewBranchID)+""+
                                                viewBranchUser+""+
                                                viewBranchPassword+""+
                                                viewBranchName+""+
                                                String.valueOf(viewBranchSYSID)+""+
                                                String.valueOf(viewBranchCreated)+""+
                                                viewBranchUT+"\n\n");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Log.e("response", "" + response);
                        }
                    }
    
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("response", "" + error);
    
            }
        }) {
    
            // Set the content type here
            @Override
            public String getBodyContentType() {
                return "application/x-www-form-urlencoded; charset=UTF-8";
            }
    
        };
        RequestHandler.getInstance(this).addToRequestQueue(jsonObjectRequest);
    }