2016-07-05 52 views
3

我想要使用Adapter中存在的片段中的數據。我使用setArguments()發送來自Adapter和的數據以接收數據。將數據從適配器發送到Android中的片段。 getArguments()返回null

但是,當我調試它,我得到nullpointerExceptiongetArguments

這就是我發送數據和接收數據的方式。

在Adapter中,發送數據。

ReversalFragment f1 = new ReversalFragment(); 
Bundle bundle = new Bundle(); 
String transId = item.getTxId(); 
bundle.putString("tId", transId); 
f1.setArguments(bundle); 

片段類,獲取數據。

Bundle arguments = getArguments(); 

if(arguments!=null) { 

    String transId = arguments.getString("tId"); 

    if (transId != null) { 

     txView.setText(transId); 
    } 
} 

任何人都可以幫我如何處理這個異常,爲什麼空?

在此先感謝。

+1

請檢查** ** TRANSID添加字符串該字符串集合前不爲空。如果** item.getTxId()**返回null,那麼String transId也將爲null。除此之外,我在這裏沒有看到任何問題。 –

+0

Bundle arguments = this.getArguments(); 如果(argument.bundle.containsKey( 「TID」)){// 做的東西 } 嘗試用這種 –

+0

我希望getArguments()沒有返回空值,而不是有可能arguments.getString( 「TID」) ;對你返回null。 –

回答

1

使用setTag可以對Fragment中的適配器和getTag中的視圖進行設置。 在構建的方法中可以傳遞setTag()中的對象;

@ExportedProperty 
     public Object getTag() { 
      throw new RuntimeException("Stub!"); 
     } 

    public void setTag(Object tag) { 
     throw new RuntimeException("Stub!"); 
    } 
1

你應該叫片段類對象適配器class.Suppose您的片段類名稱爲FragmentB,那麼你應該調用FragmentB類對象,因爲在你的程序,它是無法找出你的片段,你想在哪裏傳遞數據。

FragmentB f1 = new FragmentB(); 
    Bundle bundle = new Bundle(); 
    String transId = item.getTxId(); 
    bundle.putString("tId", transId); 
    f1.setArguments(bundle); 
+0

我在Adapter類中傳遞數據時使用了片段類對象。 – Adheesh

1

你沒有指定片段的名稱顯然, 代替Fragment f1 = new Fragment();Your_Fragment_Name f1 = new Your_Fragment_Name(); 它會對你有幫助。

+0

@ inkedTechie-其實我是這麼做的,但在編寫這個問題時編輯了這個名字。我會在這個問題上改變它。 – Adheesh

+0

@Adheesh在這種情況下,它似乎沒有任何代碼的問題。你如何處理這個片段?這在你使用靜態片段時不起作用。請包括交易片段的代碼。 – inkedTechie

1

你應該試試其他方法。在當前的方法中,您正在爲適配器類中的片段類創建一個對象,並將值分配給該對象,但是當您在Fragment類中時,它將創建一個新實例,並且這些值實際上爲null。

所以你必須嘗試這樣的事:

getArgument()setArgument()方法在你的適配器類。 我非常肯定你在Fragment類中創建適配器的對象,將其設置爲列表視圖或任何內容,此時設置並獲取值。

例如

在片段類:

BaseAdapter adapter = new Adapter(); //constructor called and values set 
Bundle args = adapter.getArgument(); 

現在你可以有確切的論據,需要在不進行任何進一步的方法調用

適配器類:

Bundle bundle; 
public Adapter(){ 
bundle = new Bundle(); 
//put required values 
} 

public Bundle getArgument(){ 
return bundle; 
} 

請注意,套件變量是適配器類中的全局變量

0

由於您將從您的片段創建適配器,這意味着您可以訪問片段中的適配器。

您可以創建在適配器public String getString()和適配器初始化後,你可以在你的片段調用此方法adapter.getString()

相關問題