0

I have a slight problem implementing a program that checks a MySQL database for a value and then returns "True" or "False" depending on the value's existence. I can get the PHP to return the values (that start with "A" in this example) by using the following code (it also displays the matching rows in the Java log):

<?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();
?>

I simply want to check to see if there is one record that satisfies the query (one city that starts with "A" in this example) and then returns either "True" or "False" and prints it in the ddms log.

I've been trying to implement something like the following, but I'm not returning anything.

<?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();
    }
}
?>

And here is my Android Code:

    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();
        }
    }
}

If you have any suggestions, please let me know. I'd really appreciate it. Thanks!

1 Answer 1

1

You are close enough but don't just return result as True or False. i would strongly recommend a place holder e.g. {result: True / False} as response. On True you can add more data and false just don't send any data.

Hence On android side you will get JSONObject all the time . So just check

 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
     }
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.