-4

My android app keeps on crashing. I'm trying to connect to a webservice via post call. But my app keeps on crashing every time it tries to call the webservice.

 import android.app.Activity;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;

    import java.io.IOException;
    public class PostActivity extends Activity {

        //static String response = null;

        public void loadPost() throws IOException {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            String blogFeedUrl = "http://localhost/medapp/public/mobile/post";

            HttpGet httpGet = new HttpGet(blogFeedUrl);
            httpResponse = httpClient.execute(httpGet);  // <-- this is where the application crashes

        }

    }
  • 3
    _"crashing"_ is not a valid description of your problem. Read up on basic debugging. Tips: Read the logcat, learn how to interpret a stack trace. Also, going through the tutorials on the dev site is useful in the beginning. – keyser May 04 '14 at 10:02

1 Answers1

0

From the code you have posted and related imports in the same, depending on the O.S(Esp Honeycomb and onwards), your application would crash due to the NetworkOnMainThreadException. You are attempting the network operation on the main thread, not in a background thread or Asyctask.

In your logcat(if you post that it'l help), NetworkOnMainThreadException will be thrown:

E/AndroidRuntime(673): java.lang.RuntimeException: Unable to start activity
    ComponentInfo{com.example/com.example.ExampleActivity}: android.os.NetworkOnMainThreadException

The explanation as to why this occurs is well documented on the Android developer's site:

A NetworkOnMainThreadException is thrown when an application attempts to perform a networking operation on its main thread. This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged.

Go through:

Why the app would crash or work depending on O.S.

Try AsyncTask to avoid NetworkOnMainThread

Why should you not use the Strict Mode alternative as your solution and only to debug(i'd suggest avoid that also actually, you know what is the problem now):
Critical to fix it, not by setting Thread policies

Community
  • 1
  • 1
Pararth
  • 8,114
  • 4
  • 34
  • 51