暂停和恢复片段后的空监听器

时间:2015-01-26 08:38:43

标签: android android-fragments nullpointerexception listener onpause

我正在写一份通讯应用程序。我有一个问题,我在activity1中有2个活动(activity1和activity2)我有一个ViewPager,其中的第一个片段是显示朋友列表的FriendsFragment。在FriendsFragment我正在使用一个班来听朋友改变并使用一个监听器。当activity2从activity1开始然后关闭时。监听器在FriendsFragment中为空。

片段代码:

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代码:

 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();
}

callbackObject.onSuccess(friends);行中我得到了NullPointerException

我该如何解决?

1 个答案:

答案 0 :(得分:1)

你必须在onPause()中销毁你的监听器并在你活动的onCreate()中重新创建它