eladrich
eladrich

Reputation: 755

Read from webservice using httpclient


I've got an android application that is supposed to read a mysql database from a web serice.
This is the code in the web serivce:

$q=mysql_query("SELECT * FROM Rates");
while($e=mysql_fetch_assoc($q))
       $output[]=$e;

print(json_encode($output));
mysql_close();

and this is the code in my application:

public void getQuery() {
    String result = "";
     InputStream is;
    try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet("http://dakatora.co.il/android/androidsql.php");
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
    }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
            is = new InputStream() {

                @Override
                public int read() throws IOException {
                    // TODO Auto-generated method stub
                    return 0;
                }
            };
    }
    try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            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());
    }

    //parse json data

For some reason the result string doesn't get the query, instead is gets just "\n". Can someone please tell me what's wrong?

Upvotes: 2

Views: 510

Answers (1)

Marc B
Marc B

Reputation: 360622

Your .php page isn't outputting anything. Try hitting the URL in your browser - you get a blank page. If the PHP code you posted is the entirety of the file, then you've forgotten to actually connect to the database. Check your server's error logs to see if the script is spitting out any errors (and/or turn on php's display_errors option).

If nothing else, try something like:

$q = mysql_query("SELECT * FROM Rates") or die(mysql_error());

It is poor practice to assume a query will succeed, even a trivial one like this. The SQL syntax may be perfect, but there's far too many OTHER reasons for things to go wrong to NOT have any kind of error handling.

Upvotes: 1

Related Questions