0

我有两节课;第一个是一个asynctask,另一个是一个ConnectionDetector包含此处显示的代码的类(第 3 步),

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语句中得到一个空指针异常。是因为上下文,我该如何解决这个问题?

该类asynctask是从不同的活动中调用的 ( partosrecord.class)

4

2 回答 2

1

将上下文从您的活动类传递给 oyur 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  
         } 
     } 
于 2013-05-07T11:47:49.687 回答
0

您调用 asynctask 的代码:-

myTask site = new myTask(this);
site.execute();

或在AsyncTask上使用以下代码

public class myTask extends AsyncTask<String,Void,String>{


private Context context;
ConnectionDetector connectiondetector
public myTask(Context con)
{
     context=con;
     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 }
}  
于 2013-05-07T11:47:33.467 回答