3

I am receiving a FATAL EXCEPTION: AsyncTask #1 error.

I have not created a Async Task I simply called the code below.

I am calling the following from a class that connects to the network:

Toast.makeText(context, "Connection Successful", Toast.LENGTH_LONG).show();

context has been passed through in the constructor from the MainActivity.

I am not sure what I am doing wrong here.

Michael Celey
  • 12,645
  • 6
  • 57
  • 62
Zapnologica
  • 22,170
  • 44
  • 158
  • 253

4 Answers4

5

make following changes for showing Toast from Network class(non Activity class) :

Step:1 Pass Activity Context to Network class instead of getBaseContext() :

netConnection = new Network(new Network.OnMessageReceived() { 
            @Override 
            // here the messageReceived method is implemented 
           public void messageReceived(String message) { 
                 // this method calls the onProgressUpdate 
                 publishProgress(message); 
           } 
     },Your_Current_Activity_Name.this);

Step 2: use runOnUiThread for showing Toast from Network class :

 public boolean connect() {
 //....your code..
 Activity activity = (Activity) context;
 activity.runOnUiThread(new Runnable() {
    public void run() {
        //show your Toast here..
       Toast.makeText(context,"Connection Successful", Toast.LENGTH_LONG).show();
    }
});
 //....your code..
}
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
1

What a strange answers here :)

First guy want you to extend Network class from Activity, second tells you that you have not got Android SDK :)

You just need to send correct Context object to your Network object, you need to send Context object from getBaseContext() method, because this context object is correct for Toast messages (here you can read explanation about that).

Community
  • 1
  • 1
Artem Zinnatullin
  • 4,305
  • 1
  • 29
  • 43
0
Toast.makeText(getApplicationContext(), "Connection Successful", Toast.LENGTH_LONG).show()
Nirav Ranpara
  • 13,753
  • 3
  • 39
  • 54
0

Change:

Toast.makeText(context, "Connection Successful", Toast.LENGTH_LONG).show();  

to

Toast.makeText(getBaseContext(), "Connection Successful", Toast.LENGTH_LONG).show();
Bigflow
  • 3,616
  • 5
  • 29
  • 52