Jay Pandya
Jay Pandya

Reputation: 547

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

Upvotes: 0

Views: 1325

Answers (2)

Chnoch
Chnoch

Reputation: 772

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.

Upvotes: 1

Sharad Mhaske
Sharad Mhaske

Reputation: 1103

You should not do networks call on main/UI thread of Application. you may start new worker thread that will run in separate thread rather than on UI thread.

Upvotes: 0

Related Questions