I'm writing radio player on android. I want to use RDS fucntion and display text in GUI. I have object that manage radio and its functions. When something changes, like RDS text, i want publish it in simple TextBox inside Activity. How i can notify GUI that one of property has changed (and send new value) and i have to refresh that property? Is there any mechanism inside Android that provide such asynchronous notification functionality? I've read about
PropertyChangeListener but this is mechanizm for JavaBeans, can I adopt that? If yes, tell me how i can register and use change listeners in my case.
You can use the Observer Design Pattern
You can use Handler for this job. Here is some examples:
https://developer.android.com/training/multiple-threads/communicate-ui.html
http://www.techotopia.com/index.php/A_Basic_Overview_of_Android_Threads_and_Thread_handlers
Cheers
Create a class like this:
abstract class RDSTextListener {
public abstract void onRDSTextChanged(String newText);
}
From your activity do something like:
RDSTextListener listener = new RDSTextListener() {
public void onRDSTextChanged(String newText) {
runOnUiThread(new Runnable() {
#Override
public void run() {
((TextView)findViewById(R.id.your_text_view)).setText(newText);
}});
}
}
You will have to pass this listener to your business class. The business class will then call onRDSTextChanged() when its appropriate, and the UI will be updated.
EDIT: Note, this doesn't use interfaces. An abstract class instead. I think that's more Android friendly, avoiding needlessly processing power.
Related
I am creating an android application using MVP architecture. I have created Presenter and Interactor classes. I am struggling to update UI when app is in background and comes back to foreground.
Let's consider following scenario.
Button on UI is clicked and presenter is notified about it. Presenter asked Interactor to provide data from backend. By the time Interactor provides result to presenter somehow UI is in background. How can I save the state of it and change UI components once app is in foreground.
I tried doing following things:
Using flags (turn on the flag and check in onResume to call the method that supposed to be called when callback received. But problem is that let's say if I have 5 different services that can be called by presenter which has different callback then I will require 5 flags which I don't like it)
Using JAVA reflection (Store the name of method be called in HashMap with parameter)
Is there any better way to achieve this?
As name MVP Suggests Model View Presenter
Model : Model is responsible for getter setter methods also known as POJO.
View : Contains activities/fragments with views.
Presenter : Actual Business Logic where you can communicate network calls OR relate with backend databases such as SQLite / MySql.
When button click you need to call presenter which will perform background tasks once it is done you need to notify your view that the response is Success/Failure via CallBacks which done with the help of interfaces.
Example:
interface BaseContract {
interface BaseView {
//Methods for View
void onDoSomething();
}
interface BasePresenter {
void doSomething();
}
}
class BaseMainPresenter implements BaseContract.BasePresenter {
BaseContract.BaseView view;
BaseMainPresenter(BaseContract.BaseView view) {
this.view = view;
}
#Override
public void doSomething() {
if (view != null)
view.onDoSomething();
}
}
class DemoClass implements BaseContract.BaseView {
//Create object of Presenter
/****
* Example :
* BaseMainPresenter baseMainPresenter = new BaseMainPresenter(this);
*/
#Override
public void onDoSomething() {
//Deal with Context here.
}
}
You could add some "pause" logic to your presenter:
Whenever the UI goes to background, you tell the presenter to "pause" and to save any data being received to a cache (could be as simple as a list inside your presenter).
Whenever the UI is back to foreground, you tell your presenter to unpause and to unload its cache to the UI (if the cache list is not null it pushes it to the UI, just like a regular response received by your interactor)
In my Android project, I've got a singleton class that retrieves data from an external source every second. When data is retrieved, it should inform some data display objects that there is new data available so that they can update themselves.
I believe that the best way to implement this is to let the data displayers implement some listening interface and then register with the data retriever singleton.
Is this a good solution? How is this problem normally solved? Are there any ready classes/frameworks for this that I should use?
What you need is a Callback. If new data is available the other Classes which implement the Callback will be informed automatically.
Here is a nice description of Callbacks.
Yes looks like a classic usecase for the observer pattern. http://en.wikipedia.org/wiki/Observer_pattern
One solution is to implement the observer pattern via Observer interface and Observable class. For example:
import java.util.Observable;
public class DataModel extends Observable
{
public void retrieveData()
{
// ...
setChanged();
notifyObservers(); // or notifyObservers(someData);
}
}
import java.util.Observer;
public class ViewClass implements Observer
{
#Override
public void update(Observable observable, Object data)
{
// update the view
}
}
You need to register the observers like this:
DataModel dm = ...;
dm.addObserver(viewClass1);
dm.addObserver(viewClass2);
dm.addObserver(viewClass3);
I am using the MVP design pattern and I have registered my presenter as a listener on the various buttons and other interactive elements on my view. And that works fine, I get notified whenever a user performs some action in the GUI.
However I don't the procedure for notifying the presenter when the model changes. I have data coming in from a server that gets processed in, for example, a User model, and changes the value of my User object.
How do you notify the presenter that the model has changed in Java?
Do I let my model hold a reference to the presenter and explicitly call something like presenter.userObjectHasBeenUpdated() in my model after I have altered the User object? Or is there a way of placing a listener on the User object that will automatically call presenter.userObjectHasBeenUpdated() when the User object gets modified?
I would say that you create a dedicated interface like Observer and you let your presenters implement it. Then each presenter can register themselves on the model objects to be notified whenever an object changes.
public interface Observer {
public void update(Object notification, Object source);
}
and in your model:
private List<Observer> observers = new ArrayList<Observer>();
public void addObserver(Observer observer) {
if (!observers.contains(observer)) {
observers.add(observer);
}
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
protected fireNotification(Object notification) {
for(Observer observer:observers) {
observer.update(notification, this);
}
}
Of course you can improve all this by adding Thread-safety, typing your notification etc...
If you are using Swing Components to show the data in view, you can use their respective models for notification. They also work as listeners but have finer levels of notifications depending on component. For example JTable can be notified of change in a row or change in whole table. See http://docs.oracle.com/javase/1.4.2/docs/api/javax/swing/table/AbstractTableModel.html#fireTableChanged(javax.swing.event.TableModelEvent) for an example.
I've been trying to make multiple Presenters "listen" to the same event but I which to make each event unique to the Presenter.
Ex.
I create 3 Composite widgets each in one different tab. They get all attached to the same event at binding. Let's call it the "NewPrescriptionEvent". If this event is fired, all my 3 composites will try to DO the job. I only want one of them to do it.
The only way I found to do this is by creating a temp event id (an integer inside the event) which I check for each widget which is trying to respond to the event.
Code snippet
private class OnNewPrescription implements NewPrescriptionHandler {
#Override
public void onNewPrescription(NewPrescriptionEvent event, int dataObjectId) {
if (getDataObject().getPatientId() == dataObjectId) {
...
}
}
}
During binding I do the usual:
eventBus.addHandler(NewPrescriptionEvent.TYPE, new OnNewPrescription());
The event:
public class NewPrescriptionEvent extends GwtEvent<NewPrescriptionHandler> {
public static final GwtEvent.Type<NewPrescriptionHandler> TYPE = new GwtEvent.Type<NewPrescriptionHandler>();
private int dataObjectId;
public NewPrescriptionEvent(int dataObjectId) {
this.dataObjectId = dataObjectId;
}
#Override
protected void dispatch(NewPrescriptionHandler handler) {
handler.onNewPrescription(this, dataObjectId);
}
#Override
public GwtEvent.Type<NewPrescriptionHandler> getAssociatedType() {
return TYPE;
}
}
I was thinking that the TYPE need to be different each time but still be the same event. Does anyone have a suggestion?
Thx.
Is it the case that you have an arbitrary number of instances of the same presenter and all are listening to the same event type? And each of your presenters 'controls' a different entity an therefore should only react on events coming from that entity? If that's the case the only solution I see is to parametrize the event as you've done.
Sounds like the EventBus probably isn't the best approach here; this is one of the main problems I've personally had with the EventBus: all events are global, and it's hard to differentiate between different events of a given type.
A good set of rules for asynchronous event handling without a shared EventBus is:
Communicate with child widgets via direct method calls.
Communicate with a parent widget via callbacks/handlers/listeners.
Avoid direct knowledge of sibling widgets (probably beside the point here)
So, the widget that contains the 3 tabs can attach callbacks to each tab that, when called, dispatches each event to its appropriate event handler (Presenters, in your case, I believe).
No global communication required, no knowledge of sources or destinations, only one event type, one reusable tab widget type, and the tab class stays simple. In principle, not too different from adding a ValueChangeHandler to a CheckBox (after all, one doesn't subscribe to check box events via the event bus, you just add a handler directly to the widget).
Rough sketch:
public class TabContainer implements IsWidget {
public TabContainer() {
tab1.addNewPrescriptionHandler(
new NewPrescriptionEventHandler() {
#Override
public void handleNewPrescriptionEvent(NewPrescriptionEvent event) {
handleTab1Event(event);
}
});
tab2.addNewPrescriptionHandler(
new NewPrescriptionEventHandler() {
#Override
public void handleNewPrescriptionEvent(NewPrescriptionEvent event) {
handleTab2Event(event);
}
});
...
}
}
And you might even be able to simplify that with some looping and pairing.
Going the other way, this container can also send events back the other way to your widgets from wherever else using the same principles.
Also, depending on what the Event class contains, you might not even need an Event class; you can define your callbacks and params however you want.
I think the title of the question is your answer.
You need different event types for each of the widgets.
You could try using addHandlerToSource(GwtEvent.Type<H> type, Object source, H handler) if you know the source to listen to.
Another possibility would be to extend EventBus to accept some kind of filter on registration.
I want to implement a design in Java where I have multiple event sources (Threads). Such event source accomplish a specific task and had to notify the unique Event Handler (Class) and this one have to accomplish other tasks according to event sources notifications.
My question is : how to implement this desiqn in the appropriate manner in Java?
There is a design pattern similar to this design?
Thank you in advance :).
I think you are looking for the Observer pattern. Java does have some standard interfaces (java.util.Observer, java.util.Observable), though these are not type specific; so you might consider your own if the domain seems to require it.
class MyThread implements Runnable {
Observable observable;
public MyThread(EventHandler observer) {
observable = new Observable();
observable.addObserver(observer);
}
public void run() {
while (!done()) {
Object result = doStuff();
observable.notifyObservers(result);
}
}
}
// might have this be singleton
class EventHandler implements Observer {
public synchronized void update(Observable o, Object arg) {
accomplishOtherTask();
}
}
Sounds like an actor pattern to me. Each thread acts as an actor, accomplishing one single task. Th eoutcome is set on a queue (yes) to be processed by the next actor.
I have no experience with java actor frameworks, though. Consult Google for that.
In GWT, this is called the event bus. Either GWT.HandlerManager or GWTx.PropertyChangeSupport are Google recommended implementations. The latter is available in J2SE since 1.4.2
Maybe I don't understand your question, but I think you don't need any design pattern, but something from the java.util.concurrent package.
A ThreadPoolExecutor ?
Observable pattern doesn't have an opinion over threading. In EventThread pattern the listener can state in what thread and when is the event handled.
public class MyObservableObject {
...
void addListener(MyListener listener, Executor executor);
}
public interface MyListener {
void onEvent(Object sender, Object event);
}
// Example
obj.addListener( myListener, CURRENT_THREAD );
obj.addListener( myListener, myWorkQueue );
obj.addListener( myListener, AWT_EDT ); // or SWT_EDT
obj.addListener( myListener, Executors.newSingleThreadScheduledExecutor() );