2013-12-17 568 views
0

這裏是我的努力在Fragment顯示一個列表,其中截至目前不斷上報NullPointerException每當它試圖初始化ListView代碼:空指針異常

public class PortfolioFragment extends ListFragment { 

ListView l; 
ArrayAdapter<String> adapter; 
List<String> list; 

public PortfolioFragment() { 
    // Required empty public constructor 
} 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState);     

} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
    // Inflate the layout for this fragment 
    list = MainActivity.globalArrayTest; 
    l = (ListView) getView().findViewById(android.R.id.list); 
    adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list); 
    l.setAdapter(adapter); 

    return inflater.inflate(R.layout.fragment_portfolio, container, false); 

} 

我得到在這一行錯誤:

l = (ListView) getView().findViewById(android.R.id.list); 
+0

發佈logcat請 – Nfear

+0

您應該使用inflater來查找您的視圖。請參閱@Raghunandan的答案 –

回答

4

更改爲

View v = inflater.inflate(R.layout.fragment_portfolio, container, false); 
l = (ListView) v.findViewById(android.R.id.list); 
return v; 

你應該有下面的XML

<ListView android:id="@android:id/list" 

或覆蓋onActivityCreated和使用getListView()

您也可以爲黑帶評論這比上述更好地利用下方。

@Override 
public void onActivityCreated(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onActivityCreated(savedInstanceState); 
      l = getListView(); // since you extend ListFragment 
} 
+1

在這種情況下,getListView是最佳解決方案 – Blackbelt

3

,因爲要擴展ListFragment你應該使用getListView()代替findViewByIdsetListAdapter應該叫後onCreateView(內onActivityCreated,例如)

0

這是另一種方式去了解這一點,雖然我只延長片段

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
              Bundle SavedInstanceState) { 

      View rootView = inflater.inflate(R.layout.fragment_item, container, false); 


      ListView itemList = (ListView)rootView.findViewById(R.id.itemListView); 


    String[] items = {"Alpha", "Orange", "Pineapple", "Venus", "Echo", "Pent", "Mouse", 
         "Phoenix", "Dent", "Sloppy"}; 


     ArrayAdapter<String> adapter = new ArrayAdapter<String>(rootView.getContext(), 
         R.layout.text_row, items); 

    itemList.setAdapter(new ArrayAdapter<>(rootView.getContext(), 
          R.layout.fragment_item, items)); 

    itemList.setAdapter(adapter); 


    return (rootView); 
}