Reputation: 3380
I have two different class(class A and Class B). i want to use the method of Class A in Class B. i normally used object for class A and called method in class B. but unfortunately i am getting Force close error. Is that any thing different to call a method of another class in android. I referred many articles in stackoverflow. but i cant understand properly. pls help me to find out the solution.
Upvotes: 0
Views: 22821
Reputation: 49410
As I said in my comment, you shouldnt instantiate activities.
If your method uses some method that are called from a Context
object, you can create a new class ( Class NewClass
) that accepts a context parameter and implements your methods in it.
So this way, you can call your class from any activity:
NewClass nc = new NewClass(this);
Look up for some example of how to use a database in Android. It uses the same way.
Upvotes: 0
Reputation: 21
earlier class A and class B both are extending Activity and now only A extends Activity and B extends A and now B can call functions of A this works for me:-
public class A extends Activity
{
functionOfA(){}
}
public class B extends A
{
//calling function of class A
functionOfA();
}
Upvotes: 2
Reputation: 123
You should not create object like this, you should use context to call object like as below
((Class A) contextObject).function();
it runs perfectly on my system,
Upvotes: 4
Reputation: 3610
In case of Android, class which extends Activity will maintain its life cycle methods. if method which is defined in different class other current running activity may be killed or in pause state. so it is suggested that if method which is reusable in application should in different class for example (AppManager singleton class) rather than being in single activity class
Upvotes: 1
Reputation:
u have to create constructor of class A & in class B make an obj to class A initialize it with
ClassA obj=new classA();
obj.method_A();
hope this will help
Upvotes: 1