Nullpointer exception on popBackStack - android

i am developing android application using fragments and sherlock action bar,
i am using the method
Blockquote
getSherlockActivity().getSupportFragmentManager().popBackStack();
for returning previous fragments.
Sometimes it run well,but sometime it gives NULL POINTER exception.
what will the solution ?

My guess is that there's nothing left to pop. Try checking to see if it exists before popping.

You should check if there is any fragment on your backstack before you try to pop it.
if( getSherlockActivity().getSupportFragmentManager().getBackStackEntryCount() > 0 )
getSherlockActivity().getSupportFragmentManager().popBackStack();

popBackStack() will not cause NullPointerException. I've created a piece of code and called it several times in a row - when there is nothing to pop. It just leaves current fragment visible and does nothing.
I think the problem is not is in popBackStack method, however, I wasn't using ABS, just a regular android fragments API's.
Could you provide a piece of code? Maybe the problem is elsewhere?

If there is no backstack it will cause the null pointer, I have an onMenuItemClickListener() that catches this with the following:
if(navController.getPreviousBackStackEntry() != null) {
navController.popBackStack();
}

Related

Null Pointer Exception if changing toolbar icon on observe? Facing problem with kotlin

Having a filter Fragment A with custom toolbar which is used commonly for many fragments and activity for filter list on click of filter icon of toolbar opening Fragment B to set filter option and and observing filter option using ViewModel and Live data . and opening Fragment A from any where but some times filter icon getting updated according to selected filter and sometimes throwing null pointer for imageview . any suggestion and help most welcome and thanks in advance .
I had tried to remove observers but didn't worked .
Image view already present in xml .
Tried Delay using handler. but still getting same error
Expecting some better and helpful solution.
This is fixed now .
Problem was Observing data before loading fragment without null
"?" safety

How to show DialogFragment from Fragment without null pointers due to fragment is not attached to activity?

I have an issue with showing DialogFragment inside Fragment. It does not matter what I try, I cannot get it to work everytime.
My layout consist of activity with navigation drawer and inside activity I am showing fragments. On those fragments I must show DialogFragment but for that, I must get context/application context/activity/whatever (depends on current year and weather) to show it.
In most cases it works ok but sometimes, even if fragment is constantly showed to user (no configuration changes or anything) it sometimes happen that fragment is not attached. I am getting that error in production as well so it is not just my device.
Good practice for that would be to check with method isAdded() and if activity is not attached then do nothing. I am not sure why this is good practice because users would not be happy if they loose their work since "save dialog" will not be shown just because Google is giving good practices as terrible ones!
So far I have this (among million combinations) inside my fragment:
private void showStoreDialog() {
if (someConditionIsOk) {
StringBuilder sb = new StringBuilder();
sb.append(getString(R.string.someText));
sb.append(MINIMUM_LENGTH);
sb.append(getString(R.string.someText2));
Toast.makeText(getActivity(), sb.toString(), Toast.LENGTH_LONG).show();
return;
}
...
Exception occures on this line: sb.append(getString(R.string.someText));
Cause: android.support.v4.app.Fragment.requireContext (Fragment.java:614)
android.support.v4.app.Fragment.getResources (Fragment.java:678)
android.support.v4.app.Fragment.getString (Fragment.java:700)
solutions.lunalabs.gpsracer.fragments.RecordingFragment.showStoreDialoglog (RecordingFragment.java:152)
I know I could solve this by routing through activity with callbacks but I do not want this because I should route all dialogs through activity even if it is needed only in one fragment. Is there a safe solution to this?
Thank you!

getFragmentManager() returns null sometimes

android.app.Fragment android.app.FragmentManager.findFragmentByTag(java.lang.String)'
on a null object reference
I had found numerous posts with this issue here on SO, but none of them helped me.
It happens relatively rarely (1/100). The place where I call the getFragmentManager() is on the main thread, when a button is clicked :
My flow is simple , first I have fragment A, then add on it several fragments until I get to fragment X.
Once a button is clicked in a custom view class that is instantiated and held in the fragment X, I call :
fragment A.getInstance().showLoadBar();
in fragment A the showLoadBar calls a fragment just for displaying loading, and it uses the getFragmentManager() there.
Most of the time it works great, and I am not able to recreate this crash. But I can see that this crash does happen sometimes.

orientation change, FragmentTransaction, Activity has been destroyed, WeakReference

Alright. My first question here. And I already found some solution, but honestly do not really get the stuff that happens in the background. So perhaps there’s someone who could clear up this stuff a little bit. After days of debugging I’m just glad that it works... and hope I did not make some serious error. So let’s have a look.
I got some Main-Activity. Just a FragmentActivity extending JFeinstein’s SlidingFragmentActivity. Further I decided to go the fragment-way and just put any content (list-fragment, article-fragment, …) as a fragment into a container (to right of the sliding-menu); my main-container. So far, so good.
One essential fragment is my article-fragment. A ViewPager (with a FragmentStatePagerAdapter) - containing some pages with text and perhaps another list-fragment. Still no problem so far, until I decide to rotate the device. And to be more precise, rotating the device works too as long as I do not decide to update my article-fragment.
I understood (correct me if I am wrong) that Android handles the fragments state on its own when rotating the device. And it seems to be everything fine just until I want to reload/update its content.
Ok let’s dig deeper into that.
On first start I got some empty main-container. Then I am loading my article-fragment for the first time. Just getting the SupportFragmentAdapter, creating my ArticleFragment and replace the main-container with the newly created fragment - tagged. No rocket-science - just a simple transaction:
ViewPagerFragment pagerFragment = (ViewPagerFragment)
getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT_ARTICLE);
if(pagerFragment != null){
if(pagerFragment.isResumed()){
pagerFragment.triggerReload();
}
} else {
pagerFragment = new ViewPagerFragment();
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.replace(R.id.id_main_root_frame, pagerFragment, TAG_FRAGMENT_ARTICLE);
t.commitAllowingStateLoss();
}
To avoid creating a fragment each time I reload my content, I’m trying to fetch the fragment before the transaction and - if it is found and resumed - trigger some reload on the existing fragment.
Now I rotate my device in this state. To avoid messing with the fragment state I left onSaveInstanceState() inside the fragment untouched. So I guess the fragment is just destroyed and recreated. And everything still works so far. But I think this part has something of a black box.
After that - normal startup, creating fragment and put into main-container, rotating device - I trigger some update. But instead of finding the old (recreated) fragment by tag, nothings found and a new fragment is created and inserted. At least tried to be inserted, because this is where I got the following exception:
java.lang.IllegalStateException: Activity has been destroyed
To be precise, I get the above exception when finish my transaction with a commitAllowingStateLoss(). When I just commit() the transaction I get the following exception:
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
So that’s where the error comes up. And after ages of debugging and searching I found some hint on this question/answer to get the SupportFragmentManager on a WeakReference of my MainActivity. And what should I say. Since I implemented that, it works. I had to change my update-process a bit, but it works. But leaves some questions ...
The behaviour seems to be similiar. First creation works perfect. Reload just the same - fragment is found by tag. After rotation, article is still shown. And when I reload the fragment with that state it is not found by tag so a new one is created, but the commit()-request does not throw an exception. A look inside the debugger shows that the WeakReference is some other instance (other id), than the one(this) all of this takes place in. And thats where I lose the plot. ..
If some of you could give me some hints, would be great!
Thanks in advance!
try this:
commitAllowingStateLoss(); instead commit();

Android: ArrayIndexOutOfBoundsException at FragmentActivity (Support V4 Lib)

This is the same issue as Issue 22404 hosted on code.google.com (http://code.google.com/p/android/issues/detail?id=22404)
To summarize: 4 fragments on the back stack, delete the dialogFragment from the back stack and rotate the phone.
Looks like the line in is: Fragment f = fm.mActive.get(mOps[pos++]);
mOps[pos++] seems to be -1 for some reason.
And I think the reason being is that a dialogFragment got marked for removal and hence got it's state reset. So when reconstructing the backstack mOps[pos++] returns -1 for index.
Any thoughts on that?

Categories

Resources