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?
Related
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
I have made this app that offers it's functionality almost completely in a notification. The configuration is done in the app itself. This is the structure I have now:
Service 1: retrieve data and changes to that data from FireBase and save it in an object. Everything the app needs to show in the app itself is in this object. It gets distributed to other activities via the observable pattern. So these activities implement Observer.
Service 2: this service keeps track of external changes that can directly affect the object in service 1. Therefore, this service is bound to service 1.
Activities: some activities to display the data. All these activities implement Observer and observe the object that's stored in Service 1.
So far so good. The above gives me no problems whatsoever. I can communicate with both services from every activity. Every activity gets an update if the object they are interested in changes and figures out what to do with the updated data.
Now I have this notification, all of it's actions are broadcasted intents, for which I have a BroadcastReceiver that handles these intents. The broadcastreceiver may need data from Service 1 to execute it's action, and all actions are located in simple classes (no activity or service), but I can't bind a broadcastreceiver or objects to a service.
As I see it I have 2 possible solutions here:
Create another service in which all possible "notification" actions are located. This service can be bound to Service 1 and thus can retrieve all the data it needs.
Make the observable object in Service 1 static, so even the objects in which the "notification" actions are located can access it.
Possible problems for solution 1: maybe 3 services is a little over-kill? But putting all functionality in the same service would create a big, unclear service.
Possible problems for solution 2: I've read that static variables are not best practice, because static variables represent global state and are hard to reason about. Source
I hope someone can tell me if I'm right on the above assumptions, and if there's a solution I have not mentioned here.
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
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!
I'm not asking about repairing my code or something I've just have a problem on where to or how to put methods in proper places in my application.
I wrote an application enhancing bluetooth chat - I made service for this bluetooth chat that runs in background. I will have more such services. Basically I want to be able to run methods across whole my application:
send message via bluetooth chat and wait for answer,
scan RFID tag with NFC,
scan Barcode with camera,
etc.
Each of this I know how to do in 1 activity easily. Now I'm looking for a solution to put this in something like a global class that will allow me to call this methods across my whole application - so I don't have to initialize anything but just - doSomething() and it does it.
Where should I put such things:
in custom activity class (all my other activities will use it)?
in application?
something else?
The same applies to handlers. Basically as to bluetooth chat you have to make handler to listen to received messages - where to put it as well.
I'm basically looking for propositions on how to solve this.
You can have one BaseActivity that extends activity and put your common functions in BaseActivity, now extend all other activities with BaseActivity.
Your activity will have these functions available.
For example:
class BaseActivity extends activity{
...........
public void sendMsgViaBluetooth(String msg){
...........
}
}
class MyActivity extends BaseActivity{
<OnSomeEvent>{
sendMsgViaBluetooth(msg);
}
}
I would create a class with some static methods that allows you to obtain instances of certain classes handling different functionality. You can create a listener system where multiple activities can register themselves for events, such as received messages. When the main class then receives something, it will go through all listeners, and inform them.
Otherwise, you can also send broadcasts, and let those activities interested listen for them. A problem here though is that no one is listening, messages might be lost. When you handle it yourself, in case no one is listening you can store messages in a queue, and send them when new listeners register.
I would not go with the BaseActivity idea. The bigger your app gets, the harder this becomes (e.g., what if you want a Fragment to do things as well, a service that should obtain something, or when you want to implement other classes that require to extend anything else than Activity).
To have data/methods that "follows" you all over the scope of your application, create a Class that extends Application. You have to specify in your Manifest that this Class will be your Application class.
android:name="com.example.MyApplicationClass">
After that, you can call getApplication() to get the Application context and cast it to your Class
myAppContext = (MyApplicationClass)getApplication();
Try avoiding Singleton pattern. I've done one in an application and when the app became big enough, my singleton would get erased sometimes (when resuming the application after coming back from launcher). The application context is supposed to keep the data even if the application is in background for a long time.