Trying to Fix Networkonmainthreadexception But Gives Toast Error

Trying to fix NetworkOnMainThreadException but gives Toast error

You can't do UI stuff in doInBackground(). Hence, you can't display a Toast there. You need to move this to onPostExecute() or somewhere else. Possibly onProgressUpdate()

You could call publishProgress(results) and show the Toast in onProgressUpdate() or return results to onPostExecute() and display it there. You also have the option of sending the data back to an Activity method

AsyncTask

How to solve NetworkOnMainThreadException error in android?

You need to use an AsyncTask to do all your network operations.

Your network operation can take a lot of time and the UI would get unresponsive if it is done on the main UI thread. And if your UI freezes for a long time, the app might get killed by the OS.

Thus Android 4+ makes it mandatory to use a background thread to perform network operations.

Put the code to do the network activity inside doInBacground() and all the AsyncTask using execute().

Here is how your AsyncTask would look like :

private class SendMail extends AsyncTask<String, Integer, Void> {
     protected void doInBackground() {
        sendEmail();
 }

 protected void onProgressUpdate() {
    //called when the background task makes any progress
 }

  protected void onPreExecute() {
     //called before doInBackground() is started
 }
 protected void onPostExecute() {
     //called after doInBackground() has finished 
 }
  }

And you can call it anywhere using new SendMail().execute("");

how do i fix FATAL EXCEPTION:main android.os.NetworkOnMainThreadException

The issue is that inside the AsyncTask's onPostExecute you call the following:

socket.getOutputStream() 

This happens on the MainThread and therefore the exception is thrown. Move it to the doInBackground inside the try catch block so it looks like this:

public class ConnectPhoneTask extends AsyncTask<String,Void,Boolean> {

@Override
protected Boolean doInBackground(String... params) {
boolean result = true;
try {
InetAddress serverAddr = InetAddress.getByName(params[0]);
socket = new Socket(serverAddr, Constants.SERVER_PORT);//Open socket on server IP and port
if(isConnected) {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true); //create output stream to send data to server
}
} catch (IOException e) {
Log.e("remotedroid", "Error while connecting", e);
result = false;
}
return result;
}

@Override
protected void onPostExecute(Boolean result)
{
isConnected = result;
Toast.makeText(context,isConnected?"Connected to server!":"Error while connecting",Toast.LENGTH_LONG).show();
}
}

android.os.NetworkOnMainThreadException while posting data to url

Its because you're doing network operation on Main UI thread

if you're using threads to do network operations
then you can use this code snippet

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

in your OnCreate()

But its wrong practice to use above said operation, instead you should use AsyncTask class provided by android to handle properly network operation without blocking UI thread.

you can learn more by visiting this LINK

or can use the below code

private class UploadFiles extends AsyncTask<String, Void, Void> {
protected String doInBackground(String... urls) {
//THIS METHOD WILL BE CALLED AFTER ONPREEXECUTE
//YOUR NETWORK OPERATION HERE
return null;
}

protected void onPreExecute() {
super.onPreExecute();
//THIS METHOD WILL BE CALLED FIRST
//DO OPERATION LIKE SHOWING PROGRESS DIALOG PRIOR TO BEGIN NETWORK OPERATION
}

protected void onPostExecute(String result) {
super.onPostExecute();
//TNIS METHOD WILL BE CALLED AT LAST AFTER DOINBACKGROUND
//DO OPERATION LIKE UPDATING UI HERE
}
}

and you can simple call this class by writing

 new UploadFiles ().execute(new String[]{//YOUR LINK});

Android app crashes due to NetworkOnMainThreadException

Just use a thread.

Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
//Your code goes here
} catch (Exception e) {
e.printStackTrace();
}
}
});

thread.start();

call the httpClient in this thread.

Android Toast crash

Of course, you need to use best practices with AsyncTask. For example check this post.

But if you want just to test it quickly, try this:

Replace these lines:

Toast t = Toast.makeText(getApplicationContext(), "Connection established", Toast.LENGTH_LONG);
t.show();

by these ones:

Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
public void run() {
Toast t = Toast.makeText(getApplicationContext(), "Connection established", Toast.LENGTH_LONG);
t.show();
}
});

FOR UPDATED CODE:

Replace this line:

if(result.equalsIgnoreCase("Exception Caught")){

by this one:

if ("Exception Caught".equalsIgnoreCase(result)) {


Related Topics



Leave a reply



Submit