How to pass information between Activities - android

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 already has.
What I want to do is have a Bluetooth connection with a device that I can send/receive data to/from, and be able to access it from several different Activities. I know Intents can be used, but can anyone try to explain how intents work?
I don't understand how if I start with an Activity, how I can build an object within that Activity, then end it, and still have the object. When I call the intent in the following Activity, how do I access it?
I can not find example code of an Activity with a custom object that is passed through an intent, opened in another Activity, then passed again through another Activity, and so on. All I can find is things for string's, int's and it seems that those methods are hardcoded for the specific objects.
Any help would be greatly appreciated, thanks.

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 A
Notebook myNotebook = new Notebook(); // the "Parcelable" object
Intent intent = new Intent(A.this, B.class);
intent.putExtra("object", myNotebook);
startActivityForResult(intent);
// Activity B
// in onCreate method
Notebook notebook = intent.getParcelableExtra("object");

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:
Intent intent = new Intent();
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.

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.
create Bluetooth connection using service(android service)
define handler in you activity which will be static object
from service to send the object add to msg.obj send that msg to handler

Related

How to send data from activity to another activity without Intent in android

In my application I want send data from activity to another activity and for this I don't want use Intent.
I know I can use this code :
Intent intent = new Intent(context, Activity.class);
intent.putExtra("name", value);
startActivity(intent);
and for this I don't want use SharedPreferences again!
Do you know other way for send data from activity to another activity without 2 above ways?
If I understand correctly, you are looking for a way to pass data from one Activity to another Activity without using either SharedPreferences or the SQLite database. Using an Intent is OK but not with startActivity(). I assume that this also goes for startActivityForResult().
Two Activitys of the same application will as a rule not be in the foreground at the same time, so LocalBroadcastManager won't be very helpful in this case. Simply "sending" won't be possible, one needs some kind of middle man.
You could look into EventBus libraries, e.g. Otto EventBus
But maybe you'd prefer to work with some type of POJO to hold the data, and perhaps some Observer which the Activitys could query. Such a class could be implemented as a field in a custom class extending Application.

How do I pass a selected object from a list activity to a details activity

Sorry if this is obvious but I am very new to andriod (just playing around trying to learn something new).
I think this is a fairly common thing to do, but I am having trouble figuring out the best way to do it.
Right now I have 3 activities. A main activity that will start a second activity that shows a list of objects, and finally a third activity, started from the list activity, where I want to make changes to the selected object. Both the list and details activities host fragments.
Is there some safe place I store the selected object and retrieve it from the details activity/fragment? It seems like the main activity is the only common link, but I am not sure I can count on that activity not having been destroyed.
Do I need to pass it via an Intent? This seems it would work but also seems overly complicated. (I am thinking I have to serialize the object and return it as a result of the activity)
Should I just combine the final 2 list and details activities into one activity, and swap out the fragments? I think if I do that I can safely store the selected object in the combined activity, is that correct?
The common and the right way to do it:
You have to create an object (that you will pass) and implement Parcelable interface (e.g.) for that object and then pass it with your intent intent.putExtra("identifier", youParcelable)
Example:
Add an object while starting new Activity:
Intent intent = new Intent(getApplicationContext(),
yourActivityClass.class);
intent.putExtra("identifier", youParcelable);
startActivity(intent);
Retrieve object from intent in newly opened Activity:
Object object = getIntent().getExtras().getParcelable("identifier");
Source

How to pass a just created object from one activity to another?

My app contains 2 activitys. Activity A is the one which is created by starting the app. In this one I create an object of my own class MyClass. This class contains one string and 3 integers. In activity A this object gets written.
The second activity B needs to read this object. How can I pass it from A to B? Or is there an other solution?
There are couple of way you can pass an object from one activity to another:
1. Application Class: this class is visible to all your application Activities so you can save your object in this class from one Activity and then access it from the other.
2. You can break apart your Class into the simple variables: string and 3 integers and pass them via a bundle or the intent it self from one activity to another, then construct your object again.
Intent intent = new Intent (this, TargetActivity.class);
intent.putExtra(KEY, value);
intent.putExtra(KEY, "value");
startActivity(intent);
3. If your object implements Serializable/Parcelable then you can pass it via a bundle.
Example on how to serialize an object:
How do I serialize an object and save it to a file in Android?
One option could be implementing Serializable interface and then you can pass object instances in intent extra using putExtra(Serializable..) variant of the Intent#putExtra() method.
//to pass :
intent.putExtra("MyClass", obj);
// to retrieve object in second Activity
getIntent().getSerializableExtra("MyClass");
It can be tricky, because there's no guarantee that your application can't be killed between activities. Actually, it can be killed during activities, so keeping persistent objects around can be tricky.
My preferred way to do this is the "singleton pattern" in which you create a class whose purpose is to create a single instance that holds whatever data you want to hang around. If your application gets killed, the singleton instance will be lost and have to be re-created, but all Android apps run this risk all the time anyway.
See Save multiple instances states of the same Activity in Android for my implementation of a singleton in Android.
Oh, and I should add that this only works within an application where all the activities are in the same process, sharing the same address space. Otherwise, you'll have to make your object serialiazable and write it off to a file.

Sending objects between activities

There are two activity classes in my project and a third class which is subclass of Thread.
Thread Class implements Bluetooth Socket which isn't Parcelable.
First Activity starts the Second Activity using startActivityforResult()
Second Activity creates an object of the Thread class and starts the thread.
I need to pass an object reference of the Thread object from Second Activity to First Activity's onActivityResult() so that I can access Thread object from the first activity.
How can I achieve this?
You have a few options.
You can either break down your object into simple data types and put those values as extras on the intent that you pass back with setResult(), do do so you'd use intent.putExtra(key, value)
Or you can make your data object implement the Parcelable interface so that you can add the data object directly to the intent.
the code to do the latter would look something like this
Intent resultIntent = new Intent();
resultIntent.putExtra("resultObject", mObj);
setResult(ACTION_OK, resultIntent);
then inside your onActivityResult you can pull it out like this:
data.getParcelableExtra("resultObject");
For the latter method to work you need to correctly implement parcelable with your data object. The former method does not require this however, since you'll be passing back simple values only. You'd then have to take those simple values and "re-inflate" the data object on the other side.
I think the best way to achieve this would be to use a singleton. You can only store primitives in Shared Preferences and Bundles. Here is a great reference for creating a singleton.
http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html

Why objects must be serialized before being passed to activities in android?

In order to pass an object to an Activity, object must implement Parcelable/Serializable (or JSON-encoded, or whatever casts the object to a scalar).
(I know the alternative of using singletons, statics and so on.)
Why it is not possible to give a POJO to my Activity, something like new Intent( ... , myObject) or startActivity(intent, myObject) ?
I turned #Jens's comment into a community wiki:
Your call to startActivity is passed through to ActivityManagerNative - which, in turn, communicates with the activity manager service that runs in a completely different process - thus forcing whatever you put in your Intent to be Parcelable or Serializable

Categories

Resources