0

I would like to pass a class reference to intent in order to have the instance of my class inside the Activity loaded. Please, consider I wrote "reference" to class, so it should not be another instance. Following all instruction I found I'm able to pass a class but it finally is another instance.

intent.putExtra("idletime", idle);

idle is my class I would like to pass as reference. and where I'm getting it:

idle_ = getIntent().getParcelableExtra("idletime"); 

but it seems that the reference is for a new instance of my class and not the same class instance I tried to pass.

this is the class definition but I think is not so important:

public class idletime extends AsyncTask<Object, Integer, Boolean> implements Parcelable  {}

Something wrong?

Andrea Guglielmi
  • 197
  • 2
  • 15

1 Answers1

3

but it seems that the reference is for a new instance of my class and not the same class instance I tried to pass.

that is a correct behaviour, putExtra will convert your class to binary form (serialize), then getParcelableExtra will deserialize your class from binary form and this way create a new instance.

marcinj
  • 48,511
  • 9
  • 79
  • 100
  • I'm happy to know that is expected.. but my needs is passing the reference to the original class.. can I do that somehow? I usually work in c++, java has some darkness to me sometime.. – Andrea Guglielmi Mar 09 '17 at 14:33
  • @AndreaGuglielmi Java does not allow direct access to pointers, and even if it did, what would happen if the object is garbage-collected between serialization and deserialization? If you want the original instance so much, you should create a `Map` and serialize a key to the object instead of object itself. – user1643723 Mar 09 '17 at 14:40
  • @AndreaGuglielmi you would have to store this reference in a form of a static field in some class, preferably Application derived - and then access this field in the same way as in C++ you would access static variable of a class. You would need to be carefull with that, as Android is allowed to kill your process any time it wants, and then all the static fields are lost. For examples look here: http://stackoverflow.com/questions/18002227/why-extend-an-application-class – marcinj Mar 09 '17 at 14:46
  • and of course if you go with the static field aproach, then this must be done using a single process. Activities can be started in new processes from the one where startActivity was called. – marcinj Mar 09 '17 at 14:49
  • Thanks a lot, I will refactor this piece of code in a way that the class will be a kind of service somehow. – Andrea Guglielmi Mar 09 '17 at 15:14