2016-06-09 76 views
0

我實際上有兩個活動。第一個是打電話給對方得到結果。調用片段方法引發NullPointerException異常

的startActivityForResult部分是好的。請求代碼和結果代碼都可以。

但它拋出Context.getResources() NullPointerException,我不明白爲什麼。我知道這個例外是什麼意思,但在這個特殊情況下,我不明白。

這裏是我的源代碼:

的onCreate之前(類範圍)

ComponentsFragment componentsFragment; 

在的onCreate

componentsFragment = new ComponentsFragment(); 

在按鈕單擊事件

Intent i = new Intent(ReportActivity.this, ManageComponentsActivity.class); 
i.putExtra("action", PICK_COMPONENT_REQUEST); 
startActivityForResult(i, PICK_COMPONENT_REQUEST); 

在第二活動

Toast.makeText(c, "*****activity started for result", Toast.LENGTH_LONG).show(); 

Component component = (Component) parent.getItemAtPosition(position); 

Toast.makeText(c, "****component : " + component.getName(), Toast.LENGTH_LONG).show(); 

Intent i = new Intent(); 
i.putExtra("component_name", component.getName()); 
setResult(RESULT_OK, i); 

finish(); 

在第一活動 - onActivityResult

if (requestCode == PICK_COMPONENT_REQUEST && resultCode == RESULT_OK) { 

    Toast.makeText(this, "*****on activity result", Toast.LENGTH_LONG).show(); 
    Toast.makeText(this, "*****component_name : " + data.getStringExtra("component_name"), Toast.LENGTH_LONG).show(); 
    Toast.makeText(this, "*****report_id : " + report_id, Toast.LENGTH_LONG).show(); 
    Toast.makeText(this, "*****category_id : " + category_id, Toast.LENGTH_LONG).show(); 

    try { 

     if (componentsFragment == null) { 
      Toast.makeText(this, "*****componentsFragment IS NULL", Toast.LENGTH_LONG).show(); 
     } 

     //componentsFragment.AddComponentItem(data.getStringExtra("component_name"), report_id, category_id); 
     componentsFragment.AddComponentItem("Fenêtre", "1", "1"); 


     componentsFragment.RefreshList("1", "1"); 

    } 

    catch (Exception e) { 
     Toast.makeText(this, String.valueOf(e), Toast.LENGTH_LONG).show(); 
    } 

} 

對於 '廚房' 的示例部件,實際輸出是:


*****活動開始爲結果

*****組分:廚房

*****上的活動結果

***** COMPONENT_NAME:廚房

***** REPORT_ID:1

***** CATEGORY_ID:1

拋出異常


所以componentsFragment不爲空...

對不起,我有一些問題,我logcat的,所以我實際上敬酒工作:(

回答

0

正是有了替代片段交易的問題。

我沒有使用組件片段在本次交易中如上所述,但是是新創建的。

ComponentsFragment fragment = new CommponentsFragment(); 

    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 

    // Replace whatever is in the fragment_container view with this fragment, 
    // and add the transaction to the back stack so the user can navigate back 
    transaction.replace(R.id.fragment_container, fragment); 
    transaction.addToBackStack(null); // Commit the transaction 
    transaction.commit(); 

這條線:

transaction.replace(R.id.fragment_container, fragment); 

不得不被替換爲:

transaction.replace(R.id.fragment_container, componentsFragment); 

,則應當將其刪除:

ComponentsFragment fragment = new CommponentsFragment();