-1

This is the code I have so far.

public void postData(String toPost) {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.mywebsite.com/dev/reverser.php");

    //This is the data to send
    String MyName = toPost; //any data to send

    try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("action", MyName));

    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String response = httpclient.execute(httppost, responseHandler);

    //This is the response from a php application

    String reverseString = response;
    Toast.makeText(this, "response" + reverseString, Toast.LENGTH_LONG).show();

    } catch (ClientProtocolException e) {
    Toast.makeText(this, "CPE response " + e.toString(), Toast.LENGTH_LONG).show();
    // TODO Auto-generated catch block
    } catch (IOException e) {
    Toast.makeText(this, "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
    // TODO Auto-generated catch block
    }

    }//end postData()

Can somebody please tell me what is wrong in the following code! I have established that there is a problem in the try catch block only and not anywhere else in the activity. I just do not know what it is or how to correct it.

My PHP code is quite simple. It is something like this -

//code to reverse the string
$reversed = strrev($_POST["action"]);
echo $reversed;
Advait Saravade
  • 3,029
  • 29
  • 34
  • why dont you tell us what exactly is the exception that you are getting . You can use the android debugger to do so . Also the way you print the response as a Toast is incorrect . – rockstar May 17 '13 at 12:03
  • AndroidRuntime(15110): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.connectingtophpandreturningdata/com.example.connectingtophpandreturningdata.MainActivity}: android.os.NetworkOnMainThreadException – Advait Saravade May 17 '13 at 12:08

3 Answers3

1

In a comment above you indicated that you are getting a android.os.NetworkOnMainThreadException.

In the most recent versions of Android you are not allowed to do networking on the main thread as it makes the UI unresponsive. Move your code to a different thread using AsyncTask (see the Android developer guide for details) or some other mechanism.

Dan Dyer
  • 53,737
  • 19
  • 129
  • 165
  • Yes. Thanks for your answer. I believe it is the NetworkOnMainThreadException. How do you propose I implement AsyncTask into my code? Could you implement it into the code yourself and put it up as an answer? That way, I can use it immediately and can give you a 1+ for your answer! – Advait Saravade May 17 '13 at 12:15
  • @AdvaitS I've added a link to the developer site documentation on how to use AsyncTasks. There is also an example in the SO question that rockstar linked to. Basically you create a class that extends `AsyncTask`, put your networking code in the `doInBackground` method, return the result and then update the UI in `onPostExecute` method. Then you just need to create an instance and call `execute`. – Dan Dyer May 17 '13 at 12:31
0

Try printing out the exception . Use this code to print out your response . Check the status of the response

        HttpResponse response = client.execute(request);

        String line;

        br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        while ((line = br.readLine()) != null)
        {
            sb.append(line + "\n");
        }
        br.close();

    } 
    catch(Exception e)
    {
        Toast.makeText(HttpPostActivity.this, "Exception: " + e.toString(), Toast.LENGTH_LONG).show();
    }

Tell us the exception . It would be easy to pinpoint your problems then .

EDIT : ANSWER :

You are trying to perform a networking operation on the MAIN thread . This is an illegal thing to do . Create a AsyncTask i.e create a seperate thread to do your networking operations .

Android Details of the exception

Stackoverflow question

Community
  • 1
  • 1
rockstar
  • 3,512
  • 6
  • 40
  • 63
  • I used your code. I got the following exception - android.os.NetworkOnMainThreadException – Advait Saravade May 17 '13 at 12:12
  • check my updated answer . If you need help creating async task thread . let me know – rockstar May 17 '13 at 12:15
  • rockstar thanks for the answer. And yes, even I have concluded that the networking operation was being performed on the Main thread(did not know that wasn't allowed). Anyway, I will quickly check out the links you gave me. In the mean time, could you show me how exactly does one use AsyncTask, by adding it to the code I presented above. That would be the best! – Advait Saravade May 17 '13 at 12:22
0

Adding as a seperate answer as the poster requests to do so .

Assumption :

a ) There is a text box that accepts the URL to load

b ) A button which when clicked performs the networking operation on the URL fetched f

Implement a button click listener that calls the following function :

    private void URL() 
    {
        String url = txtURL.getText().toString();
        new URLTask().execute(new String[] { url });
    }    




private class URLTask extends AsyncTask<String, Void, String> 
    {
        protected String doInBackground(String... urls)
        {

            BufferedReader br = null;
            String url = urls[0];
            StringBuffer sb = new StringBuffer("");

            try
            {
                HttpClient client = new DefaultHttpClient();
                HttpPost request = new HttpPost();
                request.setURI(new URI(url));

                List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
                postParameters.add(new BasicNameValuePair("param1", "value of param1")); 

                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);         

                request.setEntity(formEntity);
                HttpResponse response = client.execute(request);

                String line;

                br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                while ((line = br.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                br.close();

            } 
            catch(Exception e)
            {
                Toast.makeText(HttpPostActivity.this, "Exception: " + e.toString(), Toast.LENGTH_LONG).show();
            }
            finally 
            {
                if (br != null) 
                {
                    try 
                    {
                        br.close();
                    } 
                    catch(IOException ioe) 
                    {
                        ioe.printStackTrace();
                    }
                }           

            }           

            return(sb.toString());
        }


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

You need to implement onPostExecute as well . There are other APIS .

Android Async Task Documentation

rockstar
  • 3,512
  • 6
  • 40
  • 63