May be its simple question, may be its repeated question, this question s not for upvote and all.
I just want to pass my object from one activity to second and second to third activity. I know there are a lot of ways using shared preferences, Intent bundle from one to another activity.
The reason I want to know that why I can't use an object globally for all my activities and if I can how it is possible?
Thanks
There is a handful of ways in which you can achieve this.
Using a bus/listener:
https://github.com/greenrobot/EventBus
https://square.github.io/otto/
Using the application class (ready the first answer carefully, there are caveats):
How to declare global variables in Android?
And using utility classes with static methods.
Also, if you are have more than one fragment running at the same time, you can create your own interfaces and implement them where you need to receive the information.
Related
Hope you guys can clarify something for me.
I've been using Android for about 6 months now and I'm still confused about the best way to communicate between Activity and Fragments. I've already read the the info on the android developer site.
Fragment to Activity
Right now I know with 100% absolute certainty that an interface is the best way to communicate from Fragment to Activity. I.e. creating an interface in your Fragment and letting your Activity implement it. This way you can call the method from your interface inside your Fragment and have it handled by the Activity (which implements the interface).
Activity to Fragment
Here's were I'm not sure. The android developer site says that in order to communicate with a Fragment you have to put your objects in a Bundle.
Bundle bundle = new Bundle();
bundle.putInt(SOME_IDENTIFIER, myInt);
Now I've been know to use a Singleton class every now and then when I have quite some functionality that I can separate. Say I have a Singleton called PersistenceService where I handle all of the persistence related stuff, e.g. saving something in the SharedPreferences. The PersistenceService will then hold methods like putMyString(String key, String myString) or putSomeObject(String key, SomeObject someObj). This way a class doesn't have to handle persistence itself but can just call the PersistenceService to do it.
Now say I have to update something in my Fragment, a TextView or something.
This is what I do:
String myString = PersistenceService.getInstance(getActivity()).getMyString(someKey);
textView.setText(myString);
I pass in a context (getActivity()) because I need it to get the SharedPreferences.
Now my actual question is:
Do I retrieve my data in the Activity and pass it to the desired Fragment through its Bundle? Or do I simply reference my Singleton right in my Fragment and access the data there directly.
I'm not stuck or anything, but I'd like to know what you guys would recommend.
Any advice, remarks, info etc. is greatly appreciated.
This is a very broad question, and as the pragmatic thinking and learning book says, the answer to most questions in software is "It all depends!".
And it really does, it really all depends, there's no hard rule in software, "always" and "never" are very powerful words that shouldn't be used in software, so, saying always go for "Bundle" info or Never go for a Singleton is a little bit stupid specifically in software, so, instead of telling you exactly what to use, ask your self what would fit better in your needs taking on count things like, scalability, extensibility manageability, etc. For example:
If you go for Bundle, you give some flexibility to your fragment, you are creating some kind of independent component ready to work with whatever information you provide, on the other hand, if you know that you need that fragment only in that place, and the information you will pass is somehow complex(can't be passed using a bundle), why complicating so much? Just go for the Singleton if it does the job simple and clean.
I hope my point is well explained here, there's no hard rules for one way or another, just be as diligent as possible and don't go one way or another just because of laziness or negligence, instead be analyst if it's worth going one way or another based on your needs, and always take on count that not because you went that way this time it will be true for ALL your scenarios.
Hope it Helps!
Regards!
I use bundle when I want send data from fragment to fragment (from fragment to activity by interface, from activity to fragment by bundle).
If data is used in all fragments singleton is the best way, sometime I use also a istance of data objcet in activity that I manipulate in fragment by public methods of activity but I don't think that this is a best pratic.
Please understand that 2 fragments can’t directly communicate with each other, They will need help of the activity under the context of which they are created. Using an interface :).
Implement the interface in a fragment
interface StartCommunication
Define the interface in the activity whose context fragment is using
public class MainActivity extends Activity implements
SendFragment.StartCommunication
I was wondering if I have 2 activities that needs to update and access the same object . What would be the best way to do it? Should I use Application class? Or perhaps Static variable.. Etc?
Another option I can think of is putting it in a base class that both activities inherit. I will initialize the object from shared preferences during OnResume
If your object holds some kind of preference value, don't put it into a super-class. Make it static and/or use the singleton pattern and separate it from your application logic. This provides you with a more modular structure that will be easier to work with. The application class is probably overkill; singletons do the job most of the time. (The Android docs simply states: "There is normally no need to subclass Application.")
You can add it to a super-class, if it is a logical part of it though.
Don't forget to synchronize your object if it's going to be accessed by another/several thread(s).
There are different method to perform such requirement. Singleton is one of them. The other one is extending the application class. If you want a reference outlining all of these methods please see:
What's the best way to share data between activities?
Suppose I have an activity MyMainActivity, let's say complex enough with a bunch of code.
From another activity, to access a public variable or a method I instanciate :
MyMainActivity ma = new MyMainActivity();
ma.editVariableMethod();
String example_variable = ma.public_examplevariable;
When I instanciate MyMainActivity ma, is it like creating the hole activity again and storing everything from MyMainActivity to memory, and that way it takes the same amount of memory it would take if I was starting MyMainActivity, or is it just a link which permits to edit variables from MyMainActivity?
You can't instantiate an Activity. The framework has to take care of it. If you want to use public methods either make them static OR get a reference to a valid instance of the activity object.
Edit:
As Squonk pointed out, depending on your use case, it might be a better idea to just extract the shared logic to another new class, at least until you know what you're doing. Giving "full access" to internal variables or even methods in an Activity might seem to work, but it's very likely NOT the right approach.
It is a bad practice to share memory-resident objects between objects in Android, no matter what the objects are. Android won't ensure that it will work. There are alternatives available for most use cases. In the particular case of "accessing a public variable" in another Activity, you can call startActivityForResult(), or ensure that your Activities store data they want to "share" in SharedPreferences, etc.
If you have two or more Activities that use the same method, you should first consider if the class needs to be abstracted into a separate object. Ideally, Activities should be frameworks that delegate to POJOs.
My app contains two classes: MainActivity, Activity2.
Activity2 needs to access a non-static method of MainActivity. How to do that?
I'm new with Java and Android, if you can, please explain clearly for beginners what to do.
Thanking you in advance.
Instead of calling methods from a different activity you should use Bundles to pass values from ActivityA to ActivityB when B is started from A.
Alternatively if you want to reuse code you should create a non-activity object which you can create two instances of. Say if you do a lot of heavy calculations in both activities, you can put your calculating code in a "Calculate" object. And just initiate it like you would any other Java object. Just note that these two instance will not share any data between each other.
Calculate calc = new Calculate();
calc.codeIdLikeToReuse(numbersAndStuff);
Hope this helps. I would recommend that you read up on the Activity Life Cycle to get an idea on how the life on an activity is.
Use Broad cast receiver to call methods in different activities you can find help here
and one example
Basically, you can't do that. Two activities don't communicate this way. Usually, only one activity is alive at a time (also this might not be always true). The real answer is to use Intents.
You should read some basic Android tutorial like the anddev book.
you also can use libraries like EventBus to link the code.
refer to this post
I'm on the situation where I have to share variables between activities... but I have one doubt. Which is better: Parcelable object or set it on a custom Application object.
When something is just going to be used in next activity I just pass it as a Parcelable object, and when it is going to be used in more than one activity, I put it on Application context.
What do you think? Is it right? Which is better in performance?
Thanks!
I think your approach is completely valid.
If it is something like a user object that is accessed in every Activity store it in a custom Application object, but be sure to have a way to recreate the object if the application object gets destroyed while the app is in background.
If it is something like a path or a choice the user made that determines how the next activity works send it with the Intent.
There are also some classes that are not easy to put in an Intent. I have an ImageCache that is attached to the application class that allows to keep images like a user profil image in memory between activity changes without the need to decode the bitmap multiple times. If they are designed in a way that they don't fill up all available memory those are also a good fit for a custom app class.
I recommend sharing data between activies with extras. If it's a own class, it must implement Serializible.
If you are feeling lazy, go with Application's singleton pattern.
But, if you want to code smarter, go with Parcelable.