I have an Android app with TabManager. Due to change of Android API, I need to upgrade my app for Activity to contain the Fragment. To provide backward compatibility, I use ActionBarSherlock.
My App is working fine. However, looking at the Google Play Developer Console, there is always few crash reports on "java.lang.NullPointerException" on the line with getSherlockActivity(), I think only less than 0.1% out of total users are affected.
For example,
// Example 1
File file = new File(getSherlockActivity().getCacheDir(), "filename");
// Example 2
getSherlockActivity().setSupportProgressBarIndeterminateVisibility(false);
My question: 1. Should I change all the getSherlockActivity() to getActivity()? Or under certain rule, it is mandatory to use one of them? 2. What is the difference between them?
Thanks a lot.
The only difference is that with getSherlockActivity ()
you get the result of getActivity()
but casted as a SherlockActivity. This allows to get access to the ABS specific apis.
If you just need something that is general enough to be in the Activity
class, just use getActivity()
. It will highlight this, otherwise highlight the fact that you use something that is ABS specific using getSherlockActivity ()
.
The NPE can come from :
getActivity()
(or siblings...) before onAttach has been executedgetActivity()
(or siblings...) after onDetach has been executedSo the solution is to check if your fragment is attached before using its activity :
if( isAttached() ) {
getActivity()....
}