即使我已将视图设置为全局变量并在onCreateView()上调用findViewById,我的视图仍然返回null。片段查看返回空
这是我的视图部分
public class MainMenu extends Fragment {
TextView txt = null;
View view1;
View mView;
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
// view1 = inflater.inflate(R.layout.fragment_main_menu, container, false);
mView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_main_menu, null,false);
pref = getActivity().getPreferences(0);
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(pref.getString("CONSUMER_KEY", ""), pref.getString("CONSUMER_SECRET", ""));
txt = (TextView)mView.findViewById(R.id.tww1);
//run retrieve tweets method
new TweetStream().execute();
new Thread(new MainMenu().new Consumer()).start();
return mView;
}
码以我fragment_main_menu.xml
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/tww1"
android:gravity="center"
android:textSize="100dp"
android:text="OFF"/>
</LinearLayout>
并调用它的代码:
public void turnOn(){
txt.setText("ON");
}
它运行的方法开启功能:
class Consumer implements Runnable {
@Override
public void run() {
try {
while (queue.size() != 0) {
String msg = getObj.getMsg();
String[] result = msg.split("\\s");
String msg2 = result[0];
if(msg2.equals("ON")){
txt.setText("ON");
//turnOn();
}
else if(msg.equals("OFF")){
txt.setText("OFF");
// turnOff();
}
}
if (queue.size() == 0) {
Thread.sleep(1000);
run();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
,这是错误我得到:
06-19 12:47:43.921 5213-9586/? E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-128222
Process: com.example.john.fabric, PID: 5213
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
任何想法?谢谢!
编辑1:我使用虚假的inflater膨胀方法。我不明白为什么我应该得到一个空指针。
Edit2:运行turnOn或setText方法里面都返回null。
,你所谓的'导通()'?并从您开始线程的位置正确地发布所有代码 –
? –
Hi @KrishnaV已添加!它的onCreateView – Gene