如何使用Android排球获取并传递JSON数组?

时间:2017-08-21 10:31:23

标签: php android arrays json android-volley

我在Android Studio中遇到了如何使用Android Volley字符串请求来构建JSON数组的问题。

我的目标是每当用户输入正确的登录名和密码。它将带来该特定用户的其他价值,在我的情况下是 realname dept

我有这些JSON数组输出

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

通过以下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>

在Android Studio中,我目前的问题是无法在 try {} 中显示JSON数组。

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

}

感谢有人可以帮助我。感谢。

1 个答案:

答案 0 :(得分:0)

  1. 获取 JSON对象,就像这样
  2.   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);
            }