0

So according to this link (http://www.androiddesignpatterns.com/2012/05/using-newinstance-to-instantiate.html) and other reading I've done, it seems like having a default argument-less constructor is good practice but is it necessary? (will things break if I don't do this)

Because I'm passing in an object into my fragment and in order to set the object as an argument to the fragment, I would need to implement Serializable. I'd rather not do this.

edit: related - is it bad practice to pass in a whole object into my fragment?

Ed Lee
  • 187
  • 2
  • 13

1 Answers1

0

Short Answer yes!

You shouldn't pass your arguments in the constructor, in many cases the android system will re create your fragment by NOT using your code with the parameter-less constructor (like some cases of re creating the view for any reason)

at that time the app will crash if the system couldn't find the empty constructor

even if you provide one while using another constructor with parameters, when the system uses the empty constructor the fragment is so prone to crashes because it wasn't initialized the way you wanted it to be, some variables might stay nulls.

I'm assuming you do know the way to send arguments to fragments in bundles form your question , or do I need to explain this?

and I don't understand why would you want to do this anyways! why not just follow their design?

EDIT: I just found that this question might be duplicate,way more detailed answer here Do fragments really need an empty constructor?

Community
  • 1
  • 1
Hassan Khallouf
  • 1,170
  • 1
  • 13
  • 30
  • Oh wow yeah thanks for that other question - but I don't think it mentioned how to deal with non-primitive objects. I need to implement Serializable if I want to follow their design of adding the object argument to the bundle right? – Ed Lee Feb 19 '16 at 01:33
  • you will have to implement either Serializable or Parcelable in your class, they are not hard to implement , if you are just being lazy or something , you can send your variables from your objects seperatly as ints and strings and so on, and then re create your object in the fragment, but it's really not that big deal to implement either of those – Hassan Khallouf Feb 19 '16 at 01:43
  • Ok I'll definitely have to do it this way. Is there any performance hit to loading the fragment by passing in the object due to passing along the size? – Ed Lee Feb 19 '16 at 02:04
  • I'm not sure I understand the last sentence, due to passing along the size? – Hassan Khallouf Feb 19 '16 at 02:06
  • Due to the potentially large size of the object that you're trying to pass in the Bundle – Ed Lee Feb 19 '16 at 02:41
  • I don't think so .. you are not creating a new object .. even if you are it's not a big deal – Hassan Khallouf Feb 19 '16 at 02:54