How to pass object between unrelated activates? - android

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.

Related

is passing activity to another object a good practice?

I have:
public MissionActivity extends AppCompatActivity {
public SoundPlayer getSoundPlayer();
public DiffrentSoundPlayer getDiffrentSoundPlayer()
//...etc.
}
I am passing this Activity in constructor to another class that need all
this soundplayers and assetManager. All these players need to be created in activity. My question is: is this a good practice in Android to pass reference to Activity to another object?
Passing the activity is not in itself problematic, but given the scope of activities is something that should be done thoughtfully.
Depending on your specific case I would consider wrapping the objects that you have created on the activity inside a data transfer object and pass that object to the class that needs the objects. And by "data transfer object" I simply mean an object whose sole purpose is to store the data/objects that you are transferring.
But simply passing the activity to the other class is also completely okay, as long as you don't store the activity in that other class (just store the objects that you need from the activity).

Android Base Activity: Base's Global Variables, Can't get from some activites

I'm taking an android class now, so I am somewhat new to android app development.
My first assumption for a Base Activity is that it's Global Variables and it's values would be available to all activities. I have found that it is available to my Main Activity, but not any activities after that.
In the Base Activity I am storing an ArrayList of Objects. I also load data from an xml in there that adds objects to the arrayList. Once in the Main Activity I still have access to that arrayList and it's values. I use it to fill a list. But when I go to the next activity, it knows about the arrayList but thinks it is empty.
Do I need to create methods in the base activity to retrieve the arrayList and to add objects to the array list?
Any help would be appreciated.
Thank you,
Michelle
Global variables need to be declared static. Then they would be accessible from any class. Example:
public class Globals {
public static String myString;
}
Any class can read/write the myString like this:
Globals.myString = "foo";
or
String bar = Globals.myString;
From experience I believe the variables of one activity is only avaliable to the other while the activity is active, which means between onCreate and onDestroy, other then that you will probably get a null pointer exception, what you really should be doing is sending the data, or arrays, along with the intent to the other activity.
I dont think you should be calling on other activities variables, although it is possible as stated above. I believe when the activity has had it's onDestroy method called the objects in the activity are destroyed to and are removed from memory. Destroying anything that they held.
What is this base activity? Does it just extend activity? And then MainActivity is extending Activity as well? Only one activity is usable at any one time, if your doing what I think your doing you should have a service which can provide you with everything over the cycle of the application, just remember to stop it when your done with it.

Android: Starting intent service within fragments

I have multiple fragments within an activity. Every fragment has to display some data that is fetched from the server using REST. I have been implementing IntentService with a corresponding receiver for REST requests. Right now I am able to do this by making fragments as inner class within the activity.
The problem I have with inner class is, on orientation change, an error is thrown like "cannot instantiate fragment, no empty constructor". For this problem, on search I found answers like either make the inner class static or create a standalone public class for Fragment. I still don't understand why would this happen on orientation change.
Now if I take the approach of creating a separate standalone class for Fragment, I will have to pass the activity object around to do startService and registerReceiver. And I do not want to use AsyncTask for this, as in my app I perform multiple REST requests within a single fragment and IntentService allows a broadcast to be sent after every request so that I do not have to wait until all the requests are finished to start loading the screen. And I feel it is not ok to pass activity object to a fragment. Shouldn't the fragment be as loosely coupled as possible with the activity so that same fragment can be used within multiple activities? If yes, what would be the best approach in resolving this?

Android: Access method in an activity from another activity

My launch activity starts up another activity whose launch is set to single instance. In this 2nd activity, I have a public method. I then start up a 3rd activity and that activity needs to access the public method in the 2nd activity. I don't want to use startActivity and pass it extras because I assume the onCreate will get called (or am I wrong?) and I need to avoid the 2nd activity from reinitializing itself.
When an activity is started using startActivity, is it possible to gain access to the underlying class instance itself and simply call the method?
I actually came up with a simple solution. As a matter of fact you can access the underlying class of an activity. First, you create a class that is used to hold a public static reference to activity 2. When activity 2 is created, in its onCreate method you store "this" in the static reference. Activity 2 implements an interface with the methods that you want available to any other activity or object. The static reference you hold would be of a data type of this interface. When another activity wants to call a method in this activity, it simply accesses the public static reference and calls the method. This is no hack but is intrinsic to how Java operates and is totally legitimate.
It is not a good idea.
As I can understand method from second activity is actually not connected to particular activity while you want to call it from another one. So carry the method out to other (non-activity) class (maybe static method) and use it from both activities.
It's not directly possible to gain access to activity object started using startActivity (without using some hacks). And frankly you shouldn't even trying to accomplish this.
One Activity component can cycle through several Activity java object while its alive. For example, when user rotates the screen, old object is discarded and new activity object is created. But this is still one Activity component.
From my experience, when you need to do things you described, there is something wrong with your architecture. You either should move part of activity's responsibilities to Service or to ContentProvider, or use Intents, etc. Its hard to recommend anything more specific without knowing more details.
No there is no way to pass a reference via startActivity() however you can use some sort of shared memory to keep reference to your Activity. This is probably a bad design. However passing an extra with your Intent will not cause onCreate, that is completely related to the lifecycle.

Working with same data in three activities

I'm not very experienced in android specific components, so I just can't get where I need to look.
I have three activities:
1st gets info about some groups of objects, user selects some of this groups and activity needs to star next activity
2nd activity shows all objects from groups, that user selected at previous activity, here user can deselect some selected objects and then activity starts 3d activity
3d activity allows user to do something with selected objects
My solution is make some singleton model, that let activities get and save information about objects,
but i suppose, that android has some special components to provide data between activities
Help me to find this components^ please
It depends on the type of data that you want to share:
Primitive Data Types
To share primitive data between Activities/Services in an application, use Intent.putExtras(). For passing primitive data that needs to persist use the Preferences storage mechanism.
Non-Persistent Objects
For sharing complex non-persistent user-defined objects for short duration, the following approaches are recommended:
The android.app.Application class
The android.app.Application is a base class for those who need to maintain global application state. It can be accessed via getApplication() from any Activity or Service. It has a couple of life-cycle methods and will be instantiated by Android automatically if your register it in AndroidManifest.xml.
A public static field/method
An alternate way to make data accessible across Activities/Services is to use public static fields and/or methods. You can access these static fields from any other class in your application. To share an object, the activity which creates your object sets a static field to point to this object and any other activity that wants to use this object just accesses this static field.
A HashMap of WeakReferences to Objects
You can also use a HashMap of WeakReferences to Objects with Long keys. When an activity wants to pass an object to another activity, it simply puts the object in the map and sends the key (which is a unique Long based on a counter or time stamp) to the recipient activity via intent extras. The recipient activity retrieves the object using this key.
A Singleton class
There are advantages to using a static Singleton, such as you can refer to them without casting getApplication() to an application-specific class, or going to the trouble of hanging an interface on all your Application subclasses so that your various modules can refer to that interface instead.
But, the life cycle of a static is not well under your control; so to abide by the life-cycle model, the application class should initiate and tear down these static objects in the onCreate() and onTerminate() methods of the Application Class
Persistent Objects
Even while an application appears to continue running, the system may choose to kill its process and restart it later. If you have data that you need to persist from one activity invocation to the next, you need to represent that data as state that gets saved by an activity when it is informed that it might go away.
For sharing complex persistent user-defined objects, the following approaches are recommended:
Application Preferences
Files
contentProviders
SQLite DB
If the shared data needs to be retained across points where the application process can be killed, then place that data in persistent storage like Application Preferences, SQLite DB, Files or ContentProviders.
yes, you can send data between activities using Intents. Using the putExtra() function for that. If you want to pass your own objects, you need to implement Parcalable class.
There is no problem with using a singleton to share information between your Activities, especially if you need this data to be consistent throughout your whole app.
Alternatively you could use an Intent to pass data between Activities - putExtra().
Yes it does:
http://www.remwebdevelopment.com/dev/a33/Passing-Bundles-Around-Activities.html
Basically you can either send a Bundle or just use putExtra function for that.
try this way please
Intent i = new Intent(this, YourTragetedActivity.class);
i.putExtra("value1", "test1");
i.putExtra("value2", "test2");
startActivity(i);
//// On Your TragetedActivity
getIntent().getStringExtra("value1")
getIntent().getStringExtra("value2")

Categories

Resources