I tried to call non static method from static method but without any result ,my application works crash
my code :
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setAuth();
///
///
}
public static void setAuth() {
new MainActivity().d();
}
public void d()
{
Toast.makeText(getApplicationContext(), "fff",Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Is it permissible to call non static method from static method in android??
and how???
A static method in a class must be able to be executed without any reference to an instantiation of the class:
class MyClass {
int information;
static int usefulNumber = 72;
int method() {
return information;
}
static int methodStatic() {
// Cannot refer to information
// But can refer to usefulNumber
}
}
By definition therefore, it cannot execute a non-static method in the class because that method doesn't exist unless, as @RhinoFeeder says, you have instantiated the class and passed that instantiation to the static class:
static int methodStatic2(MyClass myClass) {
return myClass.method();
}
The only way to do this is if you have access to an instance of the class that contains the non-static method.
EDIT: I realized this answer sounds empty without a further explanation, since you do new-up a MainActivity
.
new MainActivity().d();
Will not work in Android, as you cannot create a new Activity that way.
public static void setAuth(MainActivity activity) {
activity.d();
}
That simple.
new MainActivity().d();
calls the method of another instance of the activity.