0

I use the following line of code to get HttpResponce from the server. While running the code I get the following stack trace in the logcat. Any clue why?

Code used by me:

new DeleteDirectoryLoaderTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

class DeleteDirectoryLoaderTask extends AsyncTask<URL, Integer, Long>
    {
        DeleteDirectoryLoaderTask()
        {
    
        }
        
        @Override
        protected void onPreExecute()
        {   
                
        }

        @Override
        protected Long doInBackground(URL... urls)
        {           
            
            
            try 
            {
                HttpResponse responceFromServer = m_HttpResponceInstance.makeRequest("post", HTTP_URI + "/" + "signup", registrationHeader, jsonMain);  
            } 
            catch (Exception e) 
            {                   
                e.printStackTrace();
            }
            
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... progress)
        {

        }

        @Override
        protected void onPostExecute(Long result)
        {           
                                            
        }
    }   

public HttpResponse makeRequest(String httpMethod, String url, Map<String, String> Header, JSONObject jsonObject) throws Exception 
    {
        HttpResponse responce = null;
        
        if(httpMethod.equals("post"))
        {
            DefaultHttpClient httpclient = new DefaultHttpClient();

            //url with the post data
            HttpPost httpost = new HttpPost(url);
            
            //passes the results to a string builder/entity
            StringEntity se = new StringEntity(jsonObject.toString());
            
            //sets the post request as the resulting string
            httpost.setEntity(se);
            
            for ( String key : Header.keySet() )
            {
                //sets a request header so the page receving the request
                //will know what to do with it
                httpost.setHeader(key, Header.get(key));
            }
            
            responce = httpclient.execute(httpost); 
            System.out.println(responce);
        }
        
        return  responce;
    }

Stack Trace in log cat

06-07 13:24:14.007: W/System.err(1857): android.os.NetworkOnMainThreadException
06-07 13:24:14.017: W/System.err(1857):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
06-07 13:24:14.022: W/System.err(1857):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
06-07 13:24:14.022: W/System.err(1857):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
06-07 13:24:14.022: W/System.err(1857):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
06-07 13:24:14.027: W/System.err(1857):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
06-07 13:24:14.027: W/System.err(1857):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
06-07 13:24:14.027: W/System.err(1857):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
06-07 13:24:14.027: W/System.err(1857):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
06-07 13:24:14.032: W/System.err(1857):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
06-07 13:24:14.032: W/System.err(1857):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
06-07 13:24:14.032: W/System.err(1857):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
06-07 13:24:14.032: W/System.err(1857):     at in.plackal.lovecyclesfree.HttpResponceManager.makeRequest(HttpResponceManager.java:54)
06-07 13:24:14.037: W/System.err(1857):     at in.plackal.lovecyclesfree.RegisterAccountActivity.onClick(RegisterAccountActivity.java:161)
06-07 13:24:14.037: W/System.err(1857):     at android.view.View.performClick(View.java:4261)
06-07 13:24:14.037: W/System.err(1857):     at android.view.View$PerformClick.run(View.java:17356)
06-07 13:24:14.037: W/System.err(1857):     at android.os.Handler.handleCallback(Handler.java:615)
06-07 13:24:14.037: W/System.err(1857):     at android.os.Handler.dispatchMessage(Handler.java:92)
06-07 13:24:14.042: W/System.err(1857):     at android.os.Looper.loop(Looper.java:137)
06-07 13:24:14.042: W/System.err(1857):     at android.app.ActivityThread.main(ActivityThread.java:4921)
06-07 13:24:14.042: W/System.err(1857):     at java.lang.reflect.Method.invokeNative(Native Method)
06-07 13:24:14.042: W/System.err(1857):     at java.lang.reflect.Method.invoke(Method.java:511)
06-07 13:24:14.047: W/System.err(1857):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
06-07 13:24:14.047: W/System.err(1857):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
06-07 13:24:14.047: W/System.err(1857):     at dalvik.system.NativeStart.main(Native Method)
iknow
  • 8,358
  • 12
  • 41
  • 68
AndroidDev
  • 4,521
  • 24
  • 78
  • 126

4 Answers4

1

This must be done in asynctask. (http://developer.android.com/reference/android/os/AsyncTask.html) Put code inside doInBackground

andMarkus
  • 960
  • 1
  • 8
  • 16
0

Do this whole work in Async task dear

This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask:(http://developer.android.com/reference/android/os/AsyncTask.html)

How to execute the task:

new RetrieveFeedTask().execute(urlToRssFeed);

Don't forget to add this to AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET"/>
Bhanu Sharma
  • 5,135
  • 2
  • 24
  • 49
  • I put the code in async task and its working fine. Only thing i want to confirm is that the way t i used the async task is fine or not (check my edited answer). Or should i put my async task code inside makeRequest method. – AndroidDev Apr 09 '14 at 08:47
  • ohk so now u don't get any error r8 good the only thing remember that always keep time taking process in th asynk task that it Is my ans help u to get success – Bhanu Sharma Apr 09 '14 at 08:49
  • My code implementation is fine or there is much better way to do that – AndroidDev Apr 09 '14 at 08:53
0

Please call this method from background Thread. i.e. Use AsyncTask. and then call this method from inside doInBackground()

Abdul Mohsin
  • 1,253
  • 1
  • 13
  • 24
0

You are running task on main thread, look at the firt line of stack trace.

android.os.NetworkOnMainThreadException

According to this answer: https://stackoverflow.com/a/19323642/619673

You can't make network requests on the main thread. You'll get the error you are seeing now. You need to use either AsyncTask or you need to create a new thread. Personally, I'd use AsyncTask. When you use AsyncTask you can use the onPostExecute method to return the value to the main thread. - Blaine

Community
  • 1
  • 1
deadfish
  • 11,996
  • 12
  • 87
  • 136