通过对象调用时findViewById抛出空 [英] findViewById throws null when called through an object
问题描述
我在 main.java
函数使用像一些微调UI元素到TextView的。
公共无效updateNearByPeople(){
reportEventPeopleAroundSpinner =(微调)findViewById(R.id.peopleAround);
...
}
当我调用此函数从类中,它工作正常。
但是,当我从另一个调用这个函数 class2.java
通过对象
findViewById
抛出显示java.lang.NullPointerException
如果我做的函数,并在它的所有变量静态
比它也能正常工作,而从打电话 class2.java
但它不与对象调用工作
我怎样才能解决这个搞得对象了解上下文的?
在 main.java
:
保护无效的onCreate(最终捆绑savedInstanceState){ super.onCreate(savedInstanceState);
的setContentView(R.layout.main_view); mainAppContext =这一点;
主要mainObj =新的Main();
gMapObj.initiateMap(mainAppContext,mainObj,mapFrag);
}
在 class2.java
:
公共布尔initiateMap(上下文appContext,主要mainObj,MapFragment mapFrag){
mainAppContext = appContext;
mainAppObject = mainObj;
...
mainAppObject.updateNearByPeople();
}
主要mainObj =新的Main();
你不能做到这一点。活动需要经过其生命周期,建立视图层次结构。如果你只是通过new运算符实例化,无论其onAttach或onCreate方法将被调用。这意味着你不能访问资源和意见,以及
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();
}
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
这篇关于通过对象调用时findViewById抛出空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!