2016-06-21 53 views
0

我有一个活动相关的两个动态片段之间串,我试图通过使用捆绑的第一块碎片一个文本到第二块碎片,但我得到空指针异常。在两个片段之间传递String是否正确?下面是我的代码:获得NullPointerException异常,同时通过两个片段

第一块碎片

public class FirstFragment extends Fragment { 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 



     View view = inflater.inflate(R.layout.content_main, container, false); 

     String text = "GetThisStringInSecondFragment"; 

     TextView txtView = null; 
     txtView = (TextView) view.findViewById(R.id.firstfragmenttext); 
     txtView.setText(text); 

     Bundle bundle = new Bundle(); 
     bundle.putString("HI", text); 

     return view; 
    } 


} 

第二块碎片

public class SecondFragment extends Fragment { 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.content_secondmain, 
       container, false); 

     TextView txtView = null; 
     txtView = (TextView) view.findViewById(R.id.secondfragmenttext); 


     Bundle bundle = this.getArguments(); 
     String myInt = bundle.getString("HI"); 

     txtView.setText(myInt); 

     return view; 
    } 


} 

活动

public class MainActivity extends AppCompatActivity { 


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

     Button btnLoad = (Button) findViewById(R.id.btn_load); 

     View.OnClickListener listener = new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       FragmentManager fragmentManager = getFragmentManager(); 
       FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
       FirstFragment hello = new FirstFragment(); 
       fragmentTransaction.add(R.id.fragment_container, hello, "HELLO"); 
       fragmentTransaction.commit(); 

       FragmentManager fragmentManager2 = getFragmentManager(); 
       FragmentTransaction fragmentTransaction2 = fragmentManager2.beginTransaction(); 
       SecondFragment hello2 = new SecondFragment(); 
       fragmentTransaction2.add(R.id.fragment_container, hello2, "HELLO"); 
       fragmentTransaction2.commit(); 
      } 
     }; 

     btnLoad.setOnClickListener(listener); 

    } 


} 
+0

什么是异常本身?请添加一个日志。 –

+0

你没有传递包到下一个片段 –

+0

_setArguments()_? – Piyush

回答

相关问题