0

Hi I have an android library project A. Its Main Activity contains method abc(String).When I am trying to call this method from other project after integrating project A,It force closed. I used the code

 MainActivity a=new MainActivity();
 a.abc("");

Am I do the right way to call a method from library project activity from other project?? please help me I am new to android,thanks in advance.

1 Answers1

3

You should not instantiate a Activity class. Activity has a lifecycle and you should declare the same in manifest and use startActivity(intent).

Check Declaring library components in the manifest file

http://developer.android.com/tools/projects/projects-eclipse.html

Once declared you can start the Activity.

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

Quoting Raghav Sood

By treating an Activity as a normal Java class, you end up with a null context. As most methods in an Activity are called on its Context, you will get a null pointer exception, which is why your app crashes.

Instead, move all such methods which need to be called from other classes into a Utility class which accepts a valid context in its constructor, and then use that context in the methods to do the work.

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • @prince where did i suggest `getInstance`. Did you read the post in full. read Raghav Sood's answer not the other one – Raghunandan Mar 07 '14 at 09:25
  • I used to call method in my oncreate . now how can i declare it as a class?? –  Mar 07 '14 at 09:37
  • @prince did you get the gist of my post. you can't call a method of another activity class. You can start another activity. If you want to call a method use a utils class put the method there then you can create an instance of that class and call the method. Raghav Sood's answer is the best in the link i provided. I don't why the other one got upvoted which popped that in from of the second – Raghunandan Mar 07 '14 at 09:39
  • I got the the points. But I used a method in my oncreate called pop() which used to popup the oncreate window and i declared this method in the same activity.As you said when I am uses a class file for declaring this method it shows errors because my activity contents are there in my method. this is the problem i faced now –  Mar 07 '14 at 09:45
  • @prince i am lost as to what you are saying. I cannot understand. Good luck – Raghunandan Mar 07 '14 at 09:47