我有两个类;第一个是 asynctask
,另一个是 ConnectionDetector
类
其中包含显示的代码 here (第三步),
public class myTask extends AsyncTask<String,Void,String>{
private Context context;
ConnectionDetector connectiondetector = new ConnectionDetector(context);
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//CHECK INTERNET CONNECTION
if(connectiondetector.isConnectingToInternet()){ //method from connectiondetector.java
//do something
}
}
当我运行此代码时,我在 if
语句中遇到空指针异常。
是因为上下文的原因吗?我该如何解决这个问题?
从不同的 Activity 调用 asynctask
类 (partosrecord.class
)
最佳答案
将上下文从您的 Activity 类传递给您的 asynctask 的构造函数
new myTask(ActivityName.this).execute(params);
在你的异步任务中
public class myTask extends AsyncTask<String,Void,String>{
ConnectionDetector connectiondetector
Context mcontext;
public myTask(Context context)
{
mcontext= context;
connectiondetector = new ConnectionDetector(mcontext);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if(connectiondetector.isConnectingToInternet()){
//dosomething
}
}
关于java - 从 Android 上的 asynctask 检查互联网状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16418110/