Skip to content Skip to sidebar Skip to footer

How To Pass Information Between Activities

I have asked this question a few times on here already, but still am not confident enough to start throwing things into my code because I'm afraid I'll ruin the functionality it al

Solution 1:

If you want to pass a custom object from an Activity to another one, your object have to implement Parcelable interface.

Here you can find an example of an object which implements Parcelable. Once you have an instance of this object you can add it to an intent and pass it to other activity.

Let's say you have 2 activities: A and B. If you want to send a custom object from A to B try put your parceable object in an intent and get it back in Activity B.

// Activity ANotebookmyNotebook=newNotebook(); // the "Parcelable" objectIntentintent=newIntent(A.this, B.class);
intent.putExtra("object", myNotebook);
startActivityForResult(intent);

// Activity B// in onCreate methodNotebooknotebook= intent.getParcelableExtra("object");

Solution 2:

there is a good reason you don't find a good example of transfering complicate objects: you don't suppose to that a lot. it's possible to transfer with intent extra any object, with declare the class you want to transfer as implements Serializable, or Parcalable.

but - this is not recomended doing so, unless you have good reason. there are unlimited ways to create "cross activities" objects (databases, singeltones, services..), and passing complicated objects in intent is heavy operation. also it makes terrible performances doing so.

anyway - if you want anyway doing so, that's the way:

this is how to pass serlizable object:

Intentintent=newIntent();
    intent.putExtra(name, someInstanceOfClassWhichImplementsSerializableInterface);

this is how to acheive it on the other activity:

getIntent().getSerializableExtra(name);

about the question that you don't understand how the object still lives after you finish the activity - finish() activity is not triggering distractor!!!, but do triggers to onDestoy() callback. the system decides when it's the right time call the activities distracor , and even if it was distractor - it's not preventing from the Intent object to stay alive - because nobody said your activity is the only one holding reference to it. the intent reference held by the system for the perpose of passing it to the new activity which opened with it.

Solution 3:

Using intent you can send serialized object which is like converting you object into byte stream. If you want to send your object as it is you can use handlers. e.g.

  1. create Bluetooth connection using service(android service)
  2. define handler in you activity which will be static object
  3. from service to send the object add to msg.obj send that msg to handler

Post a Comment for "How To Pass Information Between Activities"