gpt4 book ai didi

php - 如何从服务器获取计数值到android中的json?

转载 作者:行者123 更新时间:2023-11-30 02:54:01 25 4
gpt4 key购买 nike

我正在尝试在 android 中使用 json 解析和 php 检索我的服务器表中的行数。我在 php 中完成了以下编码,我也得到了值,但我不知道如何处理 json。请逐步指导我该做什么或我哪里出错了。我的代码和错误日志如下:

php代码:

<?php
mysql_connect("localhost","user","pswd");
mysql_select_db("demo");
$username= (isset($_POST['receivenumber'])) ? $_POST['receivenumber'] : '';
$q=mysql_query("SELECT COUNT(receivenumber) FROM `addtasknew` where `receivenumber` = '$username'") or die(mysql_error());
$row=mysql_fetch_assoc($q);
print (json_encode($row));
mysql_close();
?>

android中的json代码

   String result = null;
InputStream is = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mydomainname.org/task/getmytaskcount.php");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// String h="123";
//nameValuePairs.add(new BasicNameValuePair("to",h.toString()));
nameValuePairs.add(new BasicNameValuePair("receivenumber","9595959595"));

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);

HttpEntity entity = response.getEntity();
is = entity.getContent();

Log.e("log_tag", "connection success "+nameValuePairs);

}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
Toast.makeText(getActivity(), "Connection fail", Toast.LENGTH_SHORT).show();

}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,HTTP.UTF_8),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");

}
is.close();

result=sb.toString();
Log.e("log_tag", "result "+result.toString());
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
Toast.makeText(getActivity(), " Input reading fail", Toast.LENGTH_SHORT).show();

}
try
{

// I don't know wht to do here to get the count value
JSONArray jArray = new JSONArray(result);

Log.w("Lengh",""+jArray);
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getActivity(), "JsonArray fail", Toast.LENGTH_SHORT).show();
}

错误日志:

  E/log_tag(2386): result ?{"COUNT(receivenumber)":"2"}
E/log_tag(2386): Error parsing data org.json.JSONException: Value {"COUNT(receivenumber)":"2"} of type org.json.JSONObject cannot be converted to JSONArray

最佳答案

您正试图将您的 JSON 解释为 JSONArray,但它是一个 JSONObject

要检索您的值,试试这个:

JSONObject jObj = new JSONObject(result);
String count= jObj.getString("COUNT(receivenumber)");

你可以查看这个tutorial了解有关 Android 中的 JSON 的更多信息。

关于php - 如何从服务器获取计数值到android中的json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23627056/

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