Can i Create the object of a activity in other class?

前端 未结 3 727
悲哀的现实
悲哀的现实 2020-11-22 09:34

i have defined a function in mainactivity now i want to access with another class in my app.I have created a object of the mainactivity by using that object i have called th

相关标签:
3条回答
  • 2020-11-22 10:03

    Activity A should have a variable

    static ActivityA activityA;
    

    In onCreate state:

    activityA = this;
    

    and add this method:

    public static ActivityA getInstance(){
       return   activityA;
     }
    

    In activity B, call

    ActivityA.getInstance().myFunction(); //call myFunction using activityA
    
    0 讨论(0)
  • 2020-11-22 10:10

    You cannot just create objects of Activities by using:

    MyActivity activity = new MyActivity();
    

    as you would with normal Java classes. All Activities in Android must go through the Activity lifecycle so that they have a valid context attached to them.

    By treating an Activity as a normal Java class, you end up with a null context. As most methods in an Activity are called on its Context, you will get a null pointer exception, which is why your app crashes.

    Instead, move all such methods which need to be called from other classes into a Utility class which accepts a valid context in its constructor, and then use that context in the methods to do the work.

    0 讨论(0)
  • 2020-11-22 10:15

    Make the variable public and then create object in adapter like this:

    public int i;  // Variable in Activity class
    
    ((ActivityName) context).i          // accessing in adapter 
    
    0 讨论(0)
提交回复
热议问题