1

I simply have:

HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost(
        "http://www.google.com/");

// Making HTTP Request
try {
    HttpResponse response = (HttpResponse) httpClient.execute(httpPost);
    // writing response to log
    Log.d("Http Response:", response.toString());
} catch (ClientProtocolException e) {
    // writing exception to log
    e.printStackTrace();
} catch (IOException e) {
    // writing exception to log
    e.printStackTrace();
}

But when I run the app, it crashes and does not work.

this my log:

02-05 14:33:42.217: E/AndroidRuntime(25026): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.myapppp/com.app.myapppp.Main}: android.os.NetworkOnMainThreadException
02-05 14:33:42.217: E/AndroidRuntime(25026):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at android.app.ActivityThread.access$700(ActivityThread.java:140)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at android.os.Handler.dispatchMessage(Handler.java:99)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at android.os.Looper.loop(Looper.java:137)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at android.app.ActivityThread.main(ActivityThread.java:4921)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at java.lang.reflect.Method.invokeNative(Native Method)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at java.lang.reflect.Method.invoke(Method.java:511)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at dalvik.system.NativeStart.main(Native Method)
02-05 14:33:42.217: E/AndroidRuntime(25026): Caused by: android.os.NetworkOnMainThreadException
02-05 14:33:42.217: E/AndroidRuntime(25026):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at com.app.myapppp.Main.onCreate(Main.java:133)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at android.app.Activity.performCreate(Activity.java:5206)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
02-05 14:33:42.217: E/AndroidRuntime(25026):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
02-05 14:33:42.217: E/AndroidRuntime(25026):    ... 11 more
Cœur
  • 34,719
  • 24
  • 185
  • 251
  • http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception this is the solution, please search well before posting. – Remees M Syde Feb 05 '15 at 11:10

3 Answers3

0

Make your API call with AsyncTask like Example

Click to API call or as in Main method

public void onClick(View v) {
// TODO Auto-generated method stub
if(value.getText().toString().length()<1){
// out of range
Toast.makeText(this, "please enter something", Toast.LENGTH_LONG).show();
}else{
pb.setVisibility(View.VISIBLE);
new MyAsyncTask().execute(value.getText().toString());  
}
} 

AsynckTask

private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
@Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
}

//MyAsyncTask

private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
@Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}

protected void onPostExecute(Double result){
pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress){
pb.setProgress(progress[0]);
}
}

Your API call Method

public void postData(String valueIWantToSend) {

HttpClient httpclient = new DefaultHttpClient();
// specify the URL you want to post to
HttpPost httppost = new HttpPost("http://www.google.com/");
try {
// create a list to store HTTP variables and their values
List nameValuePairs = new ArrayList();
// add an HTTP variable and value pair
nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIwantToSend));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// send the variable and value, in other words post, to the URL
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// process execption
} catch (IOException e) {
// process execption
}
}
Ankitkumar Makwana
  • 3,724
  • 3
  • 18
  • 45
0

This is happening because your trying to do network related operations in your main activity. Which is not allowed rather is a bad way to do network related task. To do all such a task there are other ways such as you can do that by AsyncTask class.

Which allows you to do all this big task on the background of your application. So that your main thread does not get to busy which apparently causes your application crash.

documentation http://developer.android.com/reference/android/os/AsyncTask.html

simple asyncTask example http://programmerguru.com/android-tutorial/android-asynctask-example/

eLemEnt
  • 1,731
  • 13
  • 21
0

Need to perform network operation in separate thread.

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new NetworkOperation().execute();
    }

Asynctask exapmle

private class NetworkOperation extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
            HttpPost httpPost = new HttpPost(
                    "http://www.google.com/");

// Making HTTP Request
            try {
                HttpResponse response = (HttpResponse) httpClient.execute(httpPost);
                // writing response to log
                Log.d("Http Response:", response.toString());
            } catch (ClientProtocolException e) {
                // writing exception to log
                e.printStackTrace();
            } catch (IOException e) {
                // writing exception to log
                e.printStackTrace();
            }

            return "";
        }

        @Override
        protected void onPostExecute(String result) {

        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }
Farman Ali Khan
  • 660
  • 6
  • 19