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.
Related
I need to pass an object between 2 activities that have no connection between them (meaning, neither of them calls the other).
My Main_activity extends TabActivity. I have 2 tabs : CurrencyList (extends ListActivity implements OnItemSelectedListener) and CurrencyCalculator extends Activity.
I also have class currencyData that saves data about different currencies.
In the CurrencyList activity I created a new currencyData object and initiate it with data.
How can I pass it also to the CurrencyCalculator activity?
2 quick ways:
1. use an static method in your activity to retrieve current ticket id
2. Design and implement an interface and register the fragments as listeners from the activity
Static Method is preferable for large data.
If there is absolutely no connection between them, then one method of accessing data in different Activity classes would be to declare the data members as static class members. Keep in mind that static objects from Activities persist even after you destroy the activity and Android keeps this around for some time even after the you leave the application.
These might not be the easiest ways (just some alternate approaches to the two answers given). You can use a Handler or a BroadcastReceiver to pass the data to the other activity through an intent.
Note
that your object would have to implement either Serializable or
Parcelable if you want to pass it through an intent. I have used
Serializable before and as long as your object does not have any
nested custom objects, you actually have to do no additional work.
Also the assumption is that the receiving activity is alive and is
able to receive the broadcast and/or message.
Another approach would be to write the object to a file (again it would need to be serializable) and read it back in the other activity.
I'm very new to Android programming (and Java for that matter) coming from an iOS background.
What I am trying to do, is pass a pointer to a Fragment from one Activity to another.
Basically, I have a starting activity called BeginActivity that handles a couple of Fragments for login and register screens. Once logged in, I load up the main activity of the app called TabsFragmentActivity using this code:
public void loggedIn() {
Intent intent = new Intent(this, TabsFragmentActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
finish();
}
I'm using FLAG_ACTIVITY_CLEAR_TOP as I dont want the user to go back without actually logging out first.
Now the problem:
In BeginActivity I have a pointer to a fragment that holds the users data. I am using it like a singleton, that the first few view fragments can access from BeginActivity.
I need to pass this same object to the new TabsFragmentActivity before I call finish() on it.
How do I do this?
I know I can use putExtra() but I believe that is just for strings etc.. and not other Fragments.
Is there a way in the newly created TabsFragmentActivity that I can reference the BeginActivity to 'grab' the pointer?
Thanks
First of all, you should be sure about Fragments and Activity life cycle.
Fragments are designed to be reusable UI complex components. They look like activity, but you can reuse. So,you can have as many activities you need containing the same fragments, but not the same instances of these fragments.
If you just want to pass you user data for another activity you must use Bundle and putExtra(). Depending of the user data type can be necessary implements Serializable or Parcelable Interfaces, as #gheese said.
If you want to use the same UI appearence of your fragment on two or more activities, besides use Bundle and putExtra. Each activity that you want this behavior must contains a field whose is a Fragment and in the moment of starting this fragment you can use getActivity().getIntent().getExtra to get the user information and populate your fragment.
Basically you need to be able to pass your class via the intent, look at Serializable / Parcelable interfaces
This question has the answer you require
How to pass an object from one activity to another on Android
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
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
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