简体   繁体   中英

null listener after pause and resume fragment

i am writing a communication application. i have an issue that i have 2 activity (activity1 and activity2) in activity1 i have a ViewPager , first fragment in it is FriendsFragment that show list of friends. in FriendsFragment i am using a class to listen friends change and use a listener for it. when activity2 starts from activity1 and then close. listener will be null in FriendsFragment .

Fragment code :

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
.
.
.
FriendListController.with(getActivity()).load(new     FriendListController.Callback() {
        @Override
        public void onSuccess(List<Users> friends) {
            users = friends;
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    friendsAdapter.notifyDataSetChanged();
                    livFriends.requestLayout();
                    if (users.size() > 0) {
                        lblHeader.setText(users.get(livFriends.getFirstVisiblePosition())
                                .getNickname().toUpperCase().substring(0, 1));
                    }
                }
            });
        }

        @Override
        public void onError(String error) {

        }
    });

FriendListController Code:

 public interface Callback {
    void onSuccess(List<Users> friends);

    void onError(String error);
}

public static FriendListController with(Activity _activity) {

    return new FriendListController(_activity);
}



public void loadDatabase(Callback callback) {
    callbackObject = callback;

    Thread thread1 = new Thread(new Runnable() {
        @Override
        public void run() {
            Repository repository = new Repository();
            friends = repository.UsersRepository.getFriends();
            callbackObject.onSuccess(friends);
        }

    });
    thread1.start();
}

in line callbackObject.onSuccess(friends); i got NullPointerException .

How can i fix it?

您必须在onPause()中销毁监听器,然后在活动的onCreate()中重新创建它

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM