将JSON对象响应传递给TextView以进行测试时出错

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将JSON对象响应传递给TextView以进行测试时出错相关的知识,希望对你有一定的参考价值。

我看到了其他帖子,但没有用,我仍然收到错误,为什么我一直收到此错误。我一直在尝试将JSONObject响应传递给TextView,以在它尝试将其传递给某些表之前检查它是否确实包含对象。似乎基于该错误,我对分支没有任何价值?为什么?我认为我的JSON对象与邮递员结果匹配。

这是我的错误:

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"

此问题的主要代码:

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类

<?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代码

<?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);

以上代码中使用的db_Operation的相关代码

         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;
        

邮递员输出


    "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"
        
    ]

我是正确的,对吗?我有一个JSON对象,在JSON对象内部,有一个数组是Branches,其中有5个用逗号分隔的对象?这意味着我正在正确执行JSON对象请求吗?

这里是发送请求的PostMan屏幕。

enter image description here

答案

UPDATE

我认为您可能会选择StringRequest,而不是JsonObjectRequest,如下所示。

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:

setContentType丢失,并且传递了String参数而不是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);

以上是关于将JSON对象响应传递给TextView以进行测试时出错的主要内容,如果未能解决你的问题,请参考以下文章

Qualtrics - 将响应传递给 Javascript 以进行 API 调用

合并/转换textview与/到drawable

将 IOptions 传递给 .Net 核心中间件类以进行 json 配置检索

Ansible:从JSON响应创建变量

使用 Retrofit 发送 POST 请求并接收 Json 响应无法使用响应数据我需要将其传递给另一个活动

测试 Postman 响应体 Json 是数组还是对象