簡體   English   中英

如何使用Android Volley顯示/請求JSON對象?

[英]How to display/request JSON Object using Android Volley?

我在Android Studio中遇到有關如何請求JSON對象的問題。

我的Logcat只能在String onResponse上打印String,而不能在JSONObject值上打印。 我在AccessActivity.java中的try {}行中遇到問題

我的代碼說明如下。

我有從mysql數據庫中獲取的這些JSON對象輸出。

{
    "access":"PA001",
    "password":"123",
    "fullname":"ARCADE",
    "branch":"HQ",
    "section":"MPR"
}

在我的PHP代碼中,這就是我獲取數據並將其編碼為JSON對象的方式。

access.php

<?php
    $conn = mysqli_connect("","","","");
    if(
        isset($_POST['access']) &&
        isset($_POST['password'])
    ){
        $access     = $_POST['access'];
        $password   = $_POST['password'];
        $sql = "SELECT * FROM table WHERE access = '$access' AND password = '$password' ";
        $result = mysqli_query($conn, $sql);
        if($result && mysqli_num_rows($result) > 0){
            while($row = mysqli_fetch_array($result)){

                $accessdb     = $row['access'];
                $passworddb   = $row['password'];
                $fullnamedb   = $row['fullname'];
                $branchdb     = $row['branch'];
                $sectiondb    = $row['section'];

                echo "success_access";

                $response = array('access' => $accessdb, 'password' => $passworddb, 'fullname' => $fullnamedb, 'branch' => $branchdb, 'section' => $sectiondb);
                echo json_encode($response);
            }
        mysqli_free_result($result);
        } else {
            echo "access_failed";
        }
    }
?>

但是我的問題出現在Android Studio中,

  1. 我什至無法打印Log.e(TAG,“ JSON Object =” + jsonObject);
  2. 我無法將JSON對象的值用於下一個活動。

這是我的代碼。

AccessActivity.java

public class AccessActivity extends AppCompatActivity{

    final String TAG = this.getClass().getName();
    EditText etAccess, etPassword;
    Button bLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        etAccess        = (EditText)findViewById(R.id.etAccess);
        etPassword      = (EditText)findViewById(R.id.etPassword);
        bLogin          = (Button)findViewById(R.id.bLogin);
        bLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url = "http://localhost/access.php";
                StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.e(TAG, "Response is = " + response);
                        if(response.equals("success_access")){
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                Log.e(TAG, "JSON Object is = " + jsonObject);

                                final String accessdb   = jsonObject.getString("access");
                                final String passworddb = jsonObject.getString("password");
                                final String fullnamedb = jsonObject.getString("fullname");
                                final String branchdb   = jsonObject.getString("branch");
                                final String sectiondb  = jsonObject.getString("branch");

                                Intent intent = new Intent(AccessActivity.this, NextActivity.class);
                                intent.putExtra("access",   accessdb);
                                intent.putExtra("password", passworddb);
                                intent.putExtra("fullname", fullnamedb);
                                intent.putExtra("branch",   branchdb);
                                intent.putExtra("section",  sectiondb);
                                AccessActivity.this.startActivity(intent);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else{
                            Toast.makeText(getApplicationContext(), "Access Error", Toast.LENGTH_SHORT).show();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), "Volley Error", Toast.LENGTH_SHORT).show();
                    }
                }){
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> params = new HashMap<>();
                        params.put("access",   etAccess.getText().toString());
                        params.put("password", etPassword.getText().toString());
                        return params;
                    }
                };
                MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
            }
        });
    }
}

更新:

我的logcat顯示此

08-22 10:22:22.059 19801-19908/com.apps.test D/NetworkSecurityConfig: No Network Security Config specified, using platform default
08-22 10:22:22.064 19801-19801/com.apps.test E/my.com.apps.test.Activity: Response is = success_access{"access":"PA001","password":"123","fullname":"ARCADE","branch":"HQ","section":"HQ"}
08-22 10:22:22.112 19801-19825/com.apps.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303200)
08-22 10:22:22.128 19801-19825/com.apps.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303200)
08-22 10:22:22.134 19801-19825/com.apps.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303200)
08-22 10:22:22.140 19801-19825/com.apps.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303200)
08-22 10:22:23.697 19801-19825/com.apps.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303200)
08-22 10:22:25.751 19801-19825/com.apps.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303200)
08-22 10:22:25.780 19801-19825/com.apps.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303200)

感謝有人可以幫助我解決此問題。 謝謝。

嘗試這個。

在AccessActivity中

 Intent intent = new Intent(AccessActivity.this, NextActivity.class);
 intent.putExtra("access",   accessdb);
 intent.putExtra("password", passworddb);
 intent.putExtra("fullname", fullnamedb);
 intent.putExtra("branch",   branchdb);
 intent.putExtra("section",  sectiondb);
 AccessActivity.this.startActivity(intent);

更改

LoginActivity.this.startActivity(intent);

AccessActivity.this.startActivity(intent);

在NextActivity中

Intent intent = getIntent();
String access = intent.getStringExtra("access");
String password = intent.getStringExtra("password");
String fullname = intent.getStringExtra("fullname");
String branch = intent.getStringExtra("branch");
String section = intent.getStringExtra("section");

已編輯

更改

if(response.equals("success_access")){
}

if(response.contains("success_access")){
}

並根據您的代碼。 您需要確保當前的Activity是com.apps.test.AccessActivitycom.apps.test.AccessActivity

已編輯

改成

if (response.contains("success_access")) {
        String res = response.substring(response.indexOf("{"));
        try {
            JSONObject jsonObject = new JSONObject(res);
            final String accessdb = jsonObject.getString("access");
            final String passworddb = jsonObject.getString("password");
            final String fullnamedb = jsonObject.getString("fullname");
            final String branchdb = jsonObject.getString("branch");
            final String sectiondb = jsonObject.getString("branch");
            Log.e("Tag", accessdb);

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

您正在請求一個JsonObject嗎? 您似乎對StringRequest有所了解,因此請保持簡單。 將您的StringRequest更改為JsonObjectRequest

問題:

正如您在logcat中看到的那樣,從服務器獲得的響應是success_access{"access":"PA001","password":"123","fullname":"ARCADE","branch":"HQ","section":"HQ"}

首先,這不是有效的JSON 同樣,這就是response變量的值。 現在,您的response.equals("success_access")將永遠不會返回true,因此代碼控件將永遠不會進入if塊。

解決方案:

理想情況下,不應有諸如success_access類的多余字符串,否則您的響應應該是一個始終包含一個指定字段的JSON對象(例如, result字段)。 為了顯示成功,您的JSON如下所示:

{
    result : "success_access",
    /* other parameters down here */
} 

並且在失敗的情況下:

{
    result : "access_failed"
} 

然后,您的代碼應將respose字符串轉換為JSON (您的服務器代碼應確保其始終返回有效的JSON),以檢查result字段的值並繼續進行操作。

快速解決 :

將您的代碼更改為:

  ....
  Log.e(TAG, "Response is = " + response);
  String result = response.replace("{.*}","");
  String jsonString = response.replace(result, "");

  if(result.equals("success_access")){
    try {
            JSONObject jsonObject = new JSONObject(jsonString);
    ....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM