我想使用JSON Parsing获取特定列的记录。这是我的PHP MySql的屏幕截图,其中包含一些数据。
以上是我想在微博我的Android应用程序中获取cat_id = 2的所有记录。但是我无法理解如何做到这一点。可以请一些人帮助我。谢谢你提前。
答案 0 :(得分:0)
创建一个PHP代码来获取行并将其打印在JSON fromat
中 $res=mysql_query("select * from table_name where cat_id = '2'") or die(mysql_error());
$assInfo = array();
$num=mysql_num_rows($res);
if($num>0){
$obj=mysql_fetch_array($res);
$assInfo["first"]=$obj["column_name"];
$assInfo["second"]=$obj["another_column"];
array_push($response["info"], $assInfo);
}else{
$response["success"] = 0;
}
echo json_encode($response);
并在android中启动Asynctask以在后台抓取打印文本。
public class gettingData extends AsyncTask<Void, Void, Void> {
private String jsonResult;
public gettingData() {
}
@Override
protected Void doInBackground(Void... arg0) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("canpass", "herevalue"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent())
.toString();
Log.v("jr", jsonResult);
}
catch (ClientProtocolException e) {
Log.e("e", "error1");
e.printStackTrace();
} catch (IOException e) {
Log.e("e", "error2");
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if (jsonResult != null) {
try {
if (jsonResponse.optString("success").matches("0")) {
//your code for no rows selected
}else{
JSONArray jsonMainNode = jsonResponse.optJSONArray("info");
JSONObject jsonChildNode = jsonMainNode.getJSONObject(0);
String first = jsonChildNode.optString("first");
String second = jsonChildNode.optString("second");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, "Connection Time Out", Toast.LENGTH_LONG)
.show();
}
}
在您的活动中执行此类 -
new gettingData().execute();