1

I'm trying to convert the content of a URL and use it as a String to create a toast out of it, all called by a button.

@Override
public void onClick(View arg0) {
    String ExampleURL = ("http://pastebin.com/raw.php?i=ty0h7cS2");
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet get = new httpGet(ExampleURL);
    HttpResponse response = null;
    try {
        response = httpClient.execute(get);
    } catch (IOException e) {
        e.printStackTrace();
    }
    String ExampleURLContent = null;
    try {
        ExampleURLContent = EntityUtils.toString(response.getEntity());
    } catch (IOException e) {
        e.printStackTrace();
    }
    Toast.makeText(getApplicationContext(), "10 + 10 = " + ExampleURLContent, Toast.LENGTH_SHORT).show();
}

It compiles, but on click on the button it force-closes. Logcat:

 java.lang.NullPointerException: Attempt to invoke virtual method
 'boolean java.net.URI.isAbsolute()' on a null object reference
             at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:496)
             at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
             at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
             at de.dotwee.kwsolver.MainActivity$1.onClick(MainActivity.java:54)

             that is this line --> (response = httpClient.execute(get);)

             at android.view.View.performClick(View.java:4756)
             at android.view.View$PerformClick.run(View.java:19749)
             at android.os.Handler.handleCallback(Handler.java:739)
             at android.os.Handler.dispatchMessage(Handler.java:95)
             at android.os.Looper.loop(Looper.java:135)
             at android.app.ActivityThread.main(ActivityThread.java:5221)
             at java.lang.reflect.Method.invoke(Native Method)
             at java.lang.reflect.Method.invoke(Method.java:372)
             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Any help? Also, is there any simpler way with less code?

  • I'm not sure if this is your exact issue but from your example you are executing a web request on the UI Thread. You should wrap your request in an AsyncTask and it may resolve your issue. See this post, http://stackoverflow.com/a/20159968/1296369 – kevskree Dec 24 '14 at 17:19
  • @kevskree You're right! Wrapping in an AsyncTask actually worked. Thank you! http://stackoverflow.com/questions/16994777/android-get-html-from-web-page-as-string-with-httpclient-not-working –  Dec 25 '14 at 12:53

1 Answers1

1

Try this

String ExampleURLContent = null;
   try {
          if(response != null){
          ExampleURLContent = EntityUtils.toString(response.getEntity());
       }
   } catch (IOException e) {
    e.printStackTrace();
   }
sandeepmaaram
  • 4,191
  • 2
  • 37
  • 42