4

I've look at a few forum post and I can not find an answer to my problem. I am trying to get a response from a php file. The php file is working. The problem is the Android App will not execute my request. Here are two examples of my code and the result I get in the textview:

public void changText(View view) {
    TextView textv = (TextView)findViewById(R.id.textview1);
    textv.setText("Text Has Been Changed");
    BufferedReader in = null;
    String data = null;

    try{
           HttpClient httpclient = new DefaultHttpClient();

           HttpGet request = new HttpGet();
           URI website = new URI("http://alanhardin.comyr.com/matt24/matt28.php");
           request.setURI(website);
           HttpResponse response = httpclient.execute(request);
           in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

           textv.append(" Connected ");
       }catch(Exception e){
           Log.e("log_tag", "Error in http connection "+e.toString());
       }


   }

The TextView reads: Text Has Been Changed

    public void changText(View view) {
    TextView textv = (TextView)findViewById(R.id.textview1);
    textv.setText("Text Has Been Changed");
    BufferedReader in = null;
    String data = null;

    try{
           HttpClient httpclient = new DefaultHttpClient();

           HttpGet request = new HttpGet();
           URI website = new URI("http://alanhardin.comyr.com/matt24/matt28.php");
           request.setURI(website);
           //HttpResponse response = httpclient.execute(request);
           //in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

           textv.append(" Connected ");
       }catch(Exception e){
           Log.e("log_tag", "Error in http connection "+e.toString());
       }


   }

The TextView reads: Text Has Been Changed Connected

In this manifest I have:

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

In the error log I get the following: Error in http connection android.os.NetworkOnMainThreadException

Any help would be appreciated.

user908759
  • 1,355
  • 8
  • 26
  • 48
  • In the code you've posted, you're not actually reading the data once you construct a reader. – Ted Hopp Dec 02 '13 at 06:03
  • 1
    What happened if you run your code ? – Thein Dec 02 '13 at 06:05
  • I am not trying to read the returned JSON object right now I am just trying to connect to my php file – user908759 Dec 02 '13 at 06:27
  • If I run my code with the first example the TextView reads: "Text Has Been Changed". If I run my code with the second example the TextView reads: "Text Has Been Changed Connected". It seems the httpclient.execute(request); is causing the problems. – user908759 Dec 02 '13 at 06:29

2 Answers2

14

Android is probably executing your request just fine. You just seem to be ignoring the data returned by the server. You could do something like this, for instance:

public void changText(View view) {
    TextView textv = (TextView)findViewById(R.id.textview1);
    textv.setText("Text Has Been Changed");
    BufferedReader in = null;
    String data = null;

    try{
           HttpClient httpclient = new DefaultHttpClient();

           HttpGet request = new HttpGet();
           URI website = new URI("http://alanhardin.comyr.com/matt24/matt28.php");
           request.setURI(website);
           HttpResponse response = httpclient.execute(request);
           in = new BufferedReader(new InputStreamReader(
                   response.getEntity().getContent()));

           // NEW CODE
           String line = in.readLine();
           textv.append(" First line: " + line);
           // END OF NEW CODE

           textv.append(" Connected ");
       }catch(Exception e){
           Log.e("log_tag", "Error in http connection "+e.toString());
       }
}

It looks like your server is returning a JSON object, so you would probably want to do something more intelligent such as read the entire response, parse it (using new JSONArray(response)), and extract relevant fields, but the above code would at least verify that Android is executing your query.

EDIT: From the exception you report, it appears that you are running your code on the main UI thread. As of API 11 that is prohibited (and was frowned upon before that). There are several articles on how to fix this. See the Guide topic Painless threading as well as tutorials here and here. Also see this thread for more information.

Community
  • 1
  • 1
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • To read the entire response into a `String`, take a look at [this answer](http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string/5445161#5445161). – Ted Hopp Dec 02 '13 at 06:16
  • Thank you for your response. Unfortunately your new code did not work. The TextView still reads "Text Has Been Changed". The problems seems to be with the httpclient.execute(request), not with parsing JSON. I know eventually I will need to read the JSON object, but right now I am just trying to connect to my php file. – user908759 Dec 02 '13 at 06:25
  • @user908759 - Does it still add the word " Connected "? Perhaps you are now catching an exception. (By the way, it's better to log the exception using the three-argument call `Log.e("log_tag", "Error in http connection", e);` rather than calling `e.toString()`. You'll get more information in logcat that way.) – Ted Hopp Dec 02 '13 at 06:26
  • No Connected is not added. That was the point of my two examples. When I commented out the "httpclient.execute(request);" Connected was appended to the TextView, whenever "httpclient.execute(request);" was NOT commented out, Connected is not appended. This is why I think the problem has something to do with "httpclient.execute(request);" – user908759 Dec 02 '13 at 06:36
  • @user908759 - Sounds like trying to read the response raises an exception. What shows up in logcat? – Ted Hopp Dec 02 '13 at 06:37
  • PID: 1854 TID: 1854 Tag: Trace Text: Unexpected value from nativeGetEnabled Tags: 0 AND PID: 1854 TID: 1854 Tag: log_tag Text: Error in http connection android.os.NetworkOnMainThreadException – user908759 Dec 02 '13 at 06:49
  • 1
    Ah. The problem is that you are executing this code on the main thread. That's not allowed There are several articles on how to fix this. See the Guide topic [Painless threading](http://android-developers.blogspot.com/2009/05/painless-threading.html) as well as tutorials [here](http://blog.vogella.com/2012/02/22/android-strictmode-networkonmainthreadexception/) and [here](http://www.techblogistech.com/2011/11/how-to-fix-the-android-networkonmainthreadexception/). Also see [this thread](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) – Ted Hopp Dec 02 '13 at 06:52
  • That seems to be the problem, can you edit your answer so I can give you credit for the solve. – user908759 Dec 02 '13 at 22:31
  • _"Android 6.0 release removes support for the Apache HTTP client. If your app is using this client and targets Android 2.3 (API level 9) or higher, use the HttpURLConnection class instead. ..."._ [link](https://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#boringSSL) – Anton Kasabutski Aug 28 '17 at 22:05
  • @Anton - Good point. The same principle applies: don't do network operations on the main (UI) thread. – Ted Hopp Aug 28 '17 at 23:57
0
 private InputStream downloadUrl(final URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(NET_READ_TIMEOUT_MILLIS /* milliseconds */);
    conn.setConnectTimeout(NET_CONNECT_TIMEOUT_MILLIS /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    // Starts the query
    conn.connect();
    return conn.getInputStream();
}
Raj008
  • 3,539
  • 2
  • 28
  • 26