Jalp
Jalp

Reputation: 67

How to solve Networkonmainthread Exception

I call a web service of real estate web site and for that i built my own method's and all.. I develop a execute method in which i will set my url as per my requirement as below :

 public void Execute(RequestMethod method) throws Exception
    {
        switch(method) {
            case GET:
            {
                //add parameters
                String combinedParams = "";
                if(!params.isEmpty()){
                    combinedParams += "?";
                    for(NameValuePair p : params)
                    {
                        String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
                        if(combinedParams.length() > 1)
                        {
                            combinedParams  +=  "&" + paramString;
                        }
                        else
                        {
                            combinedParams += paramString;
                        }
                    }
                }

                HttpGet request = new HttpGet(url + combinedParams);

                //add headers
                for(NameValuePair h : headers)
                {
                    request.addHeader(h.getName(), h.getValue());
                }

                **executeRequest(request, url);** // This throws an exception
                break;
            }
            case POST:
            {
                HttpPost request = new HttpPost(url);

                //add headers
                for(NameValuePair h : headers)
                {
                    request.addHeader(h.getName(), h.getValue());
                }

                if(!params.isEmpty()){
                    request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                }

                executeRequest(request, url);
                break;
            }
        }
    }

In get case , i send the request using httpget with my desired url but at that time network on main thread exception is generated.

Upvotes: 0

Views: 3365

Answers (3)

Abdallah Alaraby
Abdallah Alaraby

Reputation: 2249

You have to use a Thread or AsyncTask, this post explains a lot about this error.

Upvotes: 0

jubei
jubei

Reputation: 21

in your AndroidManifest you can also use the following to skip the error:

<uses-sdk android:minSdkVersion="8" 
        android:targetSdkVersion="8" />

Upvotes: 2

ingsaurabh
ingsaurabh

Reputation: 15269

Change your code to below one i.e call execute this way

new Thread()
{
    @Override
    public void run()
    {
        Execute();
    }
}.start();

Upvotes: 1

Related Questions