我收到 FATAL EXCEPTION: AsyncTask #1
错误。
我还没有创建异步任务,我只是调用了下面的代码。
我从连接到网络的类中调用以下内容:
Toast.makeText(context, "Connection Successful", Toast.LENGTH_LONG).show();
context
已在 MainActivity
的构造函数中传递。我不确定我在这里做错了什么。
最佳答案
进行以下更改以显示来自 Network
类(非 Activity 类)的 Toast:
步骤:1 将 Activity Context 传递给 Network 类而不是 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);
第 2 步: 使用
runOnUiThread
显示来自网络类的 Toast: 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..
}
关于安卓 toast 错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15636309/