RayKaushik
RayKaushik

Reputation: 23

Android NewBie - facing issue for setAdapter ListView

I am totally new to Android and trying for Fragments for the first time. I have used a ListView activity which I am converting in a fragment. But somehow the ListView element retrieved by findViewById() is giving me null. Can anyone please help me on this.?

Here is the code for ListView Fragment and I m getting error after I call setAdapter method. Log value shows timeTrackerListView as null.I dont know why.!! :(

 package ray.kaushik.nasaapp;

import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

public class TimeTracker extends Fragment{
    private Time_Tracker_Adapter timeTrackerAdapter;
    private String TAG = "TimeTracker";
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        timeTrackerAdapter = new Time_Tracker_Adapter();

    }

    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState){
            return inflater.inflate(R.layout.time__tracker_layout, container, false);
    }

    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
        ListView timeTrackerListView = (ListView) getActivity().findViewById(R.id.time_tracker_List);
        Log.i(TAG, "timeTrackerListView-->" + timeTrackerListView);
        timeTrackerListView.setAdapter(timeTrackerAdapter);
    }
}

Upvotes: 2

Views: 2196

Answers (2)

Sam
Sam

Reputation: 86948

onCreate() is called before onCreateView(). The ListView hasn't been inflated yet, this is why you cannot find it...

Simply move the current onCreate() code into onCreateView() or onActivityCreated().


You should be able to set up your ListView in onCreateView() with little trouble by saving a reference to the inflated View:

public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState){
    View view = inflater.inflate(R.layout.time__tracker_layout, container, false);
    ListView timeTrackerListView = (ListView) view.findViewById(R.id.time_tracker_List);
    timeTrackerAdapter = new Time_Tracker_Adapter();
    timeTrackerListView.setAdapter(timeTrackerAdapter);
    return view;
}

Diagram from Developer's Guide:

Fragment Lifecycle

Upvotes: 3

Barak
Barak

Reputation: 16393

Your issue is you are trying to get the listview before you have set the view (onCreate is called before onCreateView)... you need to move this

ListView timeTrackerListView = (ListView) getActivity().findViewById(R.id.time_tracker_List); 

and anything that references to the onCreateView method.

Upvotes: 2

Related Questions