Getting Nullpointerexception With Contentprovideroperation
Solution 1:
This is an activity lifecycle issue. When you invoke startActivityForResult()
, the starting activity gets suspended and can, if Android gets short of resources, be destroyed altogether.
When you return from the activity you started, the call to onActivityResult()
happens early in the activity lifecycle - so for example a call to 'getActivity()' inside onActivityResult()
in a fragment will return null if the activity was actually destroyed, but return a non-null value if it wasn't destroyed.
Therefore you can't reliably do anything complex in the onActivityResult()
method. I have two patterns I use here. The first is to just use onActivityResult()
to store the response in instance variables and then take action in the onResume()
method; the second is to conditionally execute code:
@OverridepublicvoidonActivityResult(finalint requestCode, finalint resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (getActivity() != null) {
// as we have an activity, it wasn't destroyed, and we can do stuff here
}
}
Which solution you use depends on the scenario you are dealing with. I use the first solution when transient data is being returned through the data intent (as this is the only way I get it), and the second when the call to onActivityResult()
is just a notification that I should refresh the view from data stored elsewhere.
Post a Comment for "Getting Nullpointerexception With Contentprovideroperation"