简体   繁体   English

如何使用Android Volley显示/请求JSON对象?

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

I'm having a problem in Android Studio on how to request JSON Object. 我在Android Studio中遇到有关如何请求JSON对象的问题。

My Logcat can only print String onResponse but not JSONObject value. 我的Logcat只能在String onResponse上打印String,而不能在JSONObject值上打印。 I'm having a problem in line try{} inside AccessActivity.java 我在AccessActivity.java中的try {}行中遇到问题

My code explanation as below. 我的代码说明如下。

I have these JSON Object output that I fetch from mysql database. 我有从mysql数据库中获取的这些JSON对象输出。

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

In my PHP code, this is how I fetch the data and encode it as JSON Object. 在我的PHP代码中,这就是我获取数据并将其编码为JSON对象的方式。

access.php 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";
        }
    }
?>

But my problem occurs in Android Studio, 但是我的问题出现在Android Studio中,

  1. I can't even print Log.e(TAG, "JSON Object =" + jsonObject); 我什至无法打印Log.e(TAG,“ JSON Object =” + jsonObject);
  2. I can't intent JSON Object value into next activity. 我无法将JSON对象的值用于下一个活动。

Here's my code . 这是我的代码。

AccessActivity.java 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);
            }
        });
    }
}

UPDATE : 更新:

my logcat display this 我的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)

Appreciate if someone can help me to solve this problem. 感谢有人可以帮助我解决此问题。 Thanks. 谢谢。

Try this. 尝试这个。

In the AccessActivity 在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);

change 更改

LoginActivity.this.startActivity(intent);

to

AccessActivity.this.startActivity(intent);

In the NextActivity 在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");

Edited 已编辑

change 更改

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

to

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

And according to your code. 并根据您的代码。 You need to make sure that your current Activity is com.apps.test.AccessActivity or com.apps.test.AccessActivity . 您需要确保当前的Activity是com.apps.test.AccessActivitycom.apps.test.AccessActivity

Edited 已编辑

change to 改成

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();
        }
 }

Your requesting a JsonObject? 您正在请求一个JsonObject吗? You seem to have a grasp on StringRequest, so ill keep it simple. 您似乎对StringRequest有所了解,因此请保持简单。 Change your StringRequest to a JsonObjectRequest . 将您的StringRequest更改为JsonObjectRequest

Problem : 问题:

As you can see in your logcat the response that you get from the server is success_access{"access":"PA001","password":"123","fullname":"ARCADE","branch":"HQ","section":"HQ"} 正如您在logcat中看到的那样,从服务器获得的响应是success_access{"access":"PA001","password":"123","fullname":"ARCADE","branch":"HQ","section":"HQ"}

First, this is not a valid JSON . 首先,这不是有效的JSON Also, that is the value of the response variable. 同样,这就是response变量的值。 Now, your response.equals("success_access") will never return true, and hence the code control will never enter the if block. 现在,您的response.equals("success_access")将永远不会返回true,因此代码控件将永远不会进入if块。

Solution : 解决方案:

Ideally, there should be no extra string like success_access , insted your response should be a JSON object ALWAYS containing one specified field (the result feild for example). 理想情况下,不应有诸如success_access类的多余字符串,否则您的响应应该是一个始终包含一个指定字段的JSON对象(例如, result字段)。 To show success, your JSON will look something like : 为了显示成功,您的JSON如下所示:

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

And in case of failure : 并且在失败的情况下:

{
    result : "access_failed"
} 

And then your code should convert the respose string into a JSON (your server code should make sure that it returns a valid JSON always) check for the value of the result field and proceed further. 然后,您的代码应将respose字符串转换为JSON (您的服务器代码应确保其始终返回有效的JSON),以检查result字段的值并继续进行操作。

Quick Fix : 快速解决 :

Change your code to : 将您的代码更改为:

  ....
  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