[android] Create listview in fragment android

As the title I want to create a listview with custom row in Fragment. My code below.

Fragment class

public class PhotosFragment extends Fragment{

public PhotosFragment(){}

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

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

    ArrayList<ListviewContactItem> listContact = GetlistContact();
    ListView lv = (ListView)getActivity().findViewById(R.id.lv_contact);
    lv.setAdapter(new ListviewContactAdapter(getActivity(), listContact));

    return rootView;
}

private ArrayList<ListviewContactItem> GetlistContact(){
    ArrayList<ListviewContactItem> contactlist = new ArrayList<ListviewContactItem>();

    ListviewContactItem contact = new ListviewContactItem();

    contact.SetName("Topher");
    contact.SetPhone("01213113568");
    contactlist.add(contact);

    contact = new ListviewContactItem();
    contact.SetName("Jean");
    contact.SetPhone("01213869102");
    contactlist.add(contact);

    contact = new ListviewContactItem();
    contact.SetName("Andrew");
    contact.SetPhone("01213123985");
    contactlist.add(contact);

    return contactlist; 
    }   
}

Adapter class

public class ListviewContactAdapter extends BaseAdapter{
private static ArrayList<ListviewContactItem> listContact;

private LayoutInflater mInflater;

public ListviewContactAdapter(Context photosFragment, ArrayList<ListviewContactItem> results){
    listContact = results;
    mInflater = LayoutInflater.from(photosFragment);
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return listContact.size();
}

@Override
public Object getItem(int arg0) {
    // TODO Auto-generated method stub
    return listContact.get(arg0);
}

@Override
public long getItemId(int arg0) {
    // TODO Auto-generated method stub
    return arg0;
}


public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    ViewHolder holder;
    if(convertView == null){
        convertView = mInflater.inflate(R.layout.contact_item, null);
        holder = new ViewHolder();
        holder.txtname = (TextView) convertView.findViewById(R.id.lv_contact_item_name);          
        holder.txtphone = (TextView) convertView.findViewById(R.id.lv_contact_item_phone);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.txtname.setText(listContact.get(position).GetName());
    holder.txtphone.setText(listContact.get(position).GetPhone());

    return convertView;
}

static class ViewHolder{
    TextView txtname, txtphone;
}
}

But when I run the app that display no thing. Could anyone tell me what wrong here and how can I fix it?

This question is related to android listview android-fragments

The answer is


I guess your app crashes because of NullPointerException.

Change this

ListView lv = (ListView)getActivity().findViewById(R.id.lv_contact);

to

ListView lv = (ListView)rootView.findViewById(R.id.lv_contact);

assuming listview belongs to the fragment layout.

The rest of the code looks alright

Edit:

Well since you said it is not working i tried it myself

enter image description here


The inflate() method takes three parameters:

  1. The id of a layout XML file (inside R.layout),
  2. A parent ViewGroup into which the fragment's View is to be inserted,

  3. A third boolean telling whether the fragment's View as inflated from the layout XML file should be inserted into the parent ViewGroup.

In this case we pass false because the View will be attached to the parent ViewGroup elsewhere, by some of the Android code we call (in other words, behind our backs). When you pass false as last parameter to inflate(), the parent ViewGroup is still used for layout calculations of the inflated View, so you cannot pass null as parent ViewGroup .

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

So, You need to call rootView in here

ListView lv = (ListView)rootView.findViewById(R.id.lv_contact);

Instead:

public class PhotosFragment extends Fragment

You can use:

public class PhotosFragment extends ListFragment

It change the methods

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ArrayList<ListviewContactItem> listContact = GetlistContact();
        setAdapter(new ListviewContactAdapter(getActivity(), listContact));
    }

onActivityCreated is void and you didn't need to return a view like in onCreateView

You can see an example here


Please use ListFragment. Otherwise, it won't work.

EDIT 1: Then you'll only need setListAdapter() and getListView().


you need to give:

public void onActivityCreated(Bundle savedInstanceState)    
{
  super.onActivityCreated(savedInstanceState);
}

inside fragment.


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to listview

How to add a ListView to a Column in Flutter? Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView` Best way to update data with a RecyclerView adapter Android Recyclerview vs ListView with Viewholder Get clicked item and its position in RecyclerView How to show an empty view with a RecyclerView? NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference RecyclerView vs. ListView How to implement endless list with RecyclerView? Recyclerview and handling different type of row inflation

Examples related to android-fragments

FragmentActivity to Fragment How to start Fragment from an Activity How to use data-binding with Fragment In android how to set navigation drawer header image and name programmatically in class file? Android Fragment onAttach() deprecated How to convert any Object to String? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments java.lang.IllegalStateException: Fragment not attached to Activity java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference