0

I've try to get data from my web /http://localhost/android_connection/getHttpGet.php which follow the code from this site,http://www.thaicreate.com/mobile/android-httpget-httppost.html.

The result of "/http://localhost/android_connection/getHttpGet.php" just after following this line :

Server Date/Time : 2014-06-04 04:28:49

I'm using Xampp for my localhost.

In android programming the code after >> HttpResponse response = client.execute(httpGet) doesn't run by catching log.e. Log.e("error1.1","Before try"); and Log.e("error1.2","Before HttpResponse"); only appear on my LogCat.

I don't know how to fix plz help me, by the way i'm a beginner in programming of using webserver via android application.

public class MainActivity extends Activity {

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Permission StrictMode


        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        final TextView result = (TextView) findViewById(R.id.result);
        final Button btnGet = (Button) findViewById(R.id.btnGet);

        btnGet.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                String url = "http://localhost/android_connection/getHttpGet.php";
                String resultServer  = getHttpGet(url);
                result.setText(resultServer);
            }
        });
    }

    public String getHttpGet(String url) {

        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        Log.e("error1.1","Before try");
        try {
            Log.e("error1.2", "Before HttpResponse");
            HttpResponse response = client.execute(httpGet);
            Log.e("error1.3", "End of HttpResponse");
            StatusLine statusline = response.getStatusLine();
            int statusCode = statusline.getStatusCode();
            if (statusCode == 200) { // Status OK
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    str.append(line);
                    Log.e("error2","line : " + line);
                }
            }


        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return str.toString();
    }
}
Kevin Ji
  • 10,479
  • 4
  • 40
  • 63
user3705368
  • 11
  • 1
  • 1
  • 1
    I think there is an exception on this line `HttpResponse response = client.execute(httpGet);` Please check your logcat and update into your question – ductran Jun 04 '14 at 03:58
  • 1
    I think you would be getting NetworkOnMainThread Exception. If so, call getHttpGet() in AsyncTask or new Thread(){@Override public void run(){//code here}}.start(); – QAMAR Jun 04 '14 at 04:06
  • QAMAR could you plz write how to call getHttpGet() in AsyncTask because i' new in this topic, i don't know how AsyncTask work and write it. Thanks a lot by the way, what is NetworkOnMainThread Exception? – user3705368 Jun 04 '14 at 04:15
  • In logcat, it has 06-04 W/System.err(4309): org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused >>> Is it a problem of code? – user3705368 Jun 04 '14 at 04:27
  • possible duplicate of [android.os.NetworkOnMainThreadException](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) – 323go Jun 04 '14 at 04:34
  • @user3705368, read your logcat, and then *google* the exception you get. QAMAR has wonderfully explained that you're going to get a [`NetworkOnMainThreadException`](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception). The best thing to do for you now is to go through the many results and learn it -- this can't be answered in a comment, nor does it need to be, as it has been answered many times. – 323go Jun 04 '14 at 04:36

1 Answers1

1

The problem is with your server url, android devices don't recognize the localhost url as this is your url of the machine. I personally recommend you to access your XAMP server by your machine IP but if you are working on emulator and want to work with local host only change the url to 10.0.2.2. Refer developer guide

Kshitij
  • 144
  • 10
  • Many people have mention that error is because of _NetworkOnMainThreadException_ but it is not possible since there is strict policy implemented in the code. – Kshitij Jun 04 '14 at 04:39
  • I'm using real device,LG G2. I think my server is OK because i can run that url on chrome browser and also i can manage my database on http://localhost/phpmyadmin. By the way, now i'm studing AsyncTask as above recommendation said. – user3705368 Jun 04 '14 at 05:41
  • Can you open the server from your LG G2 device ? I dont think it is possible how can even your device recognize what is local host? Aysnc Task is one thing that you should definitely implement but that is not the solution to this problem. – Kshitij Jun 04 '14 at 07:28
  • It works on both real device and EMU. All i do just change String url = "http://localhost/android_connection/getHttpGet.php"; >>>> String url = "http//***IP of your computer that run webserver***/android_connection/getHttpGet.php"; – user3705368 Jun 07 '14 at 07:17
  • Ya that was I saying from the starting, though glad it worked but still don't know why people downvoted it. – Kshitij Jun 08 '14 at 08:56