GWT - Reference to a global variable set by callback method - gwt

Please help me, as I will go mad with this soon:
When I run the code, on first occasion loadNewPoint() is executed and displays some data from global variable - allPointsAndPlaces
However when I click a button (from a child class), the same method loadNewPoint() gives me null pointer for allPointsAndPlaces.
I have changed the code structure a lot from an original trying to solve this issue, and moved this method (loadNewPoint()) to a parent class to see, if it would solve the issue.
Parent class:
public class CabbieApp implements EntryPoint {
private GetLocationsServiceAsync getAllLocationsService = GWT.create(GetLocationsService.class);
CabbiePoint[] allPointsAndPlaces;
PointsQuiz quiz;
/**
* Entry point method.
*/
public void onModuleLoad() {
//Get all the required data from DB
getAllPointsAndLocations();
}
private void loadAppPages(){
// Associate the Main panel with the HTML host page.
RootPanel rootPanel = RootPanel.get("pointsList");
quiz = new PointsQuiz();
rootPanel.setStyleName("GWTapp");
rootPanel.add(quiz.getMainPanel());
loadNewPoint();
}
private void getAllPointsAndLocations() {
// Initialize the service proxy.
if (getAllLocationsService == null) {
getAllLocationsService = GWT.create(GetLocationsService.class);
}
// Set up the callback object.
AsyncCallback<CabbiePoint[]> callback = new AsyncCallback<CabbiePoint[]>() {
public void onFailure(Throwable caught) {
System.out.println(caught.getMessage());
}
public void onSuccess(CabbiePoint[] result) {
//allPointsAndPlaces = result;
System.out.println(result.length);
allPointsAndPlaces = result;
loadAppPages();
}
};
// Make the call to the service.
getAllLocationsService.getLocations(callback);
}
void loadNewPoint(){
int r = Random.nextInt(allPointsAndPlaces.length);
quiz.CurrentPlace = allPointsAndPlaces[r].getPlaceName();
quiz.CurrentLocation = allPointsAndPlaces[r].getPlaceLocation();
quiz.point.setText(quiz.CurrentPlace);
quiz.location.setText(quiz.CurrentLocation);
quiz.location.setStyleName("invisibleText");
}
}
Child class:
public class PointsQuiz extends CabbieApp{
VerticalPanel mainPanel = new VerticalPanel();
HorizontalPanel navigation = new HorizontalPanel();
TextBox point = new TextBox();
TextBox location = new TextBox();
Button showLocation = new Button("Show Location");
Button nextPoint = new Button("Next Point");
String CurrentPlace, CurrentLocation;
public PointsQuiz() {
// Assemble Add Stock panel.
navigation.add(showLocation);
navigation.add(nextPoint);
navigation.setCellHorizontalAlignment(nextPoint, HasHorizontalAlignment.ALIGN_RIGHT);
navigation.addStyleName("addPanel");
mainPanel.setSpacing(5);
mainPanel.setStyleName("body");
mainPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
mainPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
// Assemble Main panel.
mainPanel.add(point);
point.setWidth("200px");
mainPanel.add(location);
location.setWidth("200px");
mainPanel.add(navigation);
navigation.setWidth("200px");
// Move cursor focus to the input box.
showLocation.setFocus(true);
// Listen for mouse events on the show location button.
showLocation.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
showCurrentLocation();}
});
// Listen for mouse events on the next point button.
nextPoint.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
loadNewPoint();
}
});
}
private void showCurrentLocation(){
location.setStyleName("visibleText");
}
public VerticalPanel getMainPanel() {
return mainPanel;
}
}

I managed to find a solution to this problem with Bhumika's help.
To make this work I had to change CabbiePoint[] allPointsAndPlaces to static.
This would solve the reference problem one way - from child to parent.
Also I managed to find out trough debugging, that this reference
quiz = new PointsQuiz();
is also null on a second run of loadNewPoint(). So this child reference (PointsQuiz quiz;) and any other references to children were set also to static.

You are getting null pointer error because of allPointsAndPlaces is null. As per your coding The value of allPointsAndPlaces is assigned after completion of RPC call in getAllPointsAndLocations() method. so the allPointsAndPlaces has some assigned values.
Here you try to directly access loadNewPoint() method in child class. At a time, allPointsAndPlaces is not assigned.

Related

Access row data in DoubleCLickListener of TableViewer

I need to show some information related to the row or cell being clicked in table of TableViewer.
As far as I understand I can use (TableViewer) event.getViewer() in viewer.addDoubleClickListener() to retrieve data of current row or cell being clicked. Correct me if I am wrong.
But my run() function is in private void makeActions() where I can't access event. How can I overcome this problem?
private void hookDoubleClickAction()
{
viewer.addDoubleClickListener(new IDoubleClickListener()
{
public void doubleClick(DoubleClickEvent event)
{
//TableViewer chek = (TableViewer) event.getViewer();
doubleClickAction.run();
}
});
}
private void makeActions()
{
doubleClickAction = new Action()
{
public void run()
{
}
}
}
Keep a reference to the TableViewer as a field in your main class (or pass it as a parameter to the action constructor). You can then get the current selection from the viewer in your action using:
IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();

How can I observe the changed state of model items in an ObservableList?

I have an ObservableList of model items. The model item is enabled for property binding (the setter fires a property changed event). The list is the content provider to a TableViewer which allows cell editing. I also intend to add a way of adding new rows (model items) via the TableViewer so the number of items in the list may vary with time.
So far, so good.
As this is all within an eclipse editor, I would like to know when the model gets changed. I just need one changed event from any changed model item in order to set the editor 'dirty'. I guess I could attach some kind of listener to each individual list item object but I wonder if there is a clever way to do it.
I think that I might have a solution. The following class is an inline Text editor. Changes to the model bean (all instances) are picked up using the listener added in doCreateElementObservable. My eclipse editor just needs to add its' own change listener to be kept informed.
public class InlineEditingSupport extends ObservableValueEditingSupport
{
private CellEditor cellEditor;
private String property;
private DataBindingContext dbc;
IChangeListener changeListener = new IChangeListener()
{
#Override
public void handleChange(ChangeEvent event)
{
for (ITableEditorChangeListener listener : listenersChange)
{
listener.changed();
}
}
};
public InlineEditingSupport(ColumnViewer viewer, DataBindingContext dbc, String property)
{
super(viewer, dbc);
cellEditor = new TextCellEditor((Composite) viewer.getControl());
this.property = property;
this.dbc = dbc;
}
protected CellEditor getCellEditor(Object element)
{
return cellEditor;
}
#Override
protected IObservableValue doCreateCellEditorObservable(CellEditor cellEditor)
{
return SWTObservables.observeText(cellEditor.getControl(), SWT.Modify);
}
#Override
protected IObservableValue doCreateElementObservable(Object element, ViewerCell cell)
{
IObservableValue value = BeansObservables.observeValue(element, property);
value.addChangeListener(changeListener); // ADD THIS LINE TO GET CHANGE EVENTS
return value;
}
private List<ITableEditorChangeListener> listenersChange = new ArrayList<ITableEditorChangeListener>();
public void addChangeListener(ITableEditorChangeListener listener)
{
listenersChange.remove(listener);
listenersChange.add(listener);
}
public void removeChangeListener(ITableEditorChangeListener listener)
{
listenersChange.remove(listener);
}
}

GWT is making an unexpected event call

My code is below: I am seeing that on running the app the loadWidget method gets invoked even when the adminLink is not clicked. This is not want I want, but I'm not sure what is causing the issue. Please advise
public class LoginModule implements EntryPoint {
LoginPopup loginPopup;
private class LoginPopup extends PopupPanel {
public LoginPopup() {
super(true);
}
public void loadWidget(){
System.out.println("I am called 1");
CommonUi cUi = new CommonUi();
//#342 moved code to common area
FormPanel loginForm = cUi.getLoginFormUi();
setWidget(loginForm);
}
}
#Override
public void onModuleLoad() {
//#251 improved login popup ui.
final Anchor adminLink = new Anchor("User Login");
// final Label adminLink = new Label("User Login");
adminLink.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
// Instantiate the popup and show it.
loginPopup = new LoginPopup();
loginPopup.loadWidget();
loginPopup.showRelativeTo(adminLink);
loginPopup.show();
}
});
if(RootPanel.get("admin") !=null)
RootPanel.get("admin").add(adminLink);
}
}
Running Dev Mode, set a breakpoint in that method in your Java IDE, and take a look at the current stack, what code is calling that method. If that is the only code in your app, then this only appears to be invokable from that onClick handlers, so it is a matter of figuring out why that is being invoked.

setSelectionProvider over two different controls not working

I am Trying to create Eclipse Plugin which has a composite with two TreeViewer side by side. On click of each TreeViewer content Eclipse property view should give appropriate information. Now I wanted to set Selection provider for both of this treeviewer hence I used
setSelectionProvider(treeViewer1)
setSelectionProvider(treeviewer2)
But only the second added treeviewer get set since the first one is overwritten. I am intiating this two treeviewer from class Queue.java. Hence I implemented the interface ISelectionProvider over Queue.java as below:
public void addSelectionChangedListener(ISelectionChangedListener listener)
{
selectionChangedListeners.add(listener);
}
public void
removeSelectionChangedListener(ISelectionChangedListener listener)
{
selectionChangedListeners.remove(listener);
}
private void fireSelectionChanged(final SelectionChangedEvent event)
{
Object[] listeners = selectionChangedListeners.getListeners();
for (int i = 0; i < listeners.length; ++i)
{
final ISelectionChangedListener l =
(ISelectionChangedListener) listeners[i];
Platform.run(new SafeRunnable()
{
public void run()
{
l.selectionChanged(event);
}
#Override
public void handleException(Throwable e)
{
removeSelectionChangedListener(l);
}
});
}
}
public void setSelection(ISelection selection)
{
fireSelectionChanged(new SelectionChangedEvent(this, selection));
}
public ISelection getSelection()
{
ArrayList<Object> list = new ArrayList<Object>();
Object o = getProperties();
if (o instanceof IPropertySource)
list.add(o);
return new StructuredSelection(list);
}
Can anyone help me how to resolve this issue. I will be grateful. thanks in advance. Tor.
Your view would have to write a selection provider wrapper or mediator that would delegate to the viewer that currently had focus. Then your view would set it up something like this:
SelectionProviderWrapper wrapper = new SelectionProviderWrapper();
wrapper.addViewer(treeViewer1);
wrapper.addViewer(treeViewer2);
getSite().setSelectionProvider(wrapper);
I would check out org.eclipse.jdt.internal.ui.viewsupport.SelectionProviderMediator for an example of a selection provider for multiple JFace viewers.

GWT - How to associate a business object to a widget

I'd like a way to easily tie a widget back to the business object it is rendering. So when the user interacts with a widget I can easily determine the business object holding the data for that widget.
For example, if we imagine a calendar widget that we're going to implement with an AbsolutePanel. For each appt object we'll add a label to the calendar. Then when a user clicks on a label he can update the appt. So I need to know which appt object that label refers to.
For instance, if we look at the following code; if the label for an appointment receives a click, how can I find out to which appt it represented ? The only solution I can see is to create a ApptLabel sub-class for Label which would hold a reference to its appt. This is fine, but the example illustrates a more general need which is to associate widgets with data objects; however this would mean that every object that has a presence in a view needs to subclass a widget. that seems heavy - I expected to find something in the framework e.g. a string property in a widget that I can set to an object key
other approaches I tried; maintaining a map of Map -- this didnt work as the label object I create doesnt appear to be the same (in terms of the Object.equals which I guess is what HashMap uses)
class WidgetCalendar extends Composite {
AbsolutePanel m_panel = new AbsolutePanel();
m_panel.setStylePrimaryName("calendar");
m_panel.setPixelSize(width, height);
public WidgetCalendar(ArrayList<BomAppt> appts) {
initWidget(m_panel);
for (BomAppt a : appts) {
Label l = new Label();
l.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
// how do I know my BomAppt in here ?
}
m_panel.add(l, someX, someY);
}
}
}
Ideally I can do something like this
class WidgetCalendar extends Composite {
AbsolutePanel m_panel = new AbsolutePanel();
m_panel.setStylePrimaryName("calendar");
m_panel.setPixelSize(width, height);
public WidgetCalendar(ArrayList<BomAppt> appts) {
initWidget(m_panel);
for (BomAppt a : appts) {
Label l = new Label();
l.setItemData(a.getUniqueId());
l.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
BomAppt a = BomAppt.getApptWithId(e.getItemData())
}
}
m_panel.add(l, someX, someY);
}
}
}
This is the solution where I create a subclass, this seems heavy to me and I'd prefer something simpler
class ApptLabel extends Label {
public ApptLabel(BomAppt a) {
m_a = a;
this.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
m_a.doSomething();
});
}
BomAppt m_a;
}
class WidgetCalendar extends Composite {
AbsolutePanel m_panel = new AbsolutePanel();
m_panel.setStylePrimaryName("calendar");
m_panel.setPixelSize(width, height);
public WidgetCalendar(ArrayList<BomAppt> appts) {
initWidget(m_panel);
for (BomAppt a : appts) {
BomLabel l = new BomLabel();
l.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
// how do I know my BomAppt in here ?
}
m_panel.add(l, someX, someY);
}
}
}
For instance, if we look at the following code; if the label for an
appointment receives a click, how can I find out to which appt it
represented ?
By using Composite pattern you can find out which widget was clicked, initially you should create your own custom Appointment widget which is responsible for drawing one appointment. And in you Appointment widget you can have a set of other widgets, in your case, for Label add click handler. Once user clicks that label, you can execute business logic with its data and you can represent data.
public class Appointment extends Composite {
private AppointmentDetails data;
public Appointment(AppointmentDetails data){
draw(data);
}
private void draw(AppointmentDetails data){
Label label = new Label();
label.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
// do your business logic with this AppointmentDetails
}
});
}
}
After that you should have one Calendar widget which contains several Appointments.
Keep in your mind: your classes each serve a single, very clearly defined purpose, separated from other classes with other clearly defined purposes.