2015-11-22 77 views
0

fragment A中的list被點擊,它應該通過date1IDfragment B.我跟隨this卻得到了一個NullPointerException。我確定date1ID保留一個值,因爲它們在調用log時顯示值。爲什麼不能在片段之間傳遞數據?

片段A

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> listView, View view, 
            int position, long id) { 
       // Get the cursor, positioned to the corresponding listview_item_row in the result set 
       Cursor cursor = (Cursor) listView.getItemAtPosition(position); 

       // Get the state's capital from this listview_item_row in the database. 
       String ID = 
         cursor.getString(cursor.getColumnIndexOrThrow("_id")); 
       String date1 = cursor.getString(cursor.getColumnIndexOrThrow("Date")); 
       B fragment2 = new B(); 
       Bundle bundle = new Bundle(); 
       bundle.putString("ID", ID); 
       bundle.putString("date1", date1); 
       fragment2.setArguments(bundle); 
       FragmentManager fragmentManager = getFragmentManager(); 
       FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
       fragmentTransaction.replace(R.id.fragment1, fragment2); 
       fragmentTransaction.addToBackStack(null); 
       fragmentTransaction.commit(); 
       Log.e("TAG", ID); 
       Log.e("TAG", date1); 
      } 
     }); 

片段B

EditText name3; 
EditText date3; 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     View view = inflater.inflate(R.layout.updatepage1, container, false); 
     Bundle bundle=this.getArguments(); 
     date=bundle.getString("date1"); 
     ID = bundle.getString("ID"); 
     RetrievePage(date,ID); 
     return view; 
    } 

logcat的錯誤

11-22 23:09:30.896 29447-29447/com.example.project.project E/AndroidRuntime﹕ FATAL EXCEPTION: main 
    Process: com.example.project.project, PID: 29447 
    java.lang.NullPointerException 
      at com.example.project.project.B.onCreateView(B.java:69) 
      at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962) 
      at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1026) 
      at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1207) 
      at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738) 
      at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1572) 
      at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:545) 
      at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141) 
+0

什麼行會導致錯誤? –

+0

@JDev'date = bundle.getString(「date1」);' – John

+0

你的碎片被放置在不同的活動中,對吧? – Dania

回答

2

謝謝大家,我公頃通過使用下面的代碼解決了我自己的問題

添加此片段B,它的工作原理!

Bundle bundle=this.getArguments(); 
      if(getArguments()!=null) 
      { 
       date=bundle.getString("date1"); 
       ID = bundle.getString("ID"); 
      }