Search code examples
phpandroidbufferedinputstream

How do I print PHP echo on my android app?


I'm fairly new to android and PHP programming and I am currently running into a problem printing my echo statement from my php page, which is as simple as:

    <?php
    echo "Hey there response!";
    ?>

What I am currently using in my MainActivity is:

        setContentView(R.layout.activity_main);

    TextView txtView = (TextView) findViewById(R.id.txt);

    //ASYNC WAY
    new GetData(txtView).execute("");

Where AsyncTask is defined by:

private class GetData extends AsyncTask<String, Void, String>{
    private TextView display;


    GetData(TextView view){
        this.display = view;
        display = (TextView) findViewById(R.id.txt);
    }

    protected String doInBackground(String... message){
        HttpClient httpclient;
        HttpGet request;
        HttpResponse response = null;
        String result = "error0";
        try{
            httpclient = new DefaultHttpClient();
            request = new HttpGet("http://localhost/php/wamp.php");
            response = httpclient.execute(request);
        } catch (Exception e){
            result = "error1";
        }

        try{
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));
            String line="";
            while((line = rd.readLine()) != null){
                result = result + line;
            }
        } catch(Exception e){
            result = "error2";
        }
        return result;
    }

    protected void onPostExecute(String result){
        this.display.setText(result);
    }
}

The message in the txtView becomes error2, and I have no idea why.

EDIT I was originally using a non-AsyncTask method of reading in input stream but I have switch to AsyncTask due to Networking error. The problem still persists though since I am not getting the corrent echo in my application.


Solution

  • This is probably too late for yanki but for anybody else that comes across this page.

    I tried it with yanki's code and got the same error as him "error 2". I noticed then that I hadn't updated the manifest file to allow internet permissions.

     <uses-permission android:name="android.permission.INTERNET" />
    

    I ran it again and it worked perfectly. So using yanki's code and entering the internet permissions in the manifest file the program should work.