GWT Null objects in #UiHandler methods - gwt

I am using GWT 2.4 with MVP.
Here is my view object:
public class LoginWidget extends Composite implements LoginWidgetView {
interface Binder extends UiBinder<Widget, LoginWidget> {
}
private static final Binder BINDER = GWT.create(Binder.class);
#UiField Anchor settings;
public LoginWidget() {
initWidget(BINDER.createAndBindUi(this));
}
#UiHandler("settings")
void handleSettingsClick(ClickEvent e) {
presenter.showSettings();
}
private Presenter presenter;
#Override
public void setPresenter(Presenter presenter) {
this.presenter = presenter;
}
}
I am setting the view´s presenter by
...
getLoginWidget().setPresenter(new LoginWidgetPresenter(placeController));
LoginWidgetPresenter of course implements the view´s Presenter interface. But when I click on the settings anchor, the presenter reference is still null, so presenter.showSettings() throws a NullPointerException.
I suppose that after calling the LoginWidget´s constructor and initializing the widget by
initWidget(BINDER.createAndBindUi(this));
the click handling code in my #UiHandler("settings") method ignores changes to the used objects like my presenter object??
Is there a way to set the presenter object after calling the initWidget() method?
Or is it possible to customize the #UiHandler/initWidget()-behaviour that I can set my presenter afterwards?
Thanks, Manuel

I implement MVP in another way and UIBinder work for my. Maybe if you pass the LoginWidgetPresenter in LoginWidget constructor it works.
public LoginWidget(Presenter presenter) {
this.presenter = presenter;
initWidget(BINDER.createAndBindUi(this));
}
...
getLoginWidget(new LoginWidgetPresenter(placeController));

There are lot of things, which could have gone wrong. The easiest thing is to try to debug your code, by putting breakpoints handleSettings and 'setPresenter' methods.
My guess is that one of following is happening:
setPresenter is never actually called
or
getLoginWidget() always returns a new instance of the widget, and it is quite possible that you are setting presenter on one instance of login widget, but displaying totally different instance of the widget
or
You have getLoginWidget().setPresenter(null) somewhere in your code
or any other guess. It is much more easier to debug, and see for yourself, where and how presenter instance is passed. Anyway, UiBinder will not erase your field values (unless it is modified by someone else to make fun of you)

Related

GWTP get access from child presenter/view to parent presenter/view

I have 2 presenters/view. Lets call them parent and child. parent presenter is a container (using slot mechanism) for the child presenter.
In the child presenter's view user clicked button and I would like to handle this action in parent presenter.
How can I do this? What is the best approach? Should I use some kind of event and eventhandler? Or should I inject one presenter to the other?
Both are possible.
For events - GWTP have a simplified version of GWT events:
public interface MyEventHandler extends EventHandler {
void onMyEvent(MyEvent event);
}
public class MyEvent extends GwtEvent<MyEventHandler> {
public static Type<MyEventHandler> TYPE = new Type<MyEventHandler>();
private Object myData;
public Type<MyEventHandler> getAssociatedType() {
return TYPE;
}
protected void dispatch(MyEventHandler handler) {
handler.onMyEvent(this);
}
public MyEvent(Object myData) {
this.myData = myData;
}
/*The cool thing*/
public static void fire(HasHandlers source, Object myData){
source.fireEvent(new MyEvent(myData));
}
}
So in your child presenter you'll simply do:
MyEvent.fire(this, thatObjectYoudLikeToPass);
and to register it, in the parent, you'd either use:
addRegisteredHandler(MyEvent.TYPE, handler);
or
addVisibleHandler(MyEvent.TYPE, handler);
if you want it to be processed only when the parent is visible. I suggest you yo add these handlers in onBind method of your presenter (don't forget to call super.onBind() first when overriding)
For injection:
Simply make sure:
Your parent presenter is a singleton
To avoid circular dependency error in GIN do not wire it like
#Inject ParentPresenter presenter;
instead do it like this:
#Inject
Provider<ParentPresenter> presenterProvider;
and access it with presenterProvider.get() in your child

How must one use a ListEditor as a child of another Editor?

I am using GWT 2.5.0
My intent was to create an editor hierarchy which binds to a ParentBean object. The ParentBean contains a List<Group>, and the Group bean has a List<ChildBean> and List<Group>. From the Editor tutorials I have found, it seemed simple enough to create an editor which contains a ListEditor as one of its sub-editors. But the parent editor never seems to properly initialize the sub ListEditor.
Here is an explanation of how I attempted to do this.
From the code below, I created a ParentBeanEditor which is composed of one other editor, GroupListEditor.
The GroupListEditor implements IsEditor<ListEditor<Group, GroupEditor>>.
Then, the GroupEditor contains a GroupListEditor subeditor and a ChildBeanEditor.
I initialized the ParentBeanEditor with a ParentBean which contained a list of Group objects, but no GroupEditor was ever constructed for any of the Group objects. I put break points in the EditorSource<GroupEditor>.create(int) method to verify that GroupEditors were being created for each Group in the ParentBean, but the break point was never hit (the ListEditor was not constructing editors).
I expected that the GroupListEditor would be initialized since it was a subeditor of ParentBeanEditor. Neither the list nor the editor chain was set in the GroupListEditor. I tried to set the list of the GroupListEditor subeditor directly in ParentBeanEditor by having it extend ValueAwareEditor<ParentBean>. Doing this, the break point I mentioned above was hit, and the GroupListEditor tried to attach a GroupEditor to the editor chain. But the editor chain was never set, and a NPE is thrown in ListEditorWrapper line 95.
Example
Here is the example where the GroupListEditor is not initializing as expected. The EditorChain is never set, and this results in a NPE being thrown in ListEditorWrapper line 95.
Data Model
public interface ParentBean {
...
List<Group> getGroups();
}
public interface Group {
...
List<ChildBean> getChildBeans();
List<Group> getGroups();
}
public interface ChildBean {
// ChildType is an enum
ChildType getChildType();
}
Editors
The ParentBean Editor
public class ParentBeanEditor extends Composite implements ValueAwareEditor<ParentBean> {
interface ParentBeanEditorUiBinder extends UiBinder<Widget, ParentBeanEditor> {
}
private static ParentBeanEditorUiBinder BINDER = GWT.create(ParentBeanEditorUiBinder.class);
#Path("groups")
#UiField
GroupListEditor groupsEditor;
public ParentBeanEditor() {
initWidget(BINDER.createAndBindUi(this));
}
#Override
public void setDelegate(EditorDelegate<ParentBean> delegate) {}
#Override
public void flush() {}
#Override
public void onPropertyChange(String... paths) {}
#Override
public void setValue(ParentBean value) {
groupsEditor.asEditor().setValue(value.getGroups());
}
}
GroupListEditor
public class GroupListEditor extends Composite implements IsEditor<ListEditor<Group, GroupEditor>>{
interface GroupListEditorUiBinder extends UiBinder<VerticalLayoutContainer, TemplateGroupListEditor> {
}
private static GroupListEditorUiBinder BINDER = GWT.create(GroupListEditorUiBinder.class);
private class GroupEditorSource extends EditorSource<GroupEditor> {
private final GroupListEditor GroupListEditor;
public GroupEditorSource(GroupListEditor GroupListEditor) {
this.GroupListEditor = GroupListEditor;
}
#Override
public GroupEditor create(int index) {
GroupEditor subEditor = new GroupEditor();
GroupListEditor.getGroupsContainer().insert(subEditor, index);
return subEditor;
}
#Override
public void dispose(GroupEditor subEditor){
subEditor.removeFromParent();
}
#Override
public void setIndex(GroupEditor editor, int index){
GroupListEditor.getGroupsContainer().insert(editor, index);
}
}
private final ListEditor<Group, GroupEditor> editor = ListEditor.of(new GroupEditorSource(this));
#UiField
VerticalLayoutContainer groupsContainer;
public GroupListEditor() {
initWidget(BINDER.createAndBindUi(this));
}
public InsertResizeContainer getGroupsContainer() {
return groupsContainer;
}
#Override
public ListEditor<Group, GroupEditor> asEditor() {
return editor;
}
}
GroupEditor
public class GroupEditor extends Composite implements ValueAwareEditor<Group> {
interface GroupEditorUiBinder extends UiBinder<Widget, GroupEditor> {}
private static GroupEditorUiBinder BINDER = GWT.create(GroupEditorUiBinder.class);
#Ignore
#UiField
FieldSet groupField;
#UiField
#Path("childBeans")
ChildBeanListEditor childBeansEditor;
#UiField
#Path("groups")
GroupListEditor groupsEditor;
public GroupEditor() {
initWidget(BINDER.createAndBindUi(this));
}
#Override
public void setDelegate(EditorDelegate<Group> delegate) {}
#Override
public void flush() { }
#Override
public void onPropertyChange(String... paths) {}
#Override
public void setValue(Group value) {
// When the value is set, update the FieldSet header text
groupField.setHeadingText(value.getLabel());
groupsEditor.asEditor().setValue(value.getGroups());
childBeansEditor.asEditor().setValue(value.getChildBeans());
}
}
The ChildBeanListEditor will be using the polymorphic editor methodology mention here. Meaning that a specific leafeditor is attached to the editor chain based off the value of the ChildBean.getType() enum. However, I am not showing that code since I am unable to get the GroupListEditor to properly initialize.
Two concerns about your code:
Why is ParentBeanEditor.setValue feeding data to its child? It appears from this that this was a way to work around the fact that the GroupListEditor was not getting data. This should not be necessary, and may be causing your NPE by wiring up a subeditor before it is time.
Then, assuming this, it seems to follow that the GroupListEditor isn't getting data or a chain. The lack of these suggests that the Editor Framework isn't aware of it. All the basic wiring looks correct, except for one thing: Where is your EditorDriver?
If you are trying to use the editor framework by just invoking parentBeanEditor.setValue and do not have a driver, you are missing most of the key features of this tool. You should be able to ask the driver to do this work for you, and not not to call your own setValue methods throughout the tree.
A quick test - try breaking something in such a way that shouldn't compile. This would include changing the #Path annotation to something like #Path("doesnt.exist"), and trying to run the app. You should get a rebind error, as there is no such path. If you do not get this, you definitely need to be creating and user a driver.
First, try driver itself:
It isn't quite clear from your code what kind of models you are using, so I'll assume that the SimpleBeanEditorDriver will suffice for you - the other main option is the RequestFactoryEditorDriver, but it isn't actually necessary to use the RequestFactoryEditorDriver even if you use RequestFactory.
The Driver is generic on two things: The bean type you intend to edit, and the editor type that will be responsible for it. It uses these generic arguments to traverse both objects and generate code required to bind the data. Yours will likely look like this:
public interface Driver extends
SimpleBeanEditorDriver<ParentBean, ParentBeanEditor> { }
We declare these just like UiBinder interfaces - just enough details to let the code generator look around and wire up essentials. Now that we have the type, we create an instance. This might be created in your view, but may still be owned and controlled by some presenter logic. Note that this is not like uibinder - we cannot keep a static instance, since each one is wired directly to a specific editor instance.
Two steps here - create the driver, and initialize it to a given editor instance (and all sub-editors, which will be automatic):
ParentBeanEditor editor = ...;
Driver driver = GWT.create(Driver.class);
driver.initialize(editor);
Next we bind data by passing it to the driver - it is its responsibility to pass sub-objects to each sub-editor's setValue method, as well as wiring up the editor chain required by the ListEditor.
driver.edit(parentInstance);
Now the user can view or edit the object, as your application requirement works. When editing is complete (say they click the Save button), we can flush all changes from the editors back into the instance (and note that we are still using the same driver instance, still holding that specific editor instance):
ParentBean instance = driver.flush();
Note that we also could have just invoked driver.flush() and reused the earlier reference to parentInstance - its the same thing.
Assuming this has all made sense so far, there is some cleanup that can be done - ParentBeanEditor isn't really using the ValueAwareEditor methods, so they can be removed:
public class ParentBeanEditor extends Composite implements Editor<ParentBean> {
interface ParentBeanEditorUiBinder extends UiBinder<Widget, ParentBeanEditor> {
}
private static ParentBeanEditorUiBinder BINDER = GWT.create(ParentBeanEditorUiBinder.class);
#Path("groups")
#UiField
GroupListEditor groupsEditor;
public ParentBeanEditor() {
initWidget(BINDER.createAndBindUi(this));
}
}
Observe that we still implement Editor<ParentBean> - this allows the driver generics to make sense, and declares that we have fields that might themselves be sub-editors to be wired up. Also: it turns out that the #Path annotation here is unnecessary - any field/method with the same name as the property (getGroups()/setGroups() ==> groups) or the name of the property plus 'Editor' (groupsEditor). If the editor contains a field that is an editor but doesn't map to a property in the bean, you'll get an error. If you actually did this on purpose (say, a text box for searching, not for data entry), you can tag it with #Ignore.

using GIN in GWT Activities

Each of my Activities needs a correspoding singleton View implementation. What's the best strategy to inject them into activities?
constructor injection Activity constructor is called from an ActivityMapper's getActivity(). The ctor already has a parameter (a Place object). I would have to create the ActivityMapper with all possible views injected. Not good...
method injection - "A function so annotated is automatically executed after the constructor has been executed." (GWT in Action, 2nd Ed.) Well, "after the ctor has been executed" is apparently not fast enough because the view (or an RPC service injected this way) is still not initialized when the Activity's start() method is called and I get a NPE.
constructing the injector with GWT.create in Activity's ctor. Useless, as they would not longer be singletons.
What worked best for us was to use Assisted Inject.
Depending on the case, we defined activity factories either in the activity itself, in a package (for building all the activities in that package), or in the ActivityMapper.
public class MyActivity extends AbstractActivity {
private final MyView view;
#Inject
MyActivity(MyView view, #Assisted MyPlace place) {
this.view = view;
...
}
...
}
public class MyActivityMapper implements ActivityMapper {
public interface Factory {
MyActivity my(MyPlace place);
FooActivity foo(FooPlace place);
...
}
// using field injection here, feel free to replace by constructor injection
#Inject
private Factory factory;
#Overrides
public Activity getActivity(Place place) {
if (place instance MyPlace) {
return factory.my((MyPlace) place);
} else if (place instance FooPlace) {
return factory.foo((FooPlace) place);
}
...
}
}
// in the GinModule:
install(new GinFactoryModuleBuilder().build(MyActivityMapper.Factory.class));
BTW, for method injection to work, you still have to create your activities through GIN, so you'd have the same issues as with constructor injection. There's no magic, GIN won't magically inject classes that it doesn't know about and doesn't even know when they've been instantiated. You can trigger method injection explicitly by adding methods to your Ginjector, but I wouldn't recommend it (your code would depend on the Ginjector, which is something you should avoid if you can):
interface MyGinjector extends Ginjector {
// This will construct a Foo instance and inject its constructors, fields and methods
Foo foo();
// This will inject methods and (non-final) fields of an existing Bar instance
void whatever(Bar bar);
}
...
Bar bar = new Bar("some", "arguments");
myGinjector.whatever(bar);
...
A last word: I wouldn't pass the place object directly to the activity. Try to decouple places and activities, that allows you to move things around (e.g. build a mobile or tablet version, where you switch between master and detail views, instead of displaying them side by side) just by changing your "shell" layout and your activity mappers. To really decouple them, you have to build some kind of navigator though, that'll abstract your placeController.goTo() calls, so that your activities never ever deal with places.
I chose a slightly different method that has all the flexibility you need. I don't remember where I picked this design pattern up, but it wasn't my idea. I create the activity as such
public class MyActivity extends AbstractActivity{
private MyView view;
#Inject static PlaceController pc;
#Inject
public MyActivity(MyView view) {
super();
this.view = view;
}
public MyActivity withPlace(MyPlace myPlace) {
return this;
}
...
}
Then I use this in the activity mapper like this:
public class MyMapper implements ActivityMapper {
#Inject Provider<MyActivity> myActivityProvider;
public Activity getActivity(Place place) {
if ( place instanceof MyPlace){
return myActivityProvider.get().withPlace(place);
} else if
...
Also make sure the View is declared singleton in the gin module file.
In my experience a good practice is to have separate activity mappers to deal with the places and activities (the mapping). In the activity you have the presenter, here is example of a activity:
public class ActivityOne extends AbstractActivity {
#Inject
private Presenter presenter;
#Override
public void start(AcceptsOneWidget panel, EventBus eventBus) {
presenter.go(panel);
}
}
The presenter have the view injected inside, it is constructed(the presenter) when "go" method is called. The presenter is declared as singleton in the GIN module and views are usually singletons(with some exceptions like small widgets that appear in many places).
The idea is to move the contact with view inside the presenter (as the goal of the presenter is to deal with the logic and retrieve/update data to/from the view, according to MVP).
Inside the presenter you will have also the RPC services, you do not have to declare them because GIN will "magically" make instance for you, by calling GWT.create
Here is an example of a simple presenter:
public class PresenterOneImpl implements Presenter {
#Inject
private MyView view;
#Inject
private SomeRpcServiceAsync someRpc;
#Override
public void go(AcceptsOneWidget panel) {
view.setPresenter(this);
panel.setWidget(view);
updateTheViewWithData();
}
}
At the end I must note that there are some activities, like the one for the menu, which deal with places and the view directly in order to display the current state. These activities are cached inside the mapper to avoid new instance every time the place is changed.

GWT: how to fire custom events from View and consumed by Activity

I can't make a custom event be received in the Activity. Can anyone please tell me what am I missing? I am using GWT 2.1, MVP pattern and UiBinder.
Here's a sample of what I wrote:
Let's say I have MyCustomEvent class and its handler interface MyCustomEventHandler with its onMyCustomEvent(MyCustomEvent event) method.
I implement the handler interface in the Activity:
class MyActivity extends AbstractActivity implements MyCustomEventHandler {
....
public void onMyCustomEvent(MyCustomEvent event) {
doWhatYouKnow();
}
//EventBus is injected with GIN
public void start(AcceptsOneWidget container, EventBus eventBus) {
...
eventBus.addHandler(MyEvent.TYPE, this);
}
}
Now, the sending part in the view:
public class MyWidget extends Composite {
final PopUpPanel myPopUp;
public MyWidget() {
initWidget(uiBinder.createAndBindUi(this));
myPopUp.addCloseHandler(new CloseHandler<PopupPanel>() {
#Override
public void onClose(CloseEvent<PopupPanel> event) {
MyEvent event = new MyEvent();
fireEvent(event);
}
});
}
}
No exception are thrown and unfortunately onMyCustomEvent is never called in the MyActivity class. Any idea? Thanks a million.
#MyWidget
you can make the constructor take parameter ( eventBus )
which you can pass this from class MyActivity
so when you fire the event #MyActivity
the action will be executed #MyWidget
try this , i think it will work .
I think one of your comments is pointing you in the right direction here. What I'm going to guess is going on is that you have more than one EventBus floating around (there should usually only be one event bus per application).
First of all, make sure the EventBus in your Gin module is bound in the Singleton scope. Also, make sure this is the event bus that you pass in to your PlaceController, and not one you're constructing on your own.
Also, I wouldn't be too worried about the fact that your object is a ResettableEventBus in one place. I believe that's just an object that's created by the Activities/Places framework that just wraps the EventBus object you give it.

passing an object to the constructor of a widget defined in uibinder

I'm trying to pass my app's EventBus to a widget declared in a UiBinder via its constructor. I'm using the #UiConstructor annotation to mark a constructor that accepts the EventBus, but I don't know how to actually reference the object from my ui.xml code.
That is, I need something like
WidgetThatNeedsAnEventBus.java
public class WidgetThatNeedsAnEventBus extends Composite
{
private EventBus eventBus;
#UiConstructor
public WidgetThatNeedsAnEventBus(EventBus eventBus)
{
this.eventBus = eventBus;
}
}
TheUiBinderThatWillDeclareAWTNAEB.ui.xml
<g:HTMLPanel>
<c:WidgetThatNeedsAnEventBus eventBus=_I_need_some_way_to_specify_my_apps_event_bus_ />
</g:HTMLPanel>
I have no problem passing a static value to the WidgetThatNeedsAnEventBus, and I can use a factory method to create a new EventBus object. But what I need is to pass my app's already-existing EventBus.
Is there a way to refer to already-existing objects in a UiBinder?
My eventual solution was to use #UiField(provided=true) on the widget I needed to initialize with a variable.
Then, I just constructed the widget myself in Java, before calling initWidget on the parent.
For example:
public class ParentWidget extends Composite
{
#UiField(provided=true)
protected ChildWidget child;
public ParentWidget(Object theObjectIWantToPass)
{
child = new ChildWidget(theObjectIWantToPass); //_before_ initWidget
initWidget(uiBinder.create(this));
//proceed with normal initialization!
}
}
I'd suggest you use a factory method (described here). This way you can pass an instance to your widget.
With the <ui:with> element you can also pass objects to widgets (provided a setter method exists) (as documented here). But the object will be instantiated via GWT.createwhich I think is not was you intend doing with the eventBus.