2013-12-17 617 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); 
}