如何 display/request JSON Object using Android Volley?
How to display/request JSON Object using Android Volley?
我在 Android Studio 中遇到有关如何请求 JSON 对象的问题。
我的 Logcat 只能打印 String onResponse 但不能打印 JSONObject 值。我在 AccessActivity.java
中的 try{} 行遇到问题
我的代码解释如下。
我有这些 JSON 从 mysql 数据库中获取的对象输出。
{
"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 中,
- 我什至无法打印 Log.e(TAG, "JSON Object =" + jsonObject);
- 我无法将 JSON 对象值写入下一个 activity。
这是我的代码。
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)
感谢有人能帮我解决这个问题。谢谢。
试试这个。
在访问Activity
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);
下一个Activity
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.AccessActivity
或 com.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")
永远不会 return 为真,因此代码控制永远不会进入 if
块。
解法:
理想情况下,不应有像 success_access
这样的额外字符串,因为您的响应应该是一个 JSON
对象,始终包含一个指定字段(例如 result
字段)。为了显示成功,您的 JSON 将类似于:
{
result : "success_access",
/* other parameters down here */
}
如果失败:
{
result : "access_failed"
}
然后您的代码应将 respose
字符串转换为 JSON
(您的服务器代码应确保它 return 始终是有效的 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);
....
我在 Android Studio 中遇到有关如何请求 JSON 对象的问题。
我的 Logcat 只能打印 String onResponse 但不能打印 JSONObject 值。我在 AccessActivity.java
中的 try{} 行遇到问题我的代码解释如下。
我有这些 JSON 从 mysql 数据库中获取的对象输出。
{
"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 中,
- 我什至无法打印 Log.e(TAG, "JSON Object =" + jsonObject);
- 我无法将 JSON 对象值写入下一个 activity。
这是我的代码。
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)
感谢有人能帮我解决这个问题。谢谢。
试试这个。
在访问Activity
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);
下一个Activity
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.AccessActivity
或 com.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")
永远不会 return 为真,因此代码控制永远不会进入 if
块。
解法:
理想情况下,不应有像 success_access
这样的额外字符串,因为您的响应应该是一个 JSON
对象,始终包含一个指定字段(例如 result
字段)。为了显示成功,您的 JSON 将类似于:
{
result : "success_access",
/* other parameters down here */
}
如果失败:
{
result : "access_failed"
}
然后您的代码应将 respose
字符串转换为 JSON
(您的服务器代码应确保它 return 始终是有效的 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);
....