即使我已將視圖設置爲全局變量並在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