按钮的代码是
LogIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, login_user, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray myData = response.getJSONArray("myData");
Toast.makeText(LoginActivity.this, "JSoN ARRAY SIZE "+myData.length(), Toast.LENGTH_SHORT).show();
if (myData.length() > 1)
Toast.makeText(LoginActivity.this, "THIS ISNT SUPPOSED TO HAPPEN", Toast.LENGTH_SHORT).show();
JSONObject dataObject = myData.getJSONObject(0);
Users user=new Users();
user.setId(dataObject.getInt("user_id"));
user.setUserName(dataObject.getString("user_name"));
user.setPassword(dataObject.getString("password"));
user.setEmail(dataObject.getString("email"));
user.setBirthday(dataObject.getString("birthday"));
user.setIs_Admin(dataObject.getBoolean("is_admin"));
db.InsertUser(user);//adds the user into a sqllite db
Toast.makeText(LoginActivity.this, "Welcome "+user.getUserName(), Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(LoginActivity.this, "Json eror::---"+e, Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, "Volley-error:"+error, Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("USERNAME", UserName.getText().toString());
parameters.put("PASSWORD", Password.getText().toString());
return parameters;
}
};
requestQueue.add(jsonObjectRequest);
}
});
php代码:
<?php
include_once("connection.php");
if (isset($_POST['USERNAME']) && isset($_POST['PASSWORD'])) {
$username = $_POST['USERNAME'];
$password = $_POST['PASSWORD'];
$query = "SELECT * FROM `users` WHERE user_name='$username' AND password="$password"";
$result = mysqli_query($conn, $query);
$number_of_rows = mysqli_num_rows($result);
$temp_array = array();
if ($number_of_rows > 0) {
while($row = mysqli_fetch_assoc($result)){
$temp_array[] = $row;
}
}
header('Content-Type: application/json');
echo json_encode(array("myData"=>$temp_array));
mysqli_close($conn);
?>
答案 0 :(得分:0)
你能否加入你从php那里收到的Json,他们可能会被括在一个方括号[]而不是Curley括号{}
中