调用getActivity()时,setUserVisibleHint()抛出NullPointerException [英] setUserVisibleHint() throwing NullPointerException when calling getActivity()

查看:187
本文介绍了调用getActivity()时,setUserVisibleHint()抛出NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ViewPager中创建了3个片段.我试图仅当特定的碎片对用户可见时才从服务器获取数据.为此,我在setUserVisibleHint()中调用了我的Web服务方法.但是当我在该方法中使用getActivity()时,我得到了NullPointerException.如何确保仅在用户可见时加载一次数据?这里的代码:

I have create 3 Fragments which are in a ViewPager. I am trying to get data from the server only when the particular Fragment is visible to the user. For that I have called my web service method in setUserVisibleHint(). But I am get NullPointerException when I am using getActivity() inside that method. How can I make sure I that I load data only once and when its visible to the user ? Here the code:

@Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser && !_areLecturesLoaded){
            if(getActivity() == null){ //this is always null
                Log.e("Fragment1","No Activity");
            }else{
                getLatLong();
            }
            _areLecturesLoaded = true;
        }
    }

    private void getLatLong() {
        mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                // The next two lines tell the new client that "this" current class will handle connection stuff
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                //fourth line adds the LocationServices API endpoint from GooglePlayServices
                .addApi(LocationServices.API)
                .build();
    }

我已经验证了setUserVisibleHint()之后会调用onAttach()方法.在附加Activity之前,setUserVisibleHint()正在启动.

I have verified that onAttach() method is getting called after setUserVisibleHint(). Before Activity is attached setUserVisibleHint() is firing up.

推荐答案

尝试一下:

boolean isVisible=false;
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    isVisible=isVisibleToUser;

}

 @Override
public void onAttach(Context context) {
    if(visible){
    // do what you must todo
    }else{
     //do what you must todo
    }

}

这篇关于调用getActivity()时,setUserVisibleHint()抛出NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆