Tomcat shows blank page - GWT devmode works fine - java

I am developing a GWT project on eclipse, and when I run the Development Mode everything works fine. But when I deploy the WAR file (generated following this guide click) on my tomcat server, http://localhost:8080/myproj/ shows only a blank page.
I tried to add Window.alert("..") as first line in onModuleLoad() method and it DOES show correctly.
Clearing browser-cache was useless.
Server startup executes without problems nor exceptions.
What should I do to solve this problem?
This is my entry point class
public class Segnalazioni_Degrado implements EntryPoint {
protected static List<Macrocategoria> listaMacrocategorie;
protected static List<Segnalazione> segnalazioniAttiveCached = new ArrayList<Segnalazione>();
protected static List<SegnalazioneRisolta> segnalazioniRisolteCached = new ArrayList<SegnalazioneRisolta>();
protected static final DataLayerServiceAsync dataLayerService = GWT
.create(DataLayerService.class);
protected static final LoginServiceAsync loginService = GWT
.create(LoginService.class);
protected static final MailServiceAsync mailService = GWT
.create(MailService.class);
protected static Properties props;
private final String TITOLO = "PORTALE SEGNALAZIONI DEGRADO";
private LatLng romaLatLng;
private DockLayoutPanel mainPnl;
private HorizontalPanel northPnl;
private HorizontalPanel southPnl;
private VerticalPanel westPnl;
private AbsolutePanel centerPnl;
protected static StatsPanel statsPnl;
protected static MenuPanel menuPnl;
protected static LoginPanel loginPnl;
protected static LegendPanel legendPnl;
protected static MapWidget map;
private Label titoloLbl;
private/* Button */FocusWidget areaRiservataBtn;
private Button followUsOnTwitterBtn;
private HTML mailto;
/**
* TODO tweet segnalazione inserita o risolta, porta su .css tutto il
* possibile, prendi tutto da config, fai log su server, crea mail, leggenda
* icone, elimina file foto non solo link
*/
public void onModuleLoad() {
loadProps();
buildUI();
}
void loadProps() {
props.set("scarsa manutenzione manto stradale", "images/red.png");
props.set("veicolo abbandonato", "images/red.png");
props.set("discarica abusiva", "images/green.png");
props.set("accumulo spazzatura", "images/green.png");
}
void buildUI() {
Maps.loadMapsApi("", "2", false, new Runnable() {
public void run() {
buildHomePage();
}
});
}
private void buildHomePage() {
mainPnl = new DockLayoutPanel(Unit.PCT);
mainPnl.setStyleName("mainPanel");
northPnl = new HorizontalPanel();
northPnl.setStyleName("northPanel");
southPnl = new HorizontalPanel();
southPnl.setStyleName("southPanel");
westPnl = new VerticalPanel();
westPnl.setStyleName("westPanel");
centerPnl = new AbsolutePanel();
centerPnl.setStyleName("centerPnl");
loginPnl = new LoginPanel();
statsPnl = new StatsPanel();
menuPnl = new MenuPanel();
Segnalazioni_Degrado.dataLayerService
.getListaMacrocategorie(new AsyncCallback<List<Macrocategoria>>() {
#Override
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
#Override
public void onSuccess(List<Macrocategoria> result) {
Segnalazioni_Degrado.listaMacrocategorie = result;
centerPnl.add(new LegendPanel());
}
});
/**
* costruisco la Google Map
*/
Size mapSize = Size.newInstance(500, 500);
MapOptions mapOpts = MapOptions.newInstance();
mapOpts.setSize(mapSize);
romaLatLng = LatLng.newInstance(41.8902624, 12.4923096);
map = new MapWidget(romaLatLng, 12, mapOpts);
map.checkResizeAndCenter();
map.setSize("99%", "99%");
map.addControl(new LargeMapControl());
map.setDoubleClickZoom(true);
map.setScrollWheelZoomEnabled(true);
map.setStyleName("map");
/**
* costruisco il titolo del portale
*/
titoloLbl = new Label(TITOLO);
titoloLbl.setStyleName("titolo");
/**
* costruisco bottone per accedere ad area riservata
*/
/* areaRiservataBtn = new Button("Accedi all'area riservata"); */
areaRiservataBtn = new Button("AREA RISERVATA");
areaRiservataBtn.setStyleName("bottomBtn");
areaRiservataBtn.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
new AreaRiservataDialog();
}
});
/**
* costruisco bottone twitter
*/
followUsOnTwitterBtn = new Button();
followUsOnTwitterBtn.addStyleName("bottomBtn");
followUsOnTwitterBtn.addStyleName("twitter");
followUsOnTwitterBtn
.getElement()
.appendChild(
new HTML(
"<div><img src=images/twitter.gif><b>segui #stop_degrado</b></div>")
.getElement());
followUsOnTwitterBtn.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
Window.open("https://twitter.com/stop_degrado", "_blank", "");
}
});
/**
* costruisco bottone mailto
*/
mailto = new HTML("<a href=mailto:dummy#fake.foo> Contattaci </a>");
mailto.setStyleName("bottomBtn");
/**
* creo bottone ABOUT US
*/
Button aboutus = new Button("ABOUT US");
aboutus.setStyleName("bottomBtn");
aboutus.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
new AboutUsPopup();
}
});
northPnl.add(titoloLbl);
northPnl.add(loginPnl);
westPnl.add(menuPnl);
westPnl.add(statsPnl);
southPnl.add(followUsOnTwitterBtn);
southPnl.add(aboutus);
southPnl.add(areaRiservataBtn);
southPnl.add(mailto);
centerPnl.add(map);
mainPnl.addNorth(northPnl, 8);
mainPnl.addWest(westPnl, 30);
mainPnl.addSouth(southPnl, 3.5);
mainPnl.add(centerPnl);
RootLayoutPanel.get().add(mainPnl);
MenuPanel.refreshBtn.click();
}
}

I think it is a NullPointer:
protected static Properties props; // << NULL
public void onModuleLoad() {
loadProps(); // props is still NULL
buildUI();
}
void loadProps() {
// props is still NULL
props.set("scarsa manutenzione manto stradale", "images/red.png"); // BANG!
[...]
By the way:
Why did you make props static? There is only one instance of you EntryPoint. So no state can be shared.

Related

Hide UI component in sub-view

I am trying to find the best way to hide a UI component in a specific sub View but let it be visible in others.
This is the code of my UI class:
public class DCSAdminUI extends UI {
private static final long serialVersionUID = 1L;
VerticalLayout root = new VerticalLayout();
CssLayout content = new CssLayout();
private MenuBar nav = new MenuBar();
private MenuBar userNav = new MenuBar();
private Navigator navigator;
public static final String PERSISTENCE_UNIT = "mystery";
public static DCSAdminUI getCurrent() {
return (DCSAdminUI) UI.getCurrent();
}
public static DCSAdminUI getApplication() {
return (DCSAdminUI) getApplication();
}
#Override
protected void init(VaadinRequest request) {
Page.getCurrent().setTitle("Admin");
initLayout();
initNav();
initUserNav();
getUserOrg();
navigator = new Navigator(this, content);
LoginUI loginView = new LoginUI();
navigator.addView("", loginView);
navigator.addView(ActivitiesUI.VIEW_NAME.toLowerCase(), new ActivitiesUI());
navigator.addView(BookingsUI.VIEW_NAME.toLowerCase(), new BookingsUI());
navigator.addView(OperatorsUI.VIEW_NAME.toLowerCase(), new OperatorsUI());
navigator.addView(TeamUI.VIEW_NAME.toLowerCase(), new TeamUI());
navigator.addView(OrganisationsUI.VIEW_NAME.toLowerCase(), new OrganisationsUI());
navigator.addView(PlayersUI.VIEW_NAME.toLowerCase(), new PlayersUI());
navigator.addViewChangeListener(new ViewChangeListener() {
private static final long serialVersionUID = 1L;
#Override
public boolean beforeViewChange(ViewChangeEvent event) {
return true;
}
#Override
public void afterViewChange(ViewChangeEvent event) {
if (event.getViewName() == null || event.getViewName().equals("")) {
updateNavSelection("activities");
} else {
updateNavSelection(event.getViewName());
}
}
});
}
private void initLayout() {
root.setSizeFull();
setContent(root);
HorizontalLayout topbar = new HorizontalLayout();
topbar.addStyleName("topbar");
topbar.setWidth("100%");
topbar.setSpacing(true);
root.addComponent(topbar);
content.setSizeFull();
root.addComponent(content);
root.setExpandRatio(content, 1);
nav.addStyleName("nav");
topbar.addComponent(nav);
userNav.addStyleName("user-nav");
topbar.addComponent(userNav);
topbar.setComponentAlignment(userNav, Alignment.TOP_CENTER);
}
private void initNav() {
nav.addItem(ActivitiesUI.VIEW_NAME.toUpperCase(Locale.GERMANY), navCommand).setCheckable(true);
nav.addItem(BookingsUI.VIEW_NAME.toUpperCase(Locale.GERMANY), navCommand).setCheckable(true);
nav.addItem(PlayersUI.VIEW_NAME.toUpperCase(Locale.GERMANY), navCommand).setCheckable(true);
nav.addItem(TeamUI.VIEW_NAME.toUpperCase(Locale.GERMANY), navCommand).setCheckable(true);
nav.addItem(OperatorsUI.VIEW_NAME.toUpperCase(Locale.GERMANY), navCommand).setCheckable(true);
nav.addItem(OrganisationsUI.VIEW_NAME.toUpperCase(Locale.GERMANY), navCommand).setCheckable(true);
}
private void initUserNav() {
MenuItem username = userNav.addItem("DCS User", FontAwesome.CHEVRON_DOWN, null);
username.addItem("Edit Profile", null);
username.addItem("Settings", null);
username.addSeparator();
username.addItem("Logout", null);
}
private Command navCommand = new Command() {
private static final long serialVersionUID = 1L;
#Override
public void menuSelected(MenuItem selectedItem) {
updateNavSelection(selectedItem.getText());
navigator.navigateTo(selectedItem.getText().toLowerCase());
}
};
private void updateNavSelection(String selectedItem) {
for (MenuItem item : nav.getItems()) {
item.setChecked(item.getText().toLowerCase()
.equals(selectedItem.toLowerCase()));
}
}
void navigateTo(String menuItem) {
for (MenuItem item : nav.getItems()) {
if (item.getText().toLowerCase().equals(menuItem.toLowerCase())) {
navCommand.menuSelected(item);
return;
}
}
}
}
The UI component in question here is topbar in the initLayout() method which is the app's main MenuBar() but I want this to appear only for authenticated users, meaning that it should be hidden in LoginUI() (the default View class for now). My search efforts have led me to understand that I can use multiple UI classes but that this would eventually become tedious to maintain and that is why I would ideally like to find a way of hiding the topbar component in specific View classes
You can implement a ViewChangeListener in your UI and deal with your navbar in the beforeViewChange. Since this can also reject entering a View you can send anon users to the login too.

Getting a null result on my GWT Project

I'm using Eclipse + GWT to make a call to iTunes API. This is the URI I want to get information:
itunes.apple.com/es/rss/topsongs/limit=25/json
The console isn't throwing me any error, and neither GWT Development Console.
This is the part of the code I think is making ChartSearch null:
(Each Pastebin link is a Java class)
public class ITunesAPI implements EntryPoint {
private Button searchButton = new Button("Search");
private TextBox searchField = new TextBox();
private HorizontalPanel searchPanel = new HorizontalPanel();
private Label statusLabel = new Label();
private final iTunesServiceAsync iTunesService = GWT.create(iTunesService.class);
public void onModuleLoad() {
searchField.setText("PaĆ­s");
searchPanel.add(searchField);
searchPanel.add(searchButton);
searchPanel.add(statusLabel);
// Add panel to the page
RootPanel.get("form").add(searchPanel);
// Focus the cursor on the name field when the app loads
searchField.setFocus(true);
searchField.selectAll();
searchButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
statusLabel.setText("Searching...");
final String pais = searchField.getText();
RootPanel.get("iTunes").clear();
try{
iTunesService.getChart(pais, new AsyncCallback<ChartSearch>(){
public void onSuccess(ChartSearch result) {
statusLabel.setText("Exito");
showChart(pais, result);
}
public void onFailure(Throwable caught) {
statusLabel.setText("Error");
}
});
}catch(Exception e){
statusLabel.setText("Error (try/catch): " + e.getMessage());
}
}
});
}
private void showChart(String pais, ChartSearch result) {
String output="<fieldset>";
output += "<legend>" + pais + " Top 25 Chart</legend>";
if (result != null) {
for (Entry a : result.getFeed().getEntry()) {
output +="<span>" + a.getTitle().getLabel() + "</span><br/>";
}
}else
output="<span>No results</span>";
output +="</fieldset>";
HTML albums = new HTML(output);
RootPanel.get("iTunes").add(albums);
}
public class iTunesServiceImpl extends RemoteServiceServlet implements iTunesService{
String country;
public ChartSearch getChart(String country) {
this.country = country;
ClientResource cr = new ClientResource("https://itunes.apple.com/" + country + "/rss/topsongs/limit=25/json");
ChartSearch message = cr.get(ChartSearch.class);
return message;
}
If you need the rest of the project, or some specific class, tell me, I'll be glad to upload it.
Thanks,

menu items and modal windows are multiplying every time I open them

I've created a vaadin table. When I do right-click it shows context menu with +New... text and when I click on it - it shows modal window with two tables. Every table has the same fuctionality.
The problem is that every time I open and close modal window it adds duplicates for context menu items on modal tables(on the main page it works correct). Moreover - it adds several modal windows when I click on modal table context menu (for example if I open window 5 times - it add 5 context menu items and 5 modal windows for clicked modal context menus)
The only way to return to one item - restart whole application.
What is the problem?
Every my table looks like this
#Component("taskTable")
#Scope("prototype")
public class TaskTable extends AbstractObjectTable {
#Autowired
private TaskService taskService;
#Autowired
private NewTaskWindow taskWindow;
#Autowired
private ShowTaskDetailsWindow detailsWindow;
private Action[] action = new Action[] { new Action("+New...") };
#Override
public Table createTable() {
caption = "Tasks";
headers = new String[] { "Description", "Project", "Status", "Weight", "Developer", "ID" };
this.addActionHandler(new Handler() {
#Override
public Action[] getActions(Object target, Object sender) {
return action;
}
#Override
public void handleAction(Action action, Object sender, Object target) {
switch(action.getCaption()) {
case "+New...": {
PmcUi.getCurrent().addWindow(taskWindow.createWindow());
break;
}
}
//what to do for action
}
});
this.addItemClickListener(new ItemClickListener(){
#Override
public void itemClick(ItemClickEvent event) {
if (event.isDoubleClick()) {
PmcUi.getCurrent().addWindow(detailsWindow.createWindow());
}
return;
}
});
return super.createTable();
}
#Override
protected IndexedContainer projectDatasource() {
IndexedContainer indexedContainer = new IndexedContainer();
for(String header: headers) {
indexedContainer.addContainerProperty(header, String.class, "");
}
List<Task> tasks = taskService.findAllTasks();
for(int i = 0; i < tasks.size(); i++) {
Object id = indexedContainer.addItem();
Task item = tasks.get(i);
indexedContainer.getContainerProperty(id, headers[0]).setValue(item.getDescription());
indexedContainer.getContainerProperty(id, headers[1]).setValue(item.getTaskProject());
indexedContainer.getContainerProperty(id, headers[2]).setValue(item.getStatus());
indexedContainer.getContainerProperty(id, headers[3]).setValue(item.getWeight());
indexedContainer.getContainerProperty(id, headers[4]).setValue(item.getTaskDeveloper());
indexedContainer.getContainerProperty(id, headers[5]).setValue(item.getTaskId());
}
return indexedContainer;
}
}
Where AbstractObjectTable
public abstract class AbstractObjectTable extends Table {
protected String caption;
protected String[] headers = null;
protected Table createTable() {
this.setContainerDataSource(projectDatasource());
this.setVisibleColumns(headers);
this.setSelectable(true);
this.setImmediate(true);
return this;
}
protected abstract IndexedContainer projectDatasource();
}
My +New... modal windows looks similar to that
#Component("newTaskWindow")
public class NewTaskWindow {
private Window createTaskWindow;
#Autowired
private TaskService taskService;
public Window createWindow() {
createTaskWindow = new Window("New Task");
initWindow();
fillWindow();
return createTaskWindow;
}
private void initWindow() {
createTaskWindow.setSizeUndefined();
createTaskWindow.setResizable(false);
createTaskWindow.setModal(true);
createTaskWindow.addCloseListener(new CloseListener() {
#Override
public void windowClose(CloseEvent e) {
Notification.show("Closed");
}
});
}
private void fillWindow() {
final TextField taskDescription = new TextField("Description");
final ComboBox taskProject = new ComboBox("Select project");
final ComboBox taskDeveloper = new ComboBox("Select developer");
final TextField taskWeight = new TextField("Task weight");
final TextField taskStatus = new TextField("Task status");
Button create = new Button("Create");
create.addClickListener(new Button.ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
Task task = new Task();
task.setTaskId(UUID.randomUUID().toString());
task.setStatus(taskStatus.getValue());
task.setTaskDeveloper(taskDeveloper.getValue().toString());
task.setTaskProject(taskProject.getValue().toString());
task.setWeight(taskWeight.getValue());
task.setDescription(taskDescription.getValue());
taskService.insertTask(task);
createTaskWindow.close();
}
});
Button close = new Button("Cancel");
close.addClickListener(new Button.ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
createTaskWindow.close();
}
});
HorizontalLayout layout = new HorizontalLayout(create, close);
FormLayout formLayout = new FormLayout(taskProject, taskDeveloper, taskWeight, taskStatus,
taskDescription, layout);
formLayout.setMargin(true);
createTaskWindow.setContent(formLayout);
}
}
And my details windows also have similar architecture.
#Component("showTaskDetailsWindow")
public class ShowTaskDetailsWindow {
private Window showDetailsWindow;
#Autowired
private TaskService taskService;
public Window createWindow() {
showDetailsWindow = new Window("Show details");
initWindow();
fillWindow();
return showDetailsWindow;
}
private void initWindow() {
showDetailsWindow.setSizeUndefined();
showDetailsWindow.setResizable(false);
showDetailsWindow.setModal(true);
showDetailsWindow.addCloseListener(new CloseListener() {
#Override
public void windowClose(CloseEvent e) {
Notification.show("Closed");
}
});
}
private void fillWindow() {
final TextField taskDescription = new TextField("Description");
final TextField taskProject = new TextField("Task project");
final TextField taskDeveloper = new TextField("Task developer");
final TextField taskWeight = new TextField("Task weight");
final TextField taskStatus = new TextField("Task status");
FormLayout formLayout = new FormLayout(taskProject, taskDeveloper, taskWeight, taskStatus, taskDescription);
formLayout.setMargin(true);
showDetailsWindow.setContent(formLayout);
}
}
What is the problem? Why it is continuously multiplying?
The problem is your getActions implementation
#Override
public Action[] getActions(Object target, Object sender) {
return new Action[] { new Action("+New...")};
}
You should create one instance of the "new Action("+New...")" item and store it for example in the TaskTable object.
The getActions(..) should alsways return the same instance.
If you always create a new action, it just adds them to the already existing actions.
Looks like the createTable() method of the TaskTable class is called too many times but the provided code doesn't show where that method is called. That causes that multiple action handlers and item click listeners are added to a table.

GWT - Get button's "addClickHandler" from a Widget

first of all Im working on a time tracking page with login authentication using ldap.
For the login I created a dialogbox setting verticalpanel as its widget. My verticalpanel contains two textboxes to enter username/password and one button to send data to the ldap server.
On module load the dialogbox pops up and gets the time tracking content on login success.
To my question:
"LoginWidget" and "LoginClickHandler" have separated classes, hence I need to get the login button on module load to add "LoginClickHandler".
What is the best way to handle this? - since I know that my solution isnt that good.
LoginWidget class
public class LoginWidget{
private Button loginButton;
private DialogBox dialogBox;
private TextBox tbxUser;
private PasswordTextBox tbxPw;
private Label lblUser;
private Label lblPW;
private Label lblError;
public LoginWidget(){
dialogBox = new DialogBox();
tbxUser = new TextBox();
tbxPw = new PasswordTextBox();
lblUser = new Label();
lblPW = new Label();
lblError = new Label();
dialogBox.setText("Login");
dialogBox.setAnimationEnabled(true);
loginButton = new Button("Login");
// set the id of a widget by accessing its Element
loginButton.getElement().setId("closeButton");
final HTML serverResponseLabel = new HTML();
VerticalPanel dialogVPanel = new VerticalPanel();
dialogVPanel.addStyleName("dialogVPanel");
dialogVPanel.add(lblUser);
lblUser.setText("User:");
dialogVPanel.add(tbxUser);
dialogVPanel.add(lblPW);
lblPW.setText("PW:");
dialogVPanel.add(tbxPw);
dialogVPanel.add(lblError);
dialogVPanel.add(serverResponseLabel);
dialogVPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
dialogVPanel.add(loginButton);
dialogBox.setWidget(dialogVPanel);
dialogBox.show();
dialogBox.center();
}
public Button getLoginButton(){
return loginButton;
}
public DialogBox getDialogBox(){
return dialogBox;
}
public TextBox getTbxUser(){
return tbxUser;
}
public TextBox getTbxPw(){
return tbxPw;
}
public Label getLblError(){
return lblError;
}
}
LoginClickHandler class
public class LoginClickHandler implements ClickHandler {
/**
*/
private LoginWidget lw;
private ServiceImplURL serviceImplURL;
private TimeTracking dtt = new TimeTracking();
public LoginClickHandler(ServiceImplURL sIU, LoginWidget _lw){
/**
*/
this.lw = _lw;
this.serviceImplURL = sIU;
}
public void onClick(ClickEvent event) {
/**
*/
serviceImplURL.getRpcLdap().authenticate(lw.getTbxPw().getText(), lw.getTbxUser().getText(), new AsyncCallback<Boolean>() {
/**
*/
#Override
public void onSuccess(Boolean isLdapAuthOk) {
/**
*/
if(isLdapAuthOk){
lw.getDialogBox().hide();
User user = new User(lw.getTbxUser().getText(), lw.getTbxPw().getText());
serviceImplURL.getRpcSession().setUsername(user.getUsername(), new AsyncCallback<Void>() {
#Override
public void onFailure(Throwable caught) {
// TODO Auto-generated method stub
}
#Override
public void onSuccess(Void result) {
// TODO Auto-generated method stub
}
});
serviceImplURL.getRpcDB().insertUser(user.getUsername(), new AsyncCallback<Void>() {
/**
*/
#Override
public void onFailure(Throwable caught) {
/*
* connection error to implement
*/
}
#Override
public void onSuccess(Void result) {
/*
* do nothing
*/
}
});
dtt.loadContent();
}
else{
lw.getLblError().setStyleName("error");
lw.getLblError().setText("Passwort oder Username falsch!");
}
}
#Override
public void onFailure(Throwable caught) {
// TODO Auto-generated method stub
}
});
}
}
My Entrypoint
#Override
public void onModuleLoad() {
/**
*/
loadLoginWidget();
}
/**
* Creates the login pop up.
*/
public void loadLoginWidget(){
/**
*/
LoginWidget lw = new LoginWidget();
LoginClickHandler lch = new LoginClickHandler(serviceImplURL, lw);
lw.getLoginButton().addClickHandler(lch);
}
I already tried to extend Button but I dont think its a difference.
Pass a listener class (eg. your LoginClickHandler) to the view constructor:
public LoginWidget( LoginClickHandler listener )
{
...
loginButton.addClickHandler( listener )
...
}
More generally you may want to interject an interface defining the actions and have LoginClickHandler implement it:
public interface LoginListener
{
void onLogin();
...
}
public class LoginWidget
{
public LoginWidget( LoginListener listener )
{
this.listener = listener;
Button loginButton = new Button( "Login" );
loginButton.addClickHandler( new ClickHandler()
{
public void onClick( ClickEvent event ) { listener.onLogin(); }
} );
}
...
}
and finally
public class LoginClickHandler implements LoginListener
{
#Override public void onLogin()
{
serviceImplURL.getRpcLdap()...
...
}
}
and
public void loadLoginWidget()
{
LoginWidget lw = new LoginWidget( new LoginClickHandler() );
...
}
Cheers,

Updating label of a ButtonField from PopupScreen

I have a ButtonField on MainScreen, from which I am pushing a PopupScreen where I have added an ObjectListfield. What I want to do is to update the label of ButtonField on MainScreen with the element selected from ObjectListfield of PopupScreen.
Please tell me if it is possible to do without using Dialog class (I really want to use PopupScreen and not Dialog class) and the method by which this can be done. I'd appreciate if some sample code will be provided.
I have added my code.
public final class MyScreen extends MainScreen {
HorizontalFieldManager hfm;
ButtonField btn;
public MyScreen() {
// Set the displayed title of the screen
super();
setTitle("MyTitle");
btn = new ButtonField("label",ButtonField.CONSUME_CLICK);
final mypopup mps = new mypopup();
btn.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field,int context) {
UiApplication.getUiApplication().pushModalScreen(mps);
}
});
hfm = new HorizontalFieldManager();
hfm.add(btn);
add(hfm);
}
public void setlabel(String labelnew) {
btn.setLabel(labelnew);
}
public String getlabel() {
return this.btn.getLabel();
}
}
class mypopup extends PopupScreen implements FieldChangeListener {
String it;
ObjectListField obj = new ObjectListField() {
public boolean navigationClick(int status,int time) {
int selectedindex=obj.getSelectedIndex();
it=(String)obj.get(obj, selectedindex);
UiApplication.getUiApplication().popScreen(UiApplication.getUiApplication().getActiveScreen());
/*MyScreen my=new MyScreen();
my.btn.setLabel(it);
my.invalidate(); */
//close();
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
/* This im doing to see that setlabel and getlabel are
working properly */
MyScreen my=new MyScreen();
my.setlabel(it);
String gt=my.getlabel();
Dialog.alert(gt);
my.hfm.invalidate();
//the label of button is changed but not updating in mainscreen.
}
});
return true;
}
};
public mypopup() {
super(new VerticalFieldManager());
String[] type=new String[] {"a","b","c","d"};
obj.set(type);
add(obj);
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
}
}
You need to change following block of code,
MyScreen my = new MyScreen();
my.setlabel(it);
String gt = my.getlabel();
Dialog.alert(gt);
my.hfm.invalidate();
With the code block,
Screen scr = UiApplication.getUiApplication().getActiveScreen();
if (scr instanceof MyScreen) {
MyScreen my = (MyScreen) scr;
my.setlabel(it);
my.invalidate();
}
Add the button in one Manager either HorizontalFieldManager or VerticalFieldManager and after setting text on button invalidate the managerlike this way
public final class MyScreen extends MainScreen
{
ButtonField btn;
public MyScreen()
{
// Set the displayed title of the screen
super();
setTitle("MyTitle");
btn=new ButtonField("label",ButtonField.CONSUME_CLICK);
final mypopup mps=new mypopup();
btn.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field,int context){
UiApplication.getUiApplication().pushModalScreen(mps);
}
});
HorizontalFieldManager hfmToholdButtons = new HorizontalFieldManager();
btn.setLabel(mps.gettext());
hfmToholdButtons.add(btn);
hfmToholdButtons.invalidate();
}
}

Categories