Dennis Dennis - 25 days ago 9
Android Question

How to access to Class method from another Activity in Android?

My app contains two classes: MainActivity, Activity2.

Activity2 needs to access a non-static method of MainActivity. How to do that?

I'm new with Java and Android, if you can, please explain clearly for beginners what to do.

Thanking you in advance.

Answer

Instead of calling methods from a different activity you should use Bundles to pass values from ActivityA to ActivityB when B is started from A.

Alternatively if you want to reuse code you should create a non-activity object which you can create two instances of. Say if you do a lot of heavy calculations in both activities, you can put your calculating code in a "Calculate" object. And just initiate it like you would any other Java object. Just note that these two instance will not share any data between each other.

Calculate calc = new Calculate();
calc.codeIdLikeToReuse(numbersAndStuff);

Hope this helps. I would recommend that you read up on the Activity Life Cycle to get an idea on how the life on an activity is.