Skip to content Skip to sidebar Skip to footer

Error When Call Method At Third Fragment

I have sample program like at bellow that I have simplified. There is an error when I call a method in third fragment (ListFragment). Whereas there is alright when I call method in

Solution 1:

ViewPager stores current,right and if any left fragments. When you are in UserFragment you only have UserFragment and ItemFragment. when you are in ItemFragment you have all your fragments. And when you are in ListFragment you only have ListFragment and ItemFragment.

You have a npe at UserFragment:

UserFragment.onClick(UserFragment.java:42)

This part of your code at UserFragment, causes your npe:

public void onClick(View v) {
    if (v == form.getUser_item()) {
        itemFragment.user();
    }

    else if (v == form.getUser_list()) {
        listFragment.user();
       // debug here, you'll see that listFragment is null. thus listFragment.user() throws a npe.
    }
}

Because listFragment is null. It is a bad idea to handle click events of a fragment in another fragment. Try to put your click listeners in to the relevant fragments.

EDIT: To solve your npe; consider my answer. On UserFragment, you can have reference to ItemFragment. On ItemFragment, you can have references to both UserFragment and ListFragment. On ListFragment, you can have reference to ItemFragment. Other references are going to make you get a npe.

But as I mentioned before, it is a bad desing to have direct references from fragments to fragments. See this document's Communicating with the Activity part and implement something like that.

EDIT 2: For your implementation ViewPagers setOffscreenPageLimit method maybe a solution for you. Set it more than 2 and try again.

Solution 2:

Its a bad approach, you should not call other's fragment/activities methods from another activity or fragment, You can use Observer pattern to achieve this.

But Here is the updated code, it will work in your case.

p

ublic voidonClick(View v) {
        if (v == form.getItem_user()) {
            if(usreFragment == null)
              {
               userFragment = newUserFragment();
             }
            userFragment.item();
        }

        elseif (v == form.getItem_list()) {
             if(listFragment == null)
             {
                listFragment = newListFragment();
             }            
             listFragment.item();
        }
    }

Post a Comment for "Error When Call Method At Third Fragment"