Reputation: 537
I have two classes; the first is an asynctask
and the other is an ConnectionDetector
class
which contains the code shown here (3rd step),
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
}
}
when I run this code I get a null pointer exception at the if
statement.
is it because of the context, how do I fix this?
the asynctask
class is called from a different activity ( partosrecord.class
)
Upvotes: 0
Views: 461
Reputation: 38439
Code where u call asynctask:-
myTask site = new myTask(this);
site.execute();
or use this below code on 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 }
}
Upvotes: 0
Reputation: 133560
Pass context to the constructor of oyur asynctask from your activity class
new myTask(ActivityName.this).execute(params);
In your asynctask
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
}
}
Upvotes: 1