Tan Jia Ming
Tan Jia Ming

Reputation: 465

Android HTTP POST to get response without JSON, and put in Toast

I wanted to test if my Android app can sucessfully get the response from a php page, without JSON. The php just contains echo "hello";, but I failed to Toast it. Closest solution I can find is, where I tried to put some parts of it into my code: How can I view the string sent from httppost?

My code as below (updated):

public void onClick(View v) {
    Thread t = new Thread() {
        @Override
        public void run() {
            Log.i("Threaded", "Inside thread!!!");
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://192.168.1.10/fyp/test.php");

            try {
                HttpResponse response = httpclient.execute(httppost);
                InputStream content = response.getEntity().getContent();
                Log.i("Connect", content.toString());

                BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
                StringBuilder sb = new StringBuilder();
                String line = null;

                while ((line = buffer.readLine()) != null) {
                    sb.append(line + "\n");
                }
                Log.i("Connect", sb.toString());

                handler.post(new Runnable() {
                    public void run() {       
                        showToastMessage("hello");       
                      }
                    });
            } catch (Exception e) {
                Log.e("Connect", "Fail");
                e.printStackTrace();
            }
        }

    };
}

The thread seems not running, where the line Log.i("Threaded", "Inside thread!!!"); is not showing in LogCat, which part am I doing wrongly? Note: handler has been declare in the class.

Upvotes: 3

Views: 1583

Answers (1)

Nicklas Gnejs Eriksson
Nicklas Gnejs Eriksson

Reputation: 3415

Make sure you perform the toast on the UI thread or else it will fail. Either use a Handler or wrap your network operation in a AsyncTask where you pass the result to the onPostExecute method which is processed by the UI thread.

http://developer.android.com/reference/android/os/AsyncTask.html

If this is not your problem, add logging to see that you get a response from the server and check your LogCat for the "hello"

Upvotes: 2

Related Questions