1

I have a class like this:

class TopicFragment extends Fragment{

public TopicFragment(VO vO) { 
    // some code
    }

}

Users are reporting that the app is crashing and the log says this:

 android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.aaa.wert.TopicFragment: make sure class name exists, is public, and has an empty constructor that is public

I have looked into this links but i am not able to solve this;

Do fragments really need an empty constructor?

Fragment - InstantiationException: no empty Constructor -> Google Maps v2?

Please help me with this.

Community
  • 1
  • 1
Goofy
  • 6,098
  • 17
  • 90
  • 156
  • You should post the code that instantiates this Fragment as well. Also, why TopicFragment itself is not public? – Egor Oct 15 '13 at 06:41
  • Well, first of all, change your fragment constructor and make it empty with no parameters also. Then set TopicFragment as public. Then, please post your complete code. – fasteque Oct 15 '13 at 07:02

1 Answers1

1

Just simply add an empty constructor with no parameters which is public. if you have the fragment set in XML without an empty constructor it cannot be created.

public TopicFragment() {
}

I also usually always have just the empty constructor and have a method like this to instantiate with arguments

public static TopicFragment newInstance(VO vo) {
    TopicFragment fragment = new TopicFragment();
    fragment.setVo(vo);
    return fragment;
}

EDIT: and as the guys said in the comments make your class:

public class TopicFragment {
}
DArkO
  • 15,880
  • 12
  • 60
  • 88
  • So do i need to add both the above to my class? – Goofy Oct 15 '13 at 07:14
  • You need to add the first one, you can use the second one if you like instead of yours. Its all about what you are comfortable with for the second one. – DArkO Oct 15 '13 at 07:17
  • 1
    i have added default constructor and it says Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead – Goofy Oct 15 '13 at 07:51
  • The one you have is a non default constructor. it is suggesting to do what i have shown you in my sample and get rid of your constructor. – DArkO Oct 15 '13 at 10:54
  • The docs state you should use setArguments(Bundle) http://developer.android.com/reference/android/app/Fragment.html#Fragment%28%29 – Jonas Geiregat Jun 30 '14 at 08:59
  • even though that might be true, bundle just accepts primitives, plus you need to take care of the keys somehow, this works better for me, but you need to be careful when using the fields, you cannot use them until the fragment is shown/created. So it may be safer to use arguments but more painful and harder to maintain in my opinion – DArkO Jun 30 '14 at 11:17