How to access to Class method from another Activity in Android? - android

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

Related

I'm a noob and I'm used to writing reusable code with methods. How do I write the same kind of code with Activities?

I'm writing my first android app, and it's going very well so far, but my code is getting obtuse and I'd like to reorganize it in a way that allows me to reuse portions, and add things more easily.
Based on my previous experience writing simple command line programs that call methods, this is how I THINK I should organize my code:
(some code in MainActivity)
Call a void method of the object DoStuff:
Launch Activity1 and write some values to SharedPreferences file, THEN
Launch Activity2 and write some values to SharedPreferences file, THEN
continue running code from MainActivity
Right now Activity1 and Activity2 both launch at the same time. Is there a different way I should be writing/organizing my code? I guess I'm trying to do thing with Activities that I'm used to doing with methods. But I'm aware that my thinking might be wrong on this. I hope this makes sense.
Thank you for your help!
Your understanding of Activities is wrong. Activities do have methods that you can very well use.
An Activity is basically one screen that you see in your app. It can be started, stopped, resumed, etc. You can have different screens shown in one Activity (e. g. with Fragments).
If for example you have a list of notes in one Activity, you could have the detail of one note shown in another DetailActivity.
Only in rare cases, for example if you want to check on startup what Activity to show you could have another activity that does not have a layout but only does some checks and launches another one.
In each of your activities you can have methods to execute what you want on user interaction. Of course this can also go into other classes.
I would recommend you to start with a basic Android tutorial to gain a better understanding of the concepts.

android globally object reference for all activities

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.

Android Best Practice - Communication between Activity and Fragments

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

Are there any downsides to calling Activity.finish(), startActivity(), startActivityForResult() anywhere else besides in the Activity itself?

I have a project that I am working on that is currently calling the Activity methods just about all over the place. (eg. my CameraActivity is calling startActivityForResult() in its JpegPictureCallback, another activity is having startActivityForResult() called in one of its Views, and yet another has one of its button's onClickListeners call finish() )
I am new to Android, but some of this practice seems odd to me. Especially when I have had to explicitly give a child view or onClickListener the parent Activity just so it can call such methods. Usually when I have to go out of my way like that to make something work, there is usually a better way to do it.
Also calling startActivityForResult() in one class and having onActivityResult() returning in another class seems counter intuitive. It seems to not form a logical flow of information.
Specifically my questions are:
Is there a performance impact to calling Activities in this way?
Is this proper coding style? (Both personally, but specifically according to some well-defined guidelines i.e. Android's dev guidelines)
No there is no performance impact in calling activities this way.
Yes this is the standard coding style. Refer the link below for the coding standard.
For detailed info check : http://developer.android.com/training/basics/intents/result.html

Is it possible to recursively use the same activity using intents?

I am at a point of code where I need to use same activity with different values. Is it possible to use same activity recursively?
Yes, its possible but you have to use the condition inside the activity based on the value pass through intents.
It may possible for the same activity with different values so the value pass from previous activity will decide what data will display..
Yes.you can use the same activity but make sure,you don't go into infinite loop nor you get messed up with different codes for various conditions you call the activity.you can achieve that by maintaining extras in Intent you use to call the activity.
Wouldn't it be more suitable (in terms of readability) to create a new Activity-class with the same layout but other functionality? This way one Activity will have one behaviour instead of two - making your code more simple, readable and maintainable.

Categories

Resources