【问题标题】:Bool HTTP Response from PHP to Android从 PHP 到 Android 的布尔 HTTP 响应
【发布时间】:2012-03-02 00:27:46
【问题描述】:

我在实现一个检查 MySQL 数据库的值然后根据值的存在返回“True”或“False”的程序时遇到了一个小问题。我可以让 PHP 使用以下代码返回值(在此示例中以“A”开头)(它还在 Java 日志中显示匹配的行):

<?php
   mysql_connect("host","username","password");
   mysql_select_db("Deal");
   $sql=mysql_query("select * from CITY where CITY_NAME like 'A%'");
   while($row=mysql_fetch_assoc($sql))
   $output[]=$row;
   print(json_encode($output));
   mysql_close();
?>

我只是想检查是否有一条记录满足查询(在本例中是一个以“A”开头的城市),然后返回“True”或“False”并将其打印在 ddms 日志中.

我一直在尝试实现以下内容,但我没有返回任何内容。

<?php

mysql_connect("host","username","password");
mysql_select_db("Deal");

$sql = mysql_query("select * from CITY where CITY_NAME like 'A%'") or die(mysql_error());
if ($sql) {
    if(mysql_num_rows($sql) == 0) {
            $row = "False";
            print(json_encode($row);
            mysql_close();
    }

    else {
        $row = "True";
        //while($row = mysql_fetch_assoc($sql))
        //$output[]=$row;
        print(json_encode($row);
        //print(json_encode($output));
        mysql_close();
    }
}
?>

这是我的 Android 代码:

    public class CityActivity extends ListActivity {

    JSONArray jArray;
    String result = null;
    InputStream is = null;
    StringBuilder sb=null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

     ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    //http post
    try{
         HttpClient httpclient = new DefaultHttpClient();
         HttpPost httppost = new HttpPost("http://www.example.com/example.php");
         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
         HttpResponse response = httpclient.execute(httppost);
         HttpEntity entity = response.getEntity();
         is = entity.getContent();
         }catch(Exception e){
             Log.e("log_tag", "Error in http connection"+e.toString());
        }
    //convert response to string
    try{
          BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
           sb = new StringBuilder();
           sb.append(reader.readLine() + "\n");

           String line="0";
           while ((line = reader.readLine()) != null) {
                          sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
            }catch(Exception e){
                  Log.e("log_tag", "Error converting result "+e.toString());
            }
    //paring datag

    try{
          jArray = new JSONArray(result);
          JSONObject json_data=null;
          for(int i=0;i<jArray.length();i++){
                 String myString ="";
                 json_data = jArray.getJSONObject(i);
                 int ct_id = json_data.getInt("CITY_ID");
                 String ct_name = json_data.getString("CITY_NAME");
                 myString = Integer.toString(ct_id);
                 Log.i(ct_name, myString);
             } 
          }
          catch(JSONException e1){
              Toast.makeText(getBaseContext(), "No City Found" ,Toast.LENGTH_LONG).show();
          } catch (ParseException e1) {
                e1.printStackTrace();
        }
    }
}

如果您有任何建议,请告诉我。我真的很感激。谢谢!

【问题讨论】:

    标签: java php android mysql httpresponse


    【解决方案1】:

    您已经足够接近,但不只是将结果返回为 True 或 False。我强烈推荐一个占位符,例如{result: True / False} 作为响应。 True 可以添加更多数据,而 false 则不发送任何数据。

    因此在 android 端你会一直得到 JSONObject 。所以检查一下

     if (result != null && result.has("result")){
          if(result.optBoolean("result", false)){
                  // Now parse and get all your data
          }else{
             // If you are running is thread, then run on UI thread and show Toast
         }
     }
    

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-20
      • 2012-09-01
      • 2018-10-17
      • 2019-04-16
      • 1970-01-01
      相关资源
      最近更新 更多