0

I have two activites called Activity_A and Activity_B. I have a Method or Function in Activity_A like:

public void printNumber (int i) {
    for(int j = 0; j <= i; j++) {
        Log.w("TAG", "Print number is: " + j);
    }
}

Now I want to call this Method from my another activity called Activity_B.

I am trying to call this Method using following lines:

((Activity_A) this.getApplicationContext()).printNumber();

I write this line in onCreate of Activity_B and this will crash my application and logcat shows this error:

java.lang.ClassCastException: android.app.Application cannot be cast to com.example.app.Activity_A

How can I do this?

Edit: I found this question and acording to "Rich" extends Activity_A to Activity_B. But the problem is Activity_B is a list activity and I have already extends this with ListActivity.

and other answer create an instance of Activity_A and then call method. If I do this a all the variable's become empty or null of Activity_A. And I don't want to make a static method.

Is there any other way to do this without create a static reference or another instance?

Community
  • 1
  • 1
Pari
  • 1,705
  • 4
  • 18
  • 19
  • What you are trying to do here is probably wrong. You either want some other utility class to call this method from, or a better architecture. – Austyn Mahoney Aug 06 '12 at 09:42

3 Answers3

1

getApplicationContext will give you a class of type Application not Activity. So this wont work, You will have to store a static context of activity and then call this method. If you post details of what you are trying to do then someone will suggest solutions

nandeesh
  • 24,740
  • 6
  • 69
  • 79
0

I assume your Activity_A derives from Activity not from Application. getApplicationcontext() returns the Application, not an Activity.

If you want to use your printNumber() from any Activity, put it into the Application or a service.

Martze
  • 921
  • 13
  • 32
0

The application context is a higher level construct than either of your activities.

Activity A is not the parent of Activity B.

"Direct" communication between activities can only be achieved via

from A to B only via an Intent fired through startActivity or startActvityForResult

B can only communicate to A if it has been call with startActivityForResult and then is responded to by

Override the following method in activity A public void onActivityResult(int requestCode, int resultCode, Intent data)

and in Activity B, concluding with a call to

http://developer.android.com/reference/android/app/Activity.html#setResult(int)

Pork 'n' Bunny
  • 6,740
  • 5
  • 25
  • 32