问题
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();
}
I have verified that onAttach() method is getting called after setUserVisibleHint(). Before Activity is attached setUserVisibleHint() is firing up.
回答1:
Keep a Activity reference when onAttach()
is called and use it everywhere instead of getActivity()
Like this:
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
}
回答2:
try this :
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
}
}
来源:https://stackoverflow.com/questions/44856983/setuservisiblehint-throwing-nullpointerexception-when-calling-getactivity