0

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.

Dennis
  • 2,271
  • 6
  • 26
  • 42

4 Answers4

1

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.

karl
  • 1,766
  • 2
  • 13
  • 24
0

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

Ali Imran
  • 8,927
  • 3
  • 39
  • 50
0

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.

Snicolas
  • 37,840
  • 15
  • 114
  • 173
  • Thank you for helping! Actually, the method I want to call is showing a notification and I thought that it is wasteful to create the same method, with the same purpose - twice. – Dennis Nov 30 '12 at 20:41
  • Yes you are right, but that is something different. In that case, you should consider some inheritence or some composition (that's better). Give the method to another entity , and call it in both Activities. That is what @Hermith suggested by the way. – Snicolas Dec 01 '12 at 04:49
  • And read the book. It's really worth it, it was my first Android reading and really helped a lot to get the basics. – Snicolas Dec 01 '12 at 04:49
0

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

Community
  • 1
  • 1
LF00
  • 27,015
  • 29
  • 156
  • 295