Reputation: 988
I have an app that points to another app in the play store. It is working fine in test and with a lot of subscribers. But for 2 guys I have a null pointer crash on the line: if (getActivity().getPackageManager()...
I am in a fragment so I doubt that it's a context issue. What could be the reason? A permission issue? What test should I add to check for null pointer?
private void getApp(){
final Uri uri = Uri.parse("market://details?id=" + "test");
final Intent rateAppIntent = new Intent(Intent.ACTION_VIEW, uri);
if (getActivity().getPackageManager()
.queryIntentActivities(rateAppIntent, 0).size() > 0)
{
startActivity(rateAppIntent);
}
}
Upvotes: 0
Views: 720
Reputation: 570
getActivity()
returns null only when your Fragment
is not attached. In my experience your error usually happens when you are doing some asynchronous process before calling the method and user has navigated away from your Fragment
.
Typically you want to do nothing if user has left the Fragment
so a simple if (getActivity() != null)
should to it for you.
Other cases that may cause this error is when you are calling this method from outside your Fragment
class. For example you have just instantiated the Fragment
and call your method before even attaching it to your Activity
. In which case you should know calling Fragment
methods from outside the Fragment
class is a very bad experience. And you have to change your logic so the Fragment
itself will decide "when" to call its methods.
Upvotes: 1
Reputation: 75788
Problem
if (getActivity().getPackageManager().queryIntentActivities(rateAppIntent, 0).size() > 0)
For your Requirement using getActivity().getPackageManager().queryIntentActivities
totally unnecessary .
Simple Way
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=" + "test"));
startActivity(intent);
Upvotes: 1
Reputation: 164
getActivity()
could return null
if your fragment is not attached to activity. You can check it with isAdded()
or simply check if (getActivity() != null)
Upvotes: 1