Java – Get Java.Lang.NullPointerException in Android fragment

Get Java.Lang.NullPointerException in Android fragment… here is a solution to the problem.

Get Java.Lang.NullPointerException in Android fragment

Hello, I’m creating a fragment with a ListView. Whenever I run the code, java.lang.nullpointerexception appears in my fragment. The error log says the problem is in line 1. 24

Line 24: ListView messsagesListView = (ListView) getView.findViewById(

Here is my code :

My fragment class:

public class MessageFragment extends Fragment {

private List<MessageItem> messagesList = new ArrayList<MessageItem>();

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
     TODO Auto-generated method stub
    ListView messagesListView = (ListView) getView()


ArrayAdapter<MessageItem> messageListAdapter = new MessageListAdapter();

return inflater.inflate(R.layout.messages_fragment, container);

public void populateMessagesList() {

messagesList.add(new MessageItem("Gary Walts",
            "10/13/2013, 5:31:55 PM", "22"));
    messagesList.add(new MessageItem("Martha Flames",
            "10/13/2013, 6:32:35 PM", "41"));
    messagesList.add(new MessageItem("Jack Bones",
            "10/12/2013, 9:45:32 AM", "165"));
    messagesList.add(new MessageItem("Chitambaram Patel",
            "10/07/2013, 5:31:55 PM", "21"));
    messagesList.add(new MessageItem("Sally Walts",
            "10/02/2013, 5:31:55 PM", "323"));
    messagesList.add(new MessageItem("Setina Gabriole",
            "09/24/2013, 5:31:55 PM", "257"));
    messagesList.add(new MessageItem("Carl Fosters",
            "09/15/2013, 5:31:55 PM", "22"));

class MessageListAdapter extends ArrayAdapter<MessageItem> {

public MessageListAdapter() {
        super(getActivity(), R.layout.messages_list_item, messagesList);
         TODO Auto-generated constructor stub

    public View getView(int position, View convertView, ViewGroup parent) {
         TODO Auto-generated method stub

View itemView = convertView;

if (itemView == null) {
            itemView = getActivity().getLayoutInflater().inflate(
                    R.layout.messages_list_item, parent, false);

MessageItem messageItem = messagesList.get(position);

TextView friendName = (TextView) itemView

TextView dateAndTime = (TextView) itemView

TextView numberOfMessages = (TextView) itemView

return itemView;

Why is this? Thanks in advance.


Try this

 View v = inflater.inflate(R.layout.messages_fragment, null);
 ListView messagesListView = (ListView) v
 return v;

Or return in getView

 return inflater.inflate(R.layout.messages_fragment, null);

And then

public void onActivityCreated(Bundle savedInstanceState) {
     View v= getView();
     ListView messagesListView = (ListView) v.findViewById(;
     ... // rest of the code

Related Problems and Solutions