2017-06-22 34 views
1

activityA我有一個listview,其中每個項目是自定義Parcelable對象。在listViewItemClick我表現出fragment有兩個參數,其中我把bundle用這種方法:捆綁包返回長而不是parcelable

public void openFragment(CustomParcelable parcelableObject, long objectID) { 
    FragmentA fragmentA = new FragmentA(); 
    Bundle bundle = new Bundle(); 
    bundle.putParcelable(FragmentA.KEY, parcelableObject); 
    bundle.putLong(FragmentA.KEY, objectID); 
    fragmentA.setArguments(bundle); 
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 
    transaction.replace(R.id.fragmentContainer, fragmentA); 
    transaction.commitAllowingStateLoss(); 
} 

FragmentA我需要使用選自定義Parcelable對象,所以我把它在onCreatebundle這樣的:

@Override 
public void onCreate(@Nullable Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    Bundle bundle = this.getArguments(); 

    currentObject = bundle.getParcelable(KEY); 
    objectID = bundle.getLong(KEY); 

    ... 
} 

注:currentObject是在fragment定義的私人CustomParcelable,ObjectId存在於fragment長定義的私有,關鍵是public final string定義d在fragment

當我稍後在我的某個方法中使用currentObject時,它返回NPE,因爲currentObject爲null。調試時顯示它得到Parcelable,但是具有objectID的值。

Is the data passed cor數據傳遞是否正確?什麼導致currentObject爲null?

+1

爲什麼您使用相同的密鑰兩種DATAS清除您的疑問?對兩種數據使用不同的密鑰 – Sanoop

+0

我應該使用不同的密鑰嗎?如果是的話,爲什麼呢? –

+1

,因爲在捆綁中我們使用鍵值對計劃,所以對於兩個不同的值,您應該使用兩個鍵 – sumit

回答

2

您必須爲每個數據使用不同的密鑰。因爲包件處理名稱值對,一個密鑰和相應的值,

你做了什麼是用於數據相同的密鑰,所以第一個數據拿到過第二長的數據寫入,

爲例如,如果你看到this中指出,爲putParcelable

插入一個Parcelable值到這個捆綁的映射,置換了的給定鍵的任何現有值。鍵或值都可以爲空。

你應該做的是

public void openFragment(CustomParcelable parcelableObject, long objectID) { 
    FragmentA fragmentA = new FragmentA(); 
    Bundle bundle = new Bundle(); 
    bundle.putParcelable(FragmentA.KEY1, parcelableObject); 
    bundle.putLong(FragmentA.KEY2, objectID); 
    fragmentA.setArguments(bundle); 
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 
    transaction.replace(R.id.fragmentContainer, fragmentA); 
    transaction.commitAllowingStateLoss(); 
} 

和fragmentA

currentObject = bundle.getParcelable(KEY1); 
objectID = bundle.getLong(KEY2); 

希望這

+0

我明白我做錯了什麼。感謝您的幫助,現在它工作正常。 –