Android.os.networkonmainthreadexception inside new topic

I know that you cannot perform network operations in the main thread starting with Android 3.0. So, I called the new Thread :

 button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { user=login.getText().toString(); password=pass.getText().toString(); params.add(new BasicNameValuePair("user", user)); params.add(new BasicNameValuePair("pass", password)); Thread thread=new Thread(){ public void run(){ try { // Throws exception here response=CustomHttpClient.executeHttpPost(urlogin, params); response=response.replaceAll("\\s+",""); } catch (Exception e) { e.printStackTrace(); } if(response.equals("ok")){ Intent home=new Intent(c, HomeActivity.class); home.putExtra("username", user); startActivity(home); Toast toast=Toast.makeText( c, getString(R.string.welcome), Toast.LENGTH_LONG); toast.show(); }else{ if(response.equals("fallo")){ runOnUiThread(new Runnable() { @Override public void run() { Toast toast=Toast.makeText( c, R.string.nologin, Toast.LENGTH_LONG); toast.show(); login.setText(""); pass.setText(""); } }); }else if(response.equals("nologin")){ runOnUiThread(new Runnable() { @Override public void run() { Toast toast=Toast.makeText( c, R.string.nouser, Toast.LENGTH_LONG); toast.show(); login.setText(""); pass.setText(""); } }); } } } }; thread.run(); } }); 

But I get this exception, even though I am not in the main thread (or at least I think that ...)

+7
android multithreading
source share
3 answers

using run() does not start a separate thread, it actually starts runnable in the same thread on which it was launched.

you need to use start() to start a new thread.

+38
source share

These lines

 Toast toast=Toast.makeText(c, getString(R.string.welcome), Toast.LENGTH_LONG); toast.show(); 

need to run on UI Thread , since you do a couple of times below it with runOnUiThread() . Toast is an element of the UI .

0
source share

You can use this code

 if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } 

to avoid an exception, also for SDK> 9 you need to perform network operations in a separate thread other than the UI, or you can use AsyncTask .

-2
source share

All Articles