2017-01-16 44 views
0

訪問適配器我有一個主Activity.class運行片段(不FragmentActivity)通過ViewPager。我有一個自定義適配器與recyclerview列表中的片段。在Fragment外部和內部訪問適配器存在問題。所以:內片段

該代碼完全適用:

private List<MyQuestionList> theList; 
private RecyclerView recyclerView; 
private RecyclerView.Adapter adapter; 

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

    recyclerView = (RecyclerView) theview.findViewById(R.id.recyclerView); 
    recyclerView.setHasFixedSize(true); 

    theList = new ArrayList<>(); 
    requestQueue = Volley.newRequestQueue(getContext()); 

    adapter = new MyQuestionsAdapter(theList, getContext()); 

    recyclerView.setAdapter(adapter); 

    updateAdapter(); // <-- ATTENTION PLEASE, I'VE CALLED THE FUNCTION INSIDE THE FRAGMENT 

} 

public void updateAdapter(){ // <-- METHOD IS PUBLIC 
    removeItem(0); 
} 

***** And there is located parser's method where items are fetching from server 
and adding to recyclerview via adapter successfully. 
But the code is too long, and anyway there is nothing interesting :) ***** 

private void removeItem(int item){ 
    theList.remove(item); 
    adapter.notifyDataSetChanged(); 
} 

但是,當我從主Activity.class調用相同的方法(updateAdapter)這樣的(不是在運行片段內):

Fragment_Questions frau = new Fragment_Questions(); 
frau.updateAdapter(); 

代碼不起作用。下面是日誌:

Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.remove(int)' on a null object reference 
+0

在哪裏添加'Fragment_Questions'片段? –

+0

在調用片段的Activity.class中。 'public void openQuestion {added Fragment_Questions}'。通過onClick =「openQuestion」'' – HEISENBERG

回答

1

既然你說,Fragment_Questions已添加到ViewPager,使用添加的Fragment_Questions對象的引用調用updateAdapter()。

在下面給出的代碼中,您只是創建一個對象,但從不將其添加到viewpager。因此,onCreateView方法永遠不會被調用,這導致NullPointerException

+0

在open-layout中調用openQuestion,但'ViewPager'只是控制標籤佈局,並在它進入時返回'Fragment_Questions'。那麼如何實現這個方案:用戶在'Fragment_Questions'內部的'Activity.class' inits - >方法'X'調用方法中點擊佈局的元素 - >方法'X'? – HEISENBERG

+0

那麼如何從活動中使用它? – HEISENBERG