Reputation: 22556
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.
Upvotes: 3
Views: 1034
Reputation: 132972
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..
}
Upvotes: 5
Reputation: 4447
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).
Upvotes: 1
Reputation: 3666
Change:
Toast.makeText(context, "Connection Successful", Toast.LENGTH_LONG).show();
to
Toast.makeText(getBaseContext(), "Connection Successful", Toast.LENGTH_LONG).show();
Upvotes: 0
Reputation: 13785
Toast.makeText(getApplicationContext(), "Connection Successful", Toast.LENGTH_LONG).show()
Upvotes: 0