This is my save button button code of my database.
btnsave.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
pd.setFname(et1.getText().toString());
pd.setLname(et2.getText().toString());
pd.setPhone(et3.getText().toString());
pd.setRelation(spinner1.getSelectedItem().toString());
int spinner_pos=spinner1.getSelectedItemPosition();
String[]relation=getResources().getStringArray(R.array.addrelation);
String mg = he.save(pd);
m.setText(mg);
}
});
It is only saving the first spinner value in every record.
the fast way is to use a loop inside setOnclickListner (there can be some better to do this):
btnsave.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
int nSpinnerItemsCount = spinner1.getCount();
for(int nCounter = 0; nCounter < nSpinnerItemsCount; nCounter ++)
{
pd.setFname(et1.getText().toString());
pd.setLname(et2.getText().toString());
pd.setPhone(et3.getText().toString());
pd.setRelation(spinner1.getItemAtPosition(nCounter).toString());
String mg = he.save(pd);
m.setText(mg);
}
});
spinner1.getItemAtPosition(nCounter).toString() is the key. on your code your use
int spinner_pos=spinner1.getSelectedItemPosition();
By default it always return the index of the first element inside the spinner (if other element is selected).
So by using spinner1.getCount, a loop and getItemAtPosition you have all elements in the spinner and do what you want to do.
Hope that helps.
Related
I need to add items dynamically on click of listbox in Gwt . Which handler do I need to use?
Later I will be able to use addChangeHandler once items are added to listbox.
If i use click handler to add items to listbox, items are added to listbox. But on click of listbox, listbox items are not listed. Listbox closes immediately on click of it.
How to resolve this issue
Here is a simple code to demonstrate how to add items to the ListBox.
You need to understand some things first:
ClickEvent is fired whenever you click on the ListBox: first when you click to show the list and second when you click to select an item;
ChangeEvent is fired when you change the selected item - you can not use it to track the change of item list itself;
public class ListBoxTest implements EntryPoint {
private TextArea log = new TextArea();
private ListBox listBox = new ListBox();
private int i;
#Override
public void onModuleLoad() {
for(int j = 0; j < 5; j++)
listBox.addItem("item " + i++);
listBox.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
log(event.toDebugString());
for(int j = 0; j < 5; j++)
listBox.addItem("item " + i++);
}
});
listBox.addChangeHandler(new ChangeHandler() {
#Override
public void onChange(ChangeEvent event) {
log(event.toDebugString());
}
});
RootPanel.get().add(listBox);
RootPanel.get().add(log);
}
private void log(String text) {
String logText = log.getText();
if(!logText.isEmpty())
logText+= "\n";
logText+= text;
log.setText(logText);
}
}
My MainPresenter has a CellTable with a button column. When u hit a button the presenter calls "addToPopupSlot(editPopup, true)". A editPopup appears with several settings u can make there. After pressing the save button on the popup view it sends data to the database which the CellTable in the MainPresenter wants to get.
My problem is: When I click on the save button, the table doesnt get updated. I have to either refresh the page or navigate from another Presenter back to the MainPresenter.
EditPopupPresenter
#Override
protected void onBind() {
super.onBind();
this.username = Cookies.getCookie("domusr");
// hours and minutes displayed in listboxes
for (int i = 0; i < TimeSettings.HOURS_RANGE; i++) {
getView().getBeginHoursLBX().addItem(String.valueOf(i));
getView().getEndHoursLBX().addItem(String.valueOf(i));
getView().getPauseHoursLBX().addItem(String.valueOf(i));
}
for (int i = 0; i < 60; i += TimeSettings.MINUTES_RANGE) {
getView().getBeginMinutesLBX().addItem(String.valueOf(i));
getView().getEndMinutesLBX().addItem(String.valueOf(i));
getView().getPauseMinutesLBX().addItem(String.valueOf(i));
}
getView().getSaveBTN().addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
DateTimeFormat dtf = DateTimeFormat.getFormat("yyyy-MM-dd");
final String startHours = getView()
.getBeginHoursLBX()
.getValue(
getView().getBeginHoursLBX().getSelectedIndex());
final String startMinutes = getView().getBeginMinutesLBX()
.getValue(
getView().getBeginMinutesLBX()
.getSelectedIndex());
final String endHours = getView().getEndHoursLBX().getValue(
getView().getEndHoursLBX().getSelectedIndex());
final String endMinutes = getView()
.getEndMinutesLBX()
.getValue(
getView().getEndMinutesLBX().getSelectedIndex());
final String pauseHours = getView()
.getPauseHoursLBX()
.getValue(
getView().getPauseHoursLBX().getSelectedIndex());
final String pauseMinutes = getView().getPauseMinutesLBX()
.getValue(
getView().getPauseMinutesLBX()
.getSelectedIndex());
final String projectId = getView().getProjectIdLBL().getText();
final java.sql.Date date = new java.sql.Date(dtf.parse(
getView().getDateLBL().getText()).getTime());
dispatcher.execute(
new InsertTimesIntoDB(Integer.parseInt(startHours),
Integer.parseInt(startMinutes), Integer
.parseInt(endHours), Integer
.parseInt(endMinutes), Integer
.parseInt(pauseHours), Integer
.parseInt(pauseMinutes), Integer
.parseInt(projectId), date, username),
new AsyncCallback<InsertTimesIntoDBResult>() {
#Override
public void onFailure(Throwable caught) {
}
#Override
public void onSuccess(InsertTimesIntoDBResult result) {
}
});
getView().hide();
}
});
}
editColumn in MainPresenter (onBind())
// edit column
Column<Booking, String> editColumn = new Column<Booking, String>(
new ButtonCell()) {
#Override
public String getValue(Booking booking) {
return "edit";
}
};
editColumn.setFieldUpdater(new FieldUpdater<Booking, String>() {
#Override
public void update(int index, Booking object, String value) {
// pop up widget addToSlot call
editPopup.getView().getDateLBL()
.setText(String.valueOf(object.getFullDate()));
editPopup.getView().getProjectIdLBL()
.setText(String.valueOf(1234567));
editPopup.getView().getBeginHoursLBX()
.setItemSelected(object.getStartHours(), true);
editPopup
.getView()
.getBeginMinutesLBX()
.setItemText(
minutesRange.getIndex(object
.getEndMinutes()),
String.valueOf(object.getStartMinutes()));
editPopup.getView().getEndHoursLBX()
.setItemSelected(object.getEndHours(), true);
editPopup
.getView()
.getEndMinutesLBX()
.setItemText(
minutesRange.getIndex(object
.getEndMinutes()),
String.valueOf(object.getEndMinutes()));
editPopup.getView().getPauseHoursLBX()
.setItemSelected(object.getPauseHours(), true);
editPopup
.getView()
.getPauseMinutesLBX()
.setItemText(
minutesRange.getIndex(object
.getEndMinutes()),
String.valueOf(object.getPauseMinutes()));
addToPopupSlot(editPopup, true);
}
});
getView().getTimeTable().addColumn(editColumn);
I think you have some solutions here. If I were you I would do next steps:
Create a listener of events in the MainPresenter.
When you finished
update your DB (after pressing save in your popup); I´d fire an
event.
When the MainPresenter receives the event, you go to the DB
and fetch the data (filtering it using getVisibleRange()).
Refresh the CellTable using setRowData(...) method (passing correctly the arguments)
Other option is create a ListDataProvider associate with the CellTable, and call refresh on it.
I have set up an AsyncDataProvider for my CellTable and added it to a SimplePager. I have hooked up a ListHandler to take care of sorting based on a column.
When I click the header of that column, the data doesn't change but on going to the next/previous page within the pager the data is then sorted. Also before the column is clicked there is no visual indicator on the column that would indicate that it is meant to be sortable.
How can I get the data to update when I click the header of the Column?
Here's my code snippet
service.getHosts(environment, new AsyncCallback<Set<String>>() {
#Override
public void onSuccess(final Set<String> hosts) {
final List<String> hostList = new ArrayList<String>(hosts);
//Populate the table
CellTable<String> hostTable = new CellTable<String>();
TextColumn<String> hostNameColumn = new TextColumn<String>(){
#Override
public String getValue(String string){
return string;
}
};
NumberCell numberCell = new NumberCell();
Column<String, Number> lengthColumn = new Column<String, Number>(numberCell){
#Override
public Number getValue(String string) {
return new Integer(string.length());
}
};
AsyncDataProvider<String> dataProvider = new AsyncDataProvider<String>() {
#Override
protected void onRangeChanged(HasData<String> data) {
int start = data.getVisibleRange().getStart();
int end = start + data.getVisibleRange().getLength();
List<String> subList = hostList.subList(start, end);
updateRowData(start, subList);
}
};
// Hooking up sorting
ListHandler<String> columnSortHandler = new ListHandler<String>(hostList);
columnSortHandler.setComparator(lengthColumn, new Comparator<String>(){
#Override
public int compare(String arg0, String arg1) {
return new Integer(arg0.length()).compareTo(arg1.length());
}
});
hostTable.setPageSize(10);
hostTable.addColumnSortHandler(columnSortHandler);
hostTable.addColumn(hostNameColumn,"Host Name");
lengthColumn.setSortable(true);
hostTable.addColumn(lengthColumn, "Length");
VerticalPanel verticalPanel = new VerticalPanel();
SimplePager pager = new SimplePager();
pager.setDisplay(hostTable);
dataProvider.addDataDisplay(hostTable);
dataProvider.updateRowCount(hosts.size(), true);
verticalPanel.add(hostTable);
verticalPanel.add(pager);
RootPanel.get().add(verticalPanel);
}
#Override
public void onFailure(Throwable throwable) {
Window.alert(throwable.getMessage());
}
});
I'm not sure how to make sure that the list is shared by both the table and the Pager. Before adding the pager I was using
ListDataProvider<String> dataProvider = new ListDataProvider<String>();
ListHandler<String> columnSortHandler = new ListHandler<String>(dataProvider.getList());
The AsyncDataProvider doesn't have the method getList.
To summarize I want the data to be sorted as soon as the column is clicked and not after I move forward/backward with the pager controls.
As per the suggestion I have changed the code for the AsyncDataProvider to
AsyncDataProvider<String> dataProvider = new AsyncDataProvider<String>() {
#Override
protected void onRangeChanged(HasData<String> data) {
int start = data.getVisibleRange().getStart();
int end = start + data.getVisibleRange().getLength();
List<String> subList = hostList.subList(start, end);
// Hooking up sorting
ListHandler<String> columnSortHandler = new ListHandler<String>(hostList);
hostTable.addColumnSortHandler(columnSortHandler);
columnSortHandler.setComparator(lengthColumn, new Comparator<String>(){
#Override
public int compare(String v0, String v1) {
return new Integer(v0.length).compareTo(v1.length);
}
});
updateRowData(start, subList);
}
};
But there is no change in the behavior even after that. Can someone please explain the process. The GWT showcase app seems to have this functionality but how they've done it isn't all that clear.
When using an AsyncDataProvider both pagination and sorting are meant to be done on the server side. You will need an AsyncHandler to go with your AsyncDataProvider:
AsyncHandler columnSortHandler = new AsyncHandler(dataGrid) {
#Override
public void onColumnSort(ColumnSortEvent event) {
#SuppressWarnings("unchecked")
int sortIndex = dataGrid.getColumnIndex((Column<Entry, ?>) event.getColumn());
boolean isAscending = event.isSortAscending();
service.getPage(0, sortIndex, isAscending, new AsyncCallback<List<Entry>>() {
public void onFailure(Throwable caught) {
}
public void onSuccess(List<Entry> result) {
pager.setPage(0);
provider.updateRowData(0, result);
}
});
}
};
dataGrid.addColumnSortHandler(columnSortHandler);
Clicking on a column header will then fire a columnSortEvent. Then you have to get the column clicked. I am overloading my servlet to provide both sorting and pagination, so I pass a -1 for the column index when only pagination is desired.
provider = new AsyncDataProvider<Entry>() {
#Override
protected void onRangeChanged(HasData<Entry> display) {
final int start = display.getVisibleRange().getStart();
service.getPage(start, -1, true, new AsyncCallback<List<Entry>>() {
#Override
public void onFailure(Throwable caught) {
}
#Override
public void onSuccess(List<Entry> result) {
provider.updateRowData(start, result);
}
});
}
};
provider.addDataDisplay(dataGrid);
provider.updateRowCount(0, true);
Then your servlet implementation of getPage performs the sorting and pagination. The whole thing is much easier to follow with separate event handlers.
I think the problem is with the ListHandler initialization. You are passing hostList as a parameter to List Handler and in onRangeChange method you are calling updateRowData with a different list (sublist).
Make sure you use the same list in both the places.
or
Move your ListHander initialization and cellTable.addColumnSortHandler method call to onRangeChange method after updateRowData call.
I am using GWT 2.3.I which I am using GWT cell table.
Here below is the code for my cell table:
public class FormGrid extends SuperGrid {
List<Form> formList;
#Override
public void setColumns(CellTable table) {
TextColumn<Form> nameColumn = new TextColumn<Form>() {
#Override
public String getValue(Form object) {
return object.getName();
}
};
table.addColumn(nameColumn, "Name");
}
#Override
public void setData() {
if (formList != null && formList.size() > 0) {
AsyncDataProvider<Form> provider = new AsyncDataProvider<Form>() {
#Override
protected void onRangeChanged(HasData<Form> display) {
int start = display.getVisibleRange().getStart();
int end = start + display.getVisibleRange().getLength();
end = end >= formList.size() ? formList.size() : end;
List<Form> sub = formList.subList(start, end);
updateRowData(start, sub);
}
};
provider.addDataDisplay(getTable());
provider.updateRowCount(formList.size(), true);
}
}
public List<Form> getFormList() {
return formList;
}
public void setFormList(List<Form> formList) {
this.formList = formList;
}
}
In this my set column and set data will be called fro super class flow.This cell table is working fine.
Now I want to put a filter type facility (like search) in this cell table.It should be like, there is a texbox above the cell table and what ever written in that text box, it should fire a like query to all form name for that text box value.
for example I have 1000 form in the grid.Now if user writes 'app' in some filter textbox above the cell table the all the form which have 'app' in there name will be filtered and grid has only those forms only.
This is the first case:
Another case is I am only render one column in grid name.I have two more properties in form (description,tag).But I am not rendering them.now for filter if user writes 'app' in filter box then it should make a query to all three (name, description, and tag) and should return if 'app' matched to any of three.
I am not getting how to apply filter in cell table.
Please help me out.Thanks in advance.
You can find an implementation in the expenses sample.
Here is a short summary of the steps
1.) Create a Textbox and a SearchButton.
2.) add a clickHandler to the SearchButton (You can also add KeyUpHandler to the Textbox alternatively)
searchButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
search();
}
});
3.) In the search function retrieve the searchString and store it.
private void search() {
searchString = searchBox.getText();
setData();
}
4.) modify your setdata() function to take searchString into account
#Override
public void setData() {
if (formList != null && formList.size() > 0) {
AsyncDataProvider<Form> provider = new AsyncDataProvider<Form>() {
#Override
protected void onRangeChanged(HasData<Form> display) {
int start = display.getVisibleRange().getStart();
int end = start + display.getVisibleRange().getLength();
//new function if searchString is specified take into account
List<Form> sub = getSubList(start,end);
end = end >= sub.size() ? sub.size() : end;
updateRowData(sub.subList(start, end);, sub);
}
};
provider.addDataDisplay(getTable());
provider.updateRowCount(formList.size(), true);
}
}
private List<Form> getSubList(int start, int end) {
List<Form> filtered_list = null;
if (searchString != null) {
filtered_list= new ArrayList<Form>();
for (Form form : formList) {
if (form.getName().equals(searchString) || form.getTag().equals(searchString) || form.getDescription().equals(searchString))
filtered_list.add(form);
}
}
else
filtered_list = formList;
return filtered_list;
}
can propose another solution what can be used quite easy multiple times.
Idea is to create custom provider for your celltable.
GWT celltable filtering
Video in this post shows it in action.
Here is the part of code of custom list data provider which u have to implement.
#Override
protected void updateRowData(HasData display, int start, List values) {
if (!hasFilter() || filter == null) { // we don't need to filter, so call base class
super.updateRowData(display, start, values);
} else {
int end = start + values.size();
Range range = display.getVisibleRange();
int curStart = range.getStart();
int curLength = range.getLength();
int curEnd = curStart + curLength;
if (start == curStart || (curStart < end && curEnd > start)) {
int realStart = curStart < start ? start : curStart;
int realEnd = curEnd > end ? end : curEnd;
int realLength = realEnd - realStart;
List<t> resulted = new ArrayList<t>(realLength);
for (int i = realStart - start; i < realStart - start + realLength; i++) {
if (filter.isValid((T) values.get(i), getFilter())) {
resulted.add((T) values.get(i));
}
}
display.setRowData(realStart, resulted);
display.setRowCount(resulted.size());
}
}
}
My gwt project have flexTable show data of image and button on each row and coll.
But my button won't work properly. this is my current code:
private Button[] b = new Button[]{new Button("a"),...,new Button("j")};
private int z=0;
...
public void UpdateTabelGallery(JsArray str){
for(int i=0; i str.length(); i++){
b[i].setText(str.gettitle());
UpdateTabelGallery(str.get(i));
}
}
public void UpdateTabelGallery(GalleryData str){
Image img = new Image();
img.setUrl(str.getthumburl());
HTML himage= new HTML("a href="+str.geturl()+">"+ img +"/a>" + b[z] );
TabelGaleri.setWidget(y, x, himage);
//is here th right place?
b[z].addClickHandler(new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
Window.alert("I wan to show the clicked button text" + b[z].getText());
}
});
z++;
}
I'm still confuse where I should put my button handler. With this current code seems the clickhandler didn't work inside a looping. And if I put it outside loop its not working because I need to know which button clicked. I need to get my index button.but how? Is there any option than array button?
thanks
I was using this method me too, then I've created a new Button with an additional argument.
When I add the ButtonArg I set also the argument:
Panel.add(new ButtonArg("B1", i));
...
// Create a handler for the A-Z buttons
class MyHandler implements ClickHandler {
public void onClick(ClickEvent e) {
ButtonArg btn=(ButtonArg) e.getSource();
Window.alert("Button Text="+btn.getArgument());
}
}
public class ButtonArg extends Button {
int argument;
public ButtonArg(String html, int arg) {
super(html);
setArgument(arg);
}
public int getArgument() {
return argument;
}
public void setArgument(int argument) {
this.argument = argument;
}
[...]
The problem is that you refer to 'z' in your click handler, but the value of z changes, so that when your click handler is actually called the value of z is wrong.
You need a local final variable in UpdateTabelGallery which you assign the current value of z to to allow it to be captured by the handler you create. Even better, get rid of z entirely and pass i to UpdateTableGallery:
public void updateTableGallery(GalleryData str, final int i){
Image img = new Image();
img.setUrl(str.getthumburl());
HTML himage= new HTML("a href="+str.geturl()+">"+ img +"/a>" + b[i] );
TabelGaleri.setWidget(y, x, himage);
//is here th right place?
b[i].addClickHandler(new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
Window.alert("I wan't to show the clicked button text" + b[i].getText());
}
});
}
But what do you expect:
HTML himage= new HTML("a href="+str.geturl()+">"+ img +"/a>" + b[i] );
to do? Aside from the incorrect HTML syntax, I don't think adding ypur button to the string will work.
I know this is old, but it didn't look answered and I was looking to do the same thing. Here's one solution:
public void onModuleLoad() {
Button[] b=new Button[26];
RootPanel rp=RootPanel.get("body");
// Create a handler for the A-Z buttons
class MyHandler implements ClickHandler {
public void onClick(ClickEvent e) {
Button btn=(Button) e.getSource();
Window.alert("Button Text="+btn.getText());
}
}
MyHandler handler = new MyHandler();
for(int i=0;i<26;i++) {
b[i] = new Button(String.valueOf((char)(65+i)));
b[i].addStyleName("sendButton");
rp.add(b[i]);
b[i].addClickHandler(handler);
}
SimplePanel sPanel = new SimplePanel();
}