-2

I was wondering my code bellow is working very very well with android 2.2 and 3.2 but alway crash with android 4.x.

How to solve it for android latest version?

search_btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                EditText search_text = (EditText) findViewById(R.id.SearchBox);
                String search_txt_enter = search_text.getText().toString();

                if(search_txt_enter.equals(""))
                {
                    Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show();
                }
                else
                {
                    try
                    {
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost("http://mobile.xxxxx.com/search.php");

                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                        nameValuePairs.add(new BasicNameValuePair("search", search_txt_enter.trim()));
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                        HttpResponse response = httpclient.execute(httppost);

                        InputStream inputStream = response.getEntity().getContent();
                        inputStream.close();

                    }
                    catch (ClientProtocolException e)
                    {
                     // TODO Auto-generated catch block
                    }
                    catch (IOException e)
                    {
                     // TODO Auto-generated catch block

                    }
                }
            }
        });
user1731690
  • 225
  • 1
  • 3
  • 16
  • Possibly duplicate of http://stackoverflow.com/questions/9413625/android-android-os-networkonmainthreadexception – AnujMathur_07 May 24 '13 at 13:19
  • 1
    Its NetworkOnMainThread Exception. You are performing a network operation on UI thread i.e onClick. search for that in StackOverflow. you will get plenty of examples. and always check logcat while debugging. – SKK May 24 '13 at 13:20
  • possible duplicate of [android.os.NetworkOnMainThreadException](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) – Selvin May 24 '13 at 13:44

2 Answers2

1

You have to use an AsyncTask.. Network Connections must always made in an other Threads..

Below is an Example for your question:

in for example onCreate:

search_btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                EditText search_text = (EditText) findViewById(R.id.SearchBox);
                String search_txt_enter = search_text.getText().toString();
    if(search_txt_enter.equals(""))
                    {
                        Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show();
                    }else{
                        new YourTask().execute(search_txt_enter); // start the AsyncTask
                   }


}
}

An the below code in your class:

 private class YourTask extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... s) {

                //Here you have to make the loading / parsing tasks
                //Don't call any UI actions here. For example a Toast.show() this will couse Exceptions
                // UI stuff you have to make in onPostExecute method

                    try
                    {
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost("http://mobile.xxxxx.com/search.php");

                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                        nameValuePairs.add(new BasicNameValuePair("search", s[0].trim())); //The String is in the first index!
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                        HttpResponse response = httpclient.execute(httppost);

                        InputStream inputStream = response.getEntity().getContent();
                        inputStream.close();

                    }
                    catch (ClientProtocolException e)
                    {
                     // TODO Auto-generated catch block
                    }
                    catch (IOException e)
                    {
                     // TODO Auto-generated catch block

                    }



            }

            @Override
            protected void onPreExecute() {
                // This method will called during doInBackground is in process
                // Here you can for example show a ProgressDialog
            }

            @Override
            protected void onPostExecute(Long result) {
                // onPostExecute is called when doInBackground finished
                // Here you can for example fill your Listview with the content loaded in doInBackground method

            }

    }
zennon
  • 1,080
  • 10
  • 25
0

Network oriented tasks must do in asyncTask. In Previous versions, they give only suggesitions, Bt in new versions It will through error. Try to do your network related code in asyncTask's doinBackground

public class TestAsyncTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected Boolean doInBackground(String... params) {
 try
                    {
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost("http://mobile.xxxxx.com/search.php");

                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                        nameValuePairs.add(new BasicNameValuePair("search", search_txt_enter.trim()));
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                        HttpResponse response = httpclient.execute(httppost);

                        InputStream inputStream = response.getEntity().getContent();
                        inputStream.close();

                    }
                    catch (ClientProtocolException e)
                    {
                     // TODO Auto-generated catch block
                    }
}}

This will work. Call this assyncTask from your buttonClick.

button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                        TestAsyncTask testAsyncTask = new TestAsyncTask();
            testAsyncTask.execute();
            }
        });
Jithu
  • 1,478
  • 1
  • 13
  • 21