Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i Create the object of a activity in other class?

I have defined a function in MainActivity now I want to access the function from another class in my app. I have created an object of the MainActivity and with that object I have called the function. Although there is no error, it's not executing. Every time I try to execute, the app crashes.

like image 639
Pramod Yadav Avatar asked Feb 19 '13 11:02

Pramod Yadav


People also ask

Can we create object of class in another class?

You can also create an object of a class and access it in another class. This is often used for better organization of classes (one class has all the attributes and methods, while the other class holds the main() method (code to be executed)). Remember that the name of the java file should match the class name.

How can I transfer data from one activity to another in Android?

We can send the data using the putExtra() method from one activity and get the data from the second activity using the getStringExtra() method.

How do I make another activity as main activity?

If you want to make Login activity your main activity then put the the intent-filter tag inside Login activity. Any activity your want to make your main activity must contain intent-filter tag with action as main and category as launcher.


1 Answers

Activity A should have a variable

static ActivityA activityA;

In onCreate state:

activityA = this;

and add this method:

public static ActivityA getInstance(){
   return   activityA;
 }

In activity B, call

ActivityA.getInstance().myFunction(); //call myFunction using activityA
like image 90
Lumis Avatar answered Sep 18 '22 19:09

Lumis