gpt4 book ai didi

java - 如何从php获取json的COUNT(id)值到android

转载 作者:行者123 更新时间:2023-11-29 19:40:44 26 4
gpt4 key购买 nike

当我尝试获取数据库的 Count(id) 值时,出现错误。我想获取该值并将他放入textView中。

这是我的java代码(响应已经构造为数组)

public  void  test3(View rootView){ 

String result = null;

try
{
tv = (TextView) rootView.findViewById(R.id.textView);
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());

String url = "http://brunos.000webhostapp.com/teste/listar_divisoes.php";

final String finalResult = result;
JsonArrayRequest jsonRequest = new JsonArrayRequest
(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
try {
JSONObject jObj = new JSONObject(finalResult);
String count= jObj.getString("COUNT(id)");
tv.setText(count);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonRequest);
}

这是我的 php 代码:

<?php
include 'database.php';
$pDatabase = Database::getInstance();
$sql = "SELECT COUNT(id) FROM divisao;";
$result = $pDatabase->query($sql);
$rows = array();
while($temp = mysqli_fetch_assoc($result)) {
$rows[] = $temp;
}
echo json_encode($rows);
?>

最佳答案

您没有读取 JSONArray 响应对象:

 public void onResponse(JSONArray response) {
try {
JSONObject jObj = new JSONObject(finalResult);
String count= jObj.getString("COUNT(id)");
tv.setText(count);
} catch (JSONException e) {
e.printStackTrace();
}

}

应该是:

 public void onResponse(JSONArray response) {
try {
JSONObject jObj = new JSONObject(response.get(0));
String count= jObj.getString("COUNT(id)");
tv.setText(count);
} catch (JSONException e) {
e.printStackTrace();
}

}

关于java - 如何从php获取json的COUNT(id)值到android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41370839/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com