Reputation:
I have a function in main.java
that uses some UI elements like spinner to textview.
public void updateNearByPeople() {
reportEventPeopleAroundSpinner = (Spinner) findViewById(R.id.peopleAround);
…
}
When I call this function from within class, it works fine.
But when I call this function from another class2.java
through an object
findViewById
throws java.lang.NullPointerException
If I make the function and all variables in it static
than it also works fine while calling from class2.java
but it doesn’t work with object calls.
How can I solve this and made of object aware of the context?
In main.java
:
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_view);
mainAppContext = this;
Main mainObj=new Main();
gMapObj.initiateMap(mainAppContext,mainObj, mapFrag);
}
In class2.java
:
public boolean initiateMap(Context appContext, Main mainObj, MapFragment mapFrag) {
mainAppContext = appContext;
mainAppObject = mainObj;
…
mainAppObject.updateNearByPeople();
}
Upvotes: 0
Views: 67
Reputation: 157437
Main mainObj=new Main();
you can't do that. The activity needs to go through its lifecycle, to build up its view hierarchy. If you just instantiate it through the new operator, neither its onAttach or onCreate method will be called. It means that you can not access resources and views as well
Upvotes: 1