in my oncreate method I have this
// Create new fragment and transaction
myFragment = new MyFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.downPart, myFragment);
transaction.commit();
The problem is somethimes it trows forseclose message with this error
Caused by: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.pakagename.pak1.MyFragmentsActivity: make sure class name exists, is public, and has an empty constructor that is public
but it is just sometimes it is random sometimes I start my app and works good, and for example it works like 10 times in row works fine and then when I start it crashes... after that again it works
I can't get it why sometimes it just crashes, is it possible to crash if there are some other apps run in background and somehow they slow my cpu or take a lot of memory, I really do not understand this random behavior.
If you add a Fragment to the FragmentManager, Android will save their state and recreate them if the app's process is ever killed to reclaim memory, etc. 'Minimising' your app (pressing home) and then opening many other apps will cause this. When you return, it can only recreate your fragments if, as the error says, the fragment class name exists, is public, and has an empty public constructor.
You haven't shown us the code for MyFragment, but I am guessing one of these conditions is not true. In particular, it is likely that MyFragment is a (non-static) inner class of your activity. An inner class can only be instantiated within an instance of the outer class, but Android does this from another context when it recreates your fragment. This is why it is a problem to have a Fragment as an inner class.
To fix it, make sure MyFragment is either a static inner class, or its own class, and that the constructor is public (or not present; it will use the default one). A static inner class can exist without an instance of its outer class (and does not have access to any instance variables).
You can test this quite easily by pressing home after launching the app (onSaveInstanceState will be called), killing the process with DDMS, then relaunching your app. Alternatively, try your original steps whereby you open many other apps in-between.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With