2014-09-22 63 views
0

按標題,我被堵在這個荒謬的問題getListAdapter()從ListFragment返回null,getListView工作

我有一個ListFragment,這裏的精簡代碼:

public class AlarmsListFragment extends ListFragment implements AbsListView.OnItemClickListener { 
    public ListAdapter mAdapter; 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setRetainInstance(true); 

     mAdapter = new AlarmsAdapter(getActivity(), R.layout.alarm_card_item, alarmsList); 
    } 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

     View view = inflater.inflate(R.layout.fragment_alarms_list, container, false); 

     mListView = (AbsListView) view.findViewById(android.R.id.list); 
     mListView.setAdapter(mAdapter); 

     mListView.setOnItemClickListener(this); 

     return view; 
    } 
} 

而且然後有一個活動:

public class MainActivity extends Activity implements AlarmsListFragment.OnAlarmSelectedListener { 
ListFragment mAlarmsListFragment; 
protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     FragmentManager fm = getFragmentManager(); 
     mAlarmsListFragment = (ListFragment) fm.findFragmentByTag(ALARM_LIST_TAG); 
     if (mAlarmsListFragment == null) 
     { 
      mAlarmsListFragment = new AlarmsListFragment(); 
      getFragmentManager().beginTransaction() 
        .add(R.id.listContainer, mAlarmsListFragment, ALARM_LIST_TAG) 
        .commit(); 
     } 
    } 

後來,onOptionsItemSelected,我有一些代碼,需要將項目添加到ListAdapter和無效前面的列表,所以我打電話:

AlarmsAdapter mAdapater = (AlarmsAdapter) mAlarmsListFragment.getListAdapter(); 
mAdapater.add(a); 
mAdapater.notifyDataSetChanged(); 

事情是,我得到一個NullPointerException因爲getListAdapter()返回null,而getListView()工作正常..什麼可能導致這個錯誤?

+0

您是否嘗試過在您的listfragment上創建自己的getadapter方法?並返回mAdapter? – 2014-09-22 16:36:51

+0

這是我見過的最快的正確回覆,mAlarmsListFragment.getListView()。getAdapter()工作,大小寫關閉......但爲什麼getListAdapter()在這種情況下工作? – Mdk 2014-09-22 16:37:08

回答

2

你需要調用setListAdapterListFragment,即:

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

    setRetainInstance(true); 

    mAdapter = new AlarmsAdapter(getActivity(), R.layout.alarm_card_item, alarmsList); 

    setListAdapter(mAdapter); 
} 

你不需要調用setAdapter您的ListView。 ListFragment將處理它。

+0

這就解釋了爲什麼我需要mAlarmsListFragment.getListView()。getAdapter()而不是getListAdapter ...兩者之間有什麼區別?編輯:哦,好的,setListAdapter不需要在setAdapter時引用列表,這就是爲什麼get語句搞亂了 – Mdk 2014-09-22 16:38:39

相關問題