Dennis
Dennis

Reputation: 2311

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.

Upvotes: 0

Views: 2747

Answers (4)

LF-DevJourney
LF-DevJourney

Reputation: 28529

you also can use libraries like EventBus to link the code. refer to this post

Upvotes: 0

karl
karl

Reputation: 1936

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.

Upvotes: 1

Snicolas
Snicolas

Reputation: 38168

Basically, you can't do that. Two activities don't communicate this way. Usually, only one activity is alive at a time (also this might not be always true). The real answer is to use Intents.

You should read some basic Android tutorial like the anddev book.

Upvotes: 0

Ali Imran
Ali Imran

Reputation: 9217

Use Broad cast receiver to call methods in different activities you can find help here and one example

Upvotes: 0

Related Questions