2014-08-30 33 views
0

我想使用JSON解析獲取特定列的記錄。這裏是我的包含一些數據的PHP MySql的屏幕截圖。 enter image description hereAndroid JSON取特定列的記錄

這裏是上面我想獲取我的Android應用程序中的所有cat_id = 2的記錄在微調。但我不明白如何做到這一點。可以請一個人幫我。先謝謝了。

+0

創建web服務,讓üJSON對象和Android技術 – 2014-08-30 10:43:58

回答

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(); 
+0

閱讀: - 可在可能的Android使用JSON沒有PHP編寫查詢。 – tazeen 2014-09-01 05:23:56

+0

我認爲沒有@tazeen – 2014-09-01 10:48:43

+0

: - 我已經解決了這個查詢。 – tazeen 2014-09-01 11:01:41