亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

在fragment中 String info=bundle.getString("info");報錯

?

activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
? ?super.onCreate(savedInstanceState);
? ?setContentView(R.layout.activity_main);

? ?editText=findViewById(R.id.et_input);
? ?
? ?manager=getFragmentManager();
? ?transaction=manager.beginTransaction();
? ?transaction.add(R.id.content_layout,new ResultFragment());
? ?transaction.commit();
}

? ?// 通過點擊事件將edittext中的內容傳遞給Resultfagment

public void send(View view) {
? ?/*
? ?* 1.獲取輸入框輸入的內容
? ?* */
? ?String ?info=editText.getText().toString().trim();
? ?// 創建bundle對象,將需要傳遞的數據存儲到bundle中 然后調用fragment的setArguments()方法傳遞bundle
? ?ResultFragment rf=new ResultFragment();
? ?Bundle bundle=new Bundle();
? ?bundle.putString("info",info);
? ?rf.setArguments(bundle);
? ?
? ?manager=getFragmentManager();
? ?transaction=manager.beginTransaction();
? ?transaction.replace(R.id.content_layout,rf);
? ?transaction.commit();
}

fragment:

public class ResultFragment extends android.app.Fragment {

? ?private TextView textView;
? ?@Override
? ?public View onCreateView(LayoutInflater inflater, ViewGroup container,
? ? ? ? ? ? ? ? ? ? ? ? ? ? Bundle savedInstanceState) {
? ? ? ?// Inflate the layout for this fragment
? ? ? ? ? ? ? ? ?View view=inflater.inflate(R.layout.fragment_result,null);
? ? ? ? ? ? ? ? ?Bundle bundle=getArguments();
? ? ? ? ? ? ? ? ? String info=bundle.getString("info");
? ? ? ? ? ? ? ? ? textView=view.findViewById(R.id.tv_result);
? ? ? ? ? ? ? ? ? ?textView.setText(info);
? ? ? ? ? ?return view;
? ?}
logcat:

? ?Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference

正在回答

1 回答

自己百度查了一下,好像是由于activity執行onCreate方法的時候fragment就已經被實例化,即使在下面執行如下代碼片,已經被綁定的fragment也無法拿到bundle。我把oncreate中去掉了Fragment的綁定,測試可行。參考來源:https://www.jianshu.com/p/14170fd7d4bf

0 回復 有任何疑惑可以回復我~
#1

慕仔6258935 提問者

但是這樣會導致初始的fragment無法被加載。。。。實在不知道哪里出了問題。
2018-01-08 回復 有任何疑惑可以回復我~
#2

慕仔6258935 提問者

終于找到了,自己不小心,在點擊事件里面,又重新創建fragment的管理器對象,才導致的。send方法里面多寫了一遍 manager = getFragmentManager();
2018-01-08 回復 有任何疑惑可以回復我~
#3

慕仔6258935 提問者 回復 慕仔6258935 提問者

在Fragment中沒有對bundle進行是否為空的判斷,就直接設置textview的內容。
2018-01-08 回復 有任何疑惑可以回復我~

舉報

0/150
提交
取消

在fragment中 String info=bundle.getString("info");報錯

我要回答 關注問題
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號