call non static method from static method in android

馋奶兔 提交于 2019-12-22 10:53:00

问题


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???


回答1:


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();
    }



回答2:


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.




回答3:


public static void setAuth(MainActivity activity) {
       activity.d();
}

That simple.

new MainActivity().d(); calls the method of another instance of the activity.



来源:https://stackoverflow.com/questions/20089568/call-non-static-method-from-static-method-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!