-4

this might not be a new question to you - I have my main activity and I would like to call a method in another activity. Now if I do this I get my application not responding and closed.

I hear there is some special way to call methods in other activity classes?

Yosi199
  • 1,745
  • 4
  • 22
  • 47

2 Answers2

3

This is generally a bad idea, the reason why is because you have no control of the life-cycle of an activity that is not the active Activity. You could call a method and find that the activity you are calling has been destroyed to reclaim resources.

A better option would be to create a Utility class that can provide functions to multiple activities, or place things that must remain throughout the life-cycle of your application into the application class, or shared preferences.

If all your trying to do is pass information to a new activity or get information from another one, you may want to package that information into the intent, or again place it in shared preferences.

Ashterothi
  • 3,282
  • 1
  • 21
  • 35
  • Yes I want to pass some information that was generated in the first activity and display it in the other activities as well. Can you please explain more about this utility class and how to use that? – Yosi199 Aug 18 '11 at 18:37
  • If your only looking to pass information you should put the data as an Extra to your Intent that calls the upcoming class. http://stackoverflow.com/questions/2965109/passing-data-between-activities-in-android – Ashterothi Aug 18 '11 at 18:39
  • this data needs to be displayed on the second Activity's screen, so basically I need to send the info to another class and then somehow use the second activity to pull that info from this "utility class" and display it on screen? – Yosi199 Aug 18 '11 at 18:47
  • No, you should pass it as an extra in the intent as per my last comment. – Ashterothi Aug 18 '11 at 18:52
  • I used class variables to hold information in my app that I couldn't find a good way to carry across a few activies. They work fine for me. – Rob Aug 18 '11 at 18:56
0

Just create another class and place that method in that class.Then access from both activity.

jainal
  • 2,973
  • 2
  • 20
  • 18
  • I've created another class for setting and getting of information from that class. I've found out that writing to this class doesn't make the activity crash, but getting info back from this class is whats crashing my activity. – Yosi199 Aug 19 '11 at 18:31
  • If it helps, I'm trying to change the text in a TextView with info from a utility class I've created: public class Shifts extends Activity implements OnClickListener{ Utility UT2 = new Utility(); public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.shifts); TextView setDate = (TextView)this.findViewById(R.id.shifts); setDate.setText(UT2.date); } @Override public void onClick(View v) { // TODO Auto-generated method stub }} – Yosi199 Aug 19 '11 at 18:47