简体   繁体   English

如何使用Android Volley获取和传递JSON Array?

[英]How to get and passed JSON Array using Android volley?

I'm having a problem in Android Studio on how to intent JSON Array using Android Volley String Request. 我在Android Studio中遇到有关如何使用Android Volley String Request意图JSON Array的问题。

My goal is whenever user enter correct login and password. 我的目标是每当用户输入正确的登录名和密码时。 it will bring along other value of that particular user which is in my case is realname and dept . 它将带来该特定用户的其他值,在我的情况下,该值为实名部门

I have these JSON Array output 我有这些JSON数组输出

{
    "login":"ID001",
    "realname":"Tom",
    "dept":"ICTD"
}

Produce by this PHP code below 通过下面的此PHP代码生成

Login.php Login.php

<?php
    $conn = mysqli_connect("","","","");

    if(
        isset($_POST['login']) &&
        isset($_POST['password'])
    ){
        $login = $_POST['login'];
        $password = $_POST['password'];
        $sql = "SELECT * FROM users WHERE login = '$login' AND pw = '$password' ";
        $result = mysqli_query($conn, $sql);
        if($result && mysqli_num_rows($result) > 0){
            while($row = mysqli_fetch_array($result)){
                $logindb     = $row['login'];
                $realnamedb  = $row['realname'];
                $deptdb      = $row['dept'];
                echo "success_login";
                $response = array('login' => $logindb, 'real_name' => $real_namedb, 'dept' => $deptdb);
                echo json_encode($response);
            }
        mysqli_free_result($result);
        } else {
            echo "login_failed";
        }
    }
?>
<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <form action="login.php" method="post">
        <table>
            <tr>
                <td>Login :</td>
                <td><input type="text" name="login"></td>
            </tr>
            <tr>
                <td>Password :</td>
                <td><input type="text" name="password"></td>
            </tr>
            <tr>
                <td><input type="submit" name="Submit" value="Login"></td>
            </tr>
        </table>
    </form>
</body>
</html>

In Android Studio, my current problem is the JSON Array can't be display inside try{} . 在Android Studio中,我当前的问题是JSON数组无法在try {}内部显示。

LoginActivity.java LoginActivity.java

  public class LoginActivity extends AppCompatActivity{

    EditText etLogin, 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);


        etLogin         = (EditText)findViewById(R.id.etLogin);
        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/login.php";
                StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        if(response.equals("success_login")){
                            try {
                                JSONObject jsonObject   = new JSONObject(response);
                                JSONArray booking       = jsonObject.getJSONArray("login");

                                if(booking.length() > 0){
                                    for (int countItem = 0; countItem<booking.length(); countItem++){

                                        JSONObject bookingObject    = booking.getJSONObject(countItem);
                                        final String login                 = bookingObject.isNull("login");
                                        final String realname              = bookingObject.isNull("realname");
                                        final String dept                  = bookingObject.isNull("dept");


                                        Intent intent = new Intent(LoginActivity.this, NextActivity.class);
                                        intent.putExtra("login", login);
                                        intent.putExtra("realname", realname);
                                        intent.putExtra("dept", dept);
                                        LoginActivity.this.startActivity(intent);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else{
                            Toast.makeText(getApplicationContext(), "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("login", etLogin.getText().toString());
                        params.put("password", etPassword.getText().toString());
                        return params;
                    }
                };
                MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
            }
        });
    }

}

Appreciate if someone can help me. 感谢有人可以帮助我。 Thanks. 谢谢。

  1. Get JSON object like this 获取这样的JSON对象

  String url = "http://localhost/login.php";
            StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                         Log.e("response>>>>","",response);
                    if(response.equals("success_login")){
                        try {
                            JSONObject jsonObject   = new JSONObject(response);



                                    final String login                 = jsonObject.getString("login");
                                    final String realname              = jsonObject.getString("realname");
                                    final String dept                  = jsonObject.getString("dept");


                                    Intent intent = new Intent(LoginActivity.this, NextActivity.class);
                                    intent.putExtra("login", login);
                                    intent.putExtra("realname", realname);
                                    intent.putExtra("dept", dept);
                                    LoginActivity.this.startActivity(intent);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else{
                        Toast.makeText(getApplicationContext(), "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("login", etLogin.getText().toString());
                    params.put("password", etPassword.getText().toString());
                    return params;
                }
            };
            MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM