8

i am new in android and java ... i am reading from couples of day about android parceling tutorial for transfer data or variables values from one activity to other or one class to other ... but i am not so understood about that. can u tell me that is it necessary to use Parcelable for this purpose because same task can also be perform using static key word for variables as string,int or array type then why parcelable pls explain in detail .. thanks for explanation in advance please provide comparison with example

David Snabel-Caunt
  • 57,804
  • 13
  • 114
  • 132
atul yadav
  • 91
  • 1
  • 4

2 Answers2

7

While technically both approaches will work, there are a couple of flaws.

The first is that the static variable is static. If you have two instances of the same activity, they will both reference the same static object. This is probably not what you want.

Secondly, it's considered bad practice to access global variables. It makes it difficult to see what is going on, is difficult to test and you someone (another class) can modify your data. This creates some horrendous bugs.

By passing the data via a Parcelable object it is very clear what you are doing and you avoid both of these problems.

Note that this advice is not specific to Android, rather to Java and programming in general.

David Snabel-Caunt
  • 57,804
  • 13
  • 114
  • 132
  • hi david can you please provide me working code of using parcelable .because i am searching in internet but there is no full source code.please. my Email id: saurabh262134@gmail.com – atul yadav Jul 08 '11 at 11:47
  • [This is an example](http://stackoverflow.com/questions/2459524/how-can-i-pass-a-bitmap-object-from-1-activity-to-another) of passing an object which implements Parcelable to an Activity. If you want to pass your own object, you'll need to implement the Parcelable interface. There is [an example](http://developer.android.com/reference/android/os/Parcelable.html) in the Android documentation. – David Snabel-Caunt Jul 08 '11 at 11:49
  • 1
    See also this tutorial for another example http://techdroid.kbeanie.com/2010/06/parcelable-how-to-do-that-in-android.html – David Snabel-Caunt Jul 08 '11 at 11:55
  • 1
    thanks for responses..i am trying to learn about this...hope i will...:) – atul yadav Jul 08 '11 at 12:01
  • Not to mention that static variables can cause memory leaks; if you don't explicitly set a null-able static variable back to null, then whatever the variable references won't get cleaned up by the garbage collector. – Patrick Jul 02 '16 at 14:49
0

Static references never get garbage collected so you end up creating something called a memory leak.

You are keeping an object in memory that you don't need and it can't be freed up.

If you instantiate enough objects like this you will get an out of memory (oom) exception which will cause the app to crash.

Evgeny Minkevich
  • 2,319
  • 3
  • 28
  • 42
No Co
  • 13
  • 1
  • 4