Best way to pass one data to multiple fragment - java

I have a scenario that i have one activity and 4 fragment , from one of the fragment i am passing the data using interface to the main activity , I am receiving the value or say object , now what i need to do , i have to pass the same object to all other fragment . but i don't wanna to use bundle or static method/field , I just want to know the best idea or approach to this question , what i can do ?
One solution i am thinking using the abstract class , Let's say my abstract class name is ParentFragmentAbstarct should implements the Fragment class and define a abstract method inside it let say setData(), then every Fragment should extends this Fragment class then abstract method is overridden in every fragment , now i am lost , how to set the value in it if i am getting the value only from one of the fragment(let's say from network response i am receiving the data in Fragment 2 n now how to set this same value in other three fragment)

Using Abstract Class with an Array of Fragment Object:
Like ViewPager you have an Adapter holding the instances of those fragments. When one of your fragments informs the MainActivity about the new data using Interface then you can simple iterate on ViewPagerAdapter and call your abstract Method. All the fragments will get notified.
Using Broadcast Receiver
You can declare your own broadcast receiver and made your fragments to listen to those broadcast. when the data is ready, your fragment can send a broadcast and all the other Fragments who are listening to this specific broadcast can thereafter update their state. Check this one
Using Observable RxJava
In ReactiveX an observer subscribes to an Observable. Then that
observer reacts to whatever item or sequence of items the Observable
emits. This pattern facilitates concurrent operations because it does
not need to block while waiting for the Observable to emit objects,
but instead it creates a sentry in the form of an observer that stands
ready to react appropriately at whatever future time the Observable
does so.
have a look at observable
Using EventBus
EventBus is a publish/subscribe event bus for Android and Java.
This is a great library, very small footprint and gets the job done with ease

You could create a singleton data manager class, and have all the fragments subscribe to it and listen for data changes. Each fragment can then have it's own implementation when recieving a state change.
Make any database calls in this manager class and distribute data to the listeners on response callbacks

Related

Transfer information from service to fragment

I have a fragment and a service that is called by the fragment.
The fragment contains a gauge, and the service uses a device's microphone to meausure sound. I would like the gauge to reflect the sound.
Is there a way for me to transfer the sound value from the service to the fragment?
I have tried to send the gauge object from fragment to the service through a parcelable, but because the gauge is from a custom library, I cannot parcelize or serialize it. I have also tried to create a custom class with just an int attribute, sending the object from the fragment to the service, hoping that updating the int attribute in the service would update the int in the fragment, but it didnt work out.
I want this update to be happening at each second of the measurement, so sending the information OnDestroy of the service does not work for me.
Do you have any suggestions on how I could do this? Thanks
For Communication between service and fragment, you have to create boundService.
Implementing TimerTask in service for each second will solve problem of updating value.
Note: we can use liveData of sound value in service and register its observer in fragment so whenever timertask update value in livedata object it will reflect in fragment.

Good Practice - Passing instance and call methods on instance

I would like to bounce something off you guys.
In my Mobile App, I have a lot of Activity and Fragment classes and many of them contain a method or two with code for uploading images to a WebAPI 2.0 web service etc. etc. Sorry, just for info.
Now, I thought about creating a new class (e.g. ServiceController) and then move all the Service Calls to this new class. The problem is, each one for the methods contain code for displaying a ProgressBar and hiding a ProgressBar, and let the activity continue to a next one, etc. etc.
Now, is it good practice to pass an instance of the Activity that is calling the method in the ServiceController to the method in the ServiceController and then for instance do this:
public static void uploadImages(Activity activity) {
new BaseAsyncTask() {
...
...
activity.hideProgressBar();
...
}
PS: Specifically the "activity.hideProgressBar();" above.
Thanks and have fun,
Pieter
There are many ways of decoupling between the classes , First of all service calls shouldn't be in the activity
first solution
1) Create one interface which contains onsuccess , onfailure abstract methods , and the parameters for that methods will be respective data model class types
2) The above interface should be implemented by activity which is dependent of data from server .In these implementation the showing and hiding progress bar , populating UI with data takes place
3)As you said ,Service Controller Instance will be created , while creating the instance of Service controller we have pass the reference of the interface . these interface is used for communication between service controller and activity.
second solution
Use Event Bus For Communicating between service controller and Activity
OTTO EVENT BUS i will prefer these .
Let me know if you have any queries , I Hope these will solve your problem.
third solution
use MVP Pattern Refer MVP Architecture Tutorial Best solution of all

getting Context from Intent

I have an Activity StaggeredPrenotaTour starting a second Activity Details through an Intent, the class Details contains an AsyncTask class ReservationTask, and after some operations to the network, it has to pass a Java Object back go the StaggeredPrenotaTour class.
StaggeredPrenotaTour at the point where it starts Details:
Intent message = new Intent(staggeredPrenotaTour, Details.class);
message.putExtras(bundle);
getContext().startActivity(message);
Basically I need pass my Object to the current context of StaggeredPrenotaTour, so that I don't have to create a new instance of it but update the contents of the current one!
Unfortunately I've read that there is no way you can get a Context from an Intent, so how is another way to get the working instance of StaggeredPrenotaTour inside Details class?
so how is another way to get the working instance of StaggeredPrenotaTour inside Details class?
You don't.
so that I don't have to create a new instance of it but update the contents of the current one!
It sounds like these two activities should share a common data model, perhaps implemented via a singleton manager. StaggeredPrenotaTour can use the revised data in its onResume() method, which will be called as part of it coming back into the foreground after Details is destroyed (e.g., user presses BACK).
Or, use an event bus (LocalBroadcastManager, greenrobot's EventBus, Square's Otto, etc.). Have ReservationTask raise a ReservationResultsEvent that StaggeredPrenotaTour subscribes to, so StaggeredPrenotaTour can find out the results of the work.
Starting another activity doesn't have to be one-way. You can also
start another activity and receive a result back. To receive a result,
call startActivityForResult() (instead of startActivity()).
For details, read the guide on developer.android.com

implementing publish/subscribe in Android

Currently, I am working on an extensible sensing and data processing framework for Android device. This framework will enables a wide range of data signals (e.g., location, wifi, battery, accelerometer) via Android mobile device.
I consider that these data signals are publishers, which publish data. Classes that extends Activity (public class MainActivity extends Activity) are subscribers.
I believe that an ideal way of implementing this functionality is to implement a small publish/subscribe middleware in between publishers and subscribers.
Can you please suggest -- How can I implement publish/subscribe middleware on Android device ? For me, the main issue is -- how the MainActivity class can register itself for getting events and how various data signals notify to many regitered MainActivity class? Please note this middleware does not need advance features like communication over network.
Somebody did it for you http://square.github.io/otto/. Use this framework or check the sourcecode.
Think about an example this way:
SomeFragmentA - this fragment defines an interface with methods in it
SomeFragmentB - this also defines an interface with methods in it
MainActivity - this activity registers for updates from the above fragments
Now, the activity will be listening for events by simply implementing the interfaces from those two fragments and doing whatever it wants.
In this situation, when the fragment publishes anything new, it does that through a call to its method and passes back the arguments as needed.
try{
((YourInterFaceListetener) activity).someMethod(arguments);
}catch(ClassCastException cce){
Log.d(cce.getMessage());
}
Doing this creates that easy communication between the other parts of the app with an activity and you can extend it by simply implementing required interfaces.
Good luck!

Calling third part class method

I have class A (extends Activity) which present a list of items from a table.
In class B (which extends activity) i am calling a method which eventually trigger class C (C extends a broadcast receiver).
In my class C i am updating a table in my DB in which class A gets the items to present.
My question is how to invoke a class A method after class C finish updating the table.
Making class A function static is quite impossible in this case.
If class C extends BroadcastReceiver and it is responsible for updating your database, once you update you can send a new Broadcast to let other parts of your application know that the table update is finished. You will need to register a receiver in the places you want to get the notification (i.e. in your A Activity class). If you only need to broadcast locally (only to your Application) you can use the new LocalBroadcastManager provided by the v4 support library. It will only broadcast locally and get rid of IPC overhead.
Activities generally can't call methods from other activites. You need to find a different way for communicating between those classes. For example instantiate a dynamic receiver via registerReceiver() in the one activity and send a broadcast in the other.
Apart from that, your questions seems to indicates your application architecture is not optimal. There is always only one activity visible at a time. Why do your activities need to communicate with each other?

Categories