androidandroid-asynctaskandroid-2.2-froyo

Android web api call without asynctask


I need to make an api call on click of button. So i do it following way.

btn.setOnClickListener(new View.OnClickListener()
                        {
                            @Override
                            public void onClick(View v) 
                            {
                                try 
                                {
                                     HttpResponse apiResponse = mySingleTonehttpClient.execute(new HttpGet(Url));
HttpEntity resEntity = apiResponse.getEntity();
InputStream instream = resEntity.getContent();
String result = convertInputStreamToString(instream);

    }
}

This code is working fine if i set targetSDKVersion = 8 in Manifest file. But giving me Network mainthread error for targetSDKVersion = 11. Can anyone suggest me what should i do?

Thanks,

Jay


Solution

  • The reason for this is that you're not supposed to do things that can possible take a long time in the UI Thread. Because doing that will result in the UI being blocked, and you're application will be lagging.

    That's why you should either use a Worker Thread or an AsyncTask to do Network IO. You can read more information about how to use them and how they can interact with the UI Thread on the Android Developer guide.