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

前端 未结 3 764
悲哀的现实
悲哀的现实 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: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.

提交回复
热议问题