2016-02-04 45 views
0

我使用來自Web服務器的信息填充ListView。 在Activity中,我的ListAdapeter工作正常,但是當我試圖在Fragment中使用它時,我無法初始化我的適配器。用Activity和SupportMapFragment的相同方法填充列表視圖

ListAdapter.java

public class ListAdapter extends BaseAdapter { 

    MainActivity main; 

    public ListAdapter(MainActivity main){ 
     this.main = main; 
    } 
    //Some methods. 
} 

MainActivity.java

public class ListReportsFragment extends SupportMapFragment { 
    @Override 
    public ListView list; 
     public ListAdapter adapter; 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_main); 
      Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
      setSupportActionBar(toolbar); 
      //......... 
      list = (ListView) findViewById(R.id.list); 
      adapter = new ListAdapter(this); 
      list.setAdapter(adapter); 

     } 
//........ 
    } 

還有就是可以正常使用,但是,當我嘗試在我的片段使用它:

ListReportsFragment

@Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 
     list = (ListView) getView().findViewById(R.id.list); 
     adapter = new ListAdapter(new MainActivity()); 
     list.setAdapter(adapter); //This is the line 58 
    } 

我得到 java.lang.NullPointerExceptionlayout.ListReportsFragment.onActivityCreated(ListReportsFragment.java:58)

回答

0

更改

adapter = new ListAdapter(new MainActivity()); 

adapter = new ListAdapter(getActivity()); 
0

要創建MainActivity的新對象,這就是爲什麼你得到錯誤

adapter = new ListAdapter(new MainActivity()); 

通MainActivity將其分解,然後將它傳遞給ListAdapter

MainActivity main; 

public ListReportsFragment(MainActivity main){ 
    this.main = main; 
} 

@Override 
public void onActivityCreated(Bundle savedInstanceState) { 
    super.onActivityCreated(savedInstanceState); 
    list = (ListView) getView().findViewById(R.id.list); 
    adapter = new ListAdapter(main); 
    list.setAdapter(adapter); //This is the line 58 
} 
錯誤
0

變化從

adapter = new ListAdapter(new MainActivity()); 

adapter = new ListAdapter(getActivity()); 

此外,如下移動代碼來onCreateView()的這一部分:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.fragment_main, container, false); 

    adapter = new ListAdapter(getActivity()); 
    listView = (ListView) rootView.findViewById(R.id.listview_forecast); 
    listView.setAdapter(arrayAdapter); 

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
//what to do on item click goes here! 
    }); 
    return rootView; 
}