Getting a cannot make a static reference to a non static method when I call AsyncTask<Void.execute
I’m using AsyncTask to load bitmaps in the background. I created a class Mybackground that inherits from AsyncTask. If I do the following it works,
new MyBackground().execute();
But when I call it this way,
MyBackground mBackground=new MyBackground();
mBackground.p1=1;
mBackground.p2="tets";
MyBackground.execute();
I get the error cannot make a static reference to a non static. Why am I getting this error. Is there a way to do this? If not what would be a good way to pass in 2 different arguments, since execute only takes in 1 paramete开发者_JAVA百科r?
You would call mBackground.execute()
which calls the execute
method of a particular instance of your MyBackground
class.
Calling new MyBackground().execute()
creates a new MyBackground
instance and then calls execute on that, which is why you don't get the error.
Take a look at Java: static and instance methods if you are unsure on what the difference between a static and instance method is.
Static methods do not require an instance of that type to exist, and static properties are shared between all instances of a class.
If you want to pass some data into your AsyncTask
you can create a new constructor for it:
public class MyBackground extends AsyncTask<Void, Void, Void> {
...
private int p1;
private String p2;
public MyBackground(int p1, String p2) {
this.p1 = p1;
this.p2 = p2;
}
...
}
You would then use either:
MyBackground myBackground = new MyBackground(1,"tets");
myBackground.execute();
// or
MyBackground myBackground = new MyBackground(1,"tets").execute();
Joseph Earl has a good explanation of why you are getting the static reference error.
精彩评论