smartgwt - listgrid editing by cell having some problem - smartgwt

I made listgid which can be edited by cell.
For testing I added save button. When I click on save button then listgrid's first record(updated first column value on first row) should be appear on pop up, but its not showing updated value on pop up.
For example in this case there is first listgrid record name->jon, i edited jon to shobhit and then click on save button. After clicking on save button I should get name shobhit but its showing jon which is the old value.
Please have a look on below my code and help me to accomplish this interesting task.
public void onModuleLoad() {
VLayout vLayout = new VLayout(10);
final ListGrid listGrid = new ListGrid();
ListGridField nameField = new ListGridField("name","Name");
nameField.setWidth(100);
nameField.setAlign(Alignment.CENTER);
ListGridField ageField = new ListGridField("age","Age");
ageField.setWidth(100);
ageField.setAlign(Alignment.CENTER);
ListGridField locationField = new ListGridField("location","Location");
locationField.setWidth(100);
locationField.setAlign(Alignment.CENTER);
listGrid.setFields(nameField, ageField, locationField);
listGrid.setDataSource(getDS());
listGrid.setWidth(310);
listGrid.setHeight(224);
listGrid.setAutoFetchData(true);
listGrid.setCanEdit(true);
listGrid.setEditEvent(ListGridEditEvent.CLICK);
listGrid.setEditByCell(true);
vLayout.addMember(listGrid);
IButton saveButton = new IButton("Save");
saveButton.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
ListGridRecord[] record = listGrid.getRecords();
Record r = record[0];
SC.say(r.getAttributeAsString("name"));
}
});
vLayout.addMember(saveButton);
RootPanel.get("gwtContent").add(vLayout);
}
private RestDataSource getDS() {
RestDataSource ds = new RestDataSource();
DataSourceTextField nameField=new DataSourceTextField("name", "Name");
DataSourceIntegerField ageField=new DataSourceIntegerField("age", "Age");
DataSourceTextField locationField=new DataSourceTextField("location", "Location");
ds.setFields(nameField, ageField, locationField);
ds.setDataFormat(DSDataFormat.JSON);
OperationBinding fetchOB = new OperationBinding();
fetchOB.setOperationType(DSOperationType.FETCH);
OperationBinding addOB = new OperationBinding();
addOB.setOperationType(DSOperationType.ADD);
addOB.setDataProtocol(DSProtocol.POSTPARAMS);
OperationBinding updateOB = new OperationBinding();
updateOB.setOperationType(DSOperationType.UPDATE);
updateOB.setDataProtocol(DSProtocol.POSTPARAMS);
OperationBinding removeOB = new OperationBinding();
removeOB.setOperationType(DSOperationType.REMOVE);
removeOB.setDataProtocol(DSProtocol.POSTPARAMS);
ds.setOperationBindings(fetchOB, addOB, updateOB, removeOB);
if (!GWT.isScript()){
ds.setFetchDataURL("data/dataIntegration/json/data-fetch.js");
ds.setJsonRecordXPath("response/data");
}else{
}
return ds;
}
JSON data file:
{
response: {
status: 0,
startRow: 0,
endRow: 4,
totalRows: 5,
data: [
{"name":"Jon", "age":40, "location":"USA"},
{"name":"Tom", "age":30, "location":"USA"},
{"name":"Frank", "age":35, "location":"USA"},
{"name":"Deb", "age":24, "location":"USA"},
{"name":"Leroy", "age":70, "location":"USA"}
]
}
}

Use the addRowEditorExitHandler for listgrid.This will not require a save button.
Once you make changes and click any where outside grid, control will automatically come to addRowEditorExitHandler.
ListGrid listGrid = new ListGrid();
listGrid.setCanEdit(true);
listGrid.setAutoSaveEdits(false);
listGrid.setDataSource(getDS());
listGrid.addRowEditorExitHandler(new RowEditorExitHandler() {
#Override
public void onRowEditorExit(final RowEditorExitEvent event) {
SC.say(event.getNewValues().get("name"));
//event.getNewValues gives a map of unsaved edits in edited row
//This values u can put to a new record and save it
}
});

Related

Monotouch.Dialog Generate from db and retain values

I'm have a settings view where I'm using MT.D to build out my UI. I just got it to read elements from a database to populate the elements in a section.
What I don't know how to do is access each elements properties or values. I want to style the element with a different background color for each item based on it's value in the database. I also want to be able to get the selected value so that I can update it in the db. Here's the rendering of the code that does the UI stuff with MT.D. I can get the values to show up and slide out like their supposed to... but, styling or adding delegates to them to handle clicks I'm lost.
List<StyledStringElement> clientTypes = SettingsController.GetClientTypes ();
public SettingsiPhoneView () : base (new RootElement("Home"), true)
{
Root = new RootElement("Settings") {
new Section ("Types") {
new RootElement ("Types") {
new Section ("Client Types") {
from ct in clientTypes
select (Element) ct
}
},
new StringElement ("Other Types")
}
Here's how I handled it below. Basically you have to create the element in a foreach loop and then populate the delegate with whatever you want to do there. Like so:
public static List<StyledStringElement> GetClientTypesAsElement ()
{
List<ClientType> clientTypes = new List<ClientType> ();
List<StyledStringElement> ctStringElements = new List<StyledStringElement> ();
using (var db = new SQLite.SQLiteConnection(Database.db)) {
var query = db.Table<ClientType> ().Where (ct => ct.IsActive == true && ct.Description != "Default");
foreach (ClientType ct in query)
clientTypes.Add (ct);
}
foreach (ClientType ct in clientTypes) {
// Build RGB values from the hex stored in the db (Hex example : #0E40BF)
UIColor bgColor = UIColor.Clear.FromHexString(ct.Color, 1.0f);
var localRef = ct;
StyledStringElement element = new StyledStringElement(ct.Type, delegate {
ClientTypeView.EditClientTypeView(localRef.Type, localRef.ClientTypeId);
});
element.BackgroundColor = bgColor;
ctStringElements.Add (element);
}
return ctStringElements;
}

Insert data in TableModel.addRow into Blackberry TableView

I need to Create a table where 3 columns are needed and can have multiple rows. I am using BlackBerry API version 6. I have debugged my code and it's giving IllegalArgumentException. I am not able to sort this error out.
My code is as follows:
public class designTableLayout extends MainScreen{
TableModel theModel = new TableModel();
theView = new TableView(theModel);
TableController theController = new TableController(theModel, theView,
TableController.FIELD_FOCUS);
theView.setController(theController);
HeaderTemplate theTemplate = new HeaderTemplate(theView, 1, 3);
theTemplate.createRegion(new XYRect(0,0,1,1));
theTemplate.createRegion(new XYRect(1,0,1,1));
theTemplate.createRegion(new XYRect(2,0,1,1));
theTemplate.setRowProperties(0, new TemplateRowProperties(60));
theTemplate.setColumnProperties(0, new TemplateColumnProperties(40));
theTemplate.setColumnProperties(1, new TemplateColumnProperties(40));
theTemplate.setColumnProperties(2, new TemplateColumnProperties(40));
theTemplate.useFixedHeight(true);
theView.setDataTemplate(theTemplate);
theModel.addRow(new String[]{"the","quick","brown"});// problem arises here
theModel.addRow(new String[]{"jumps","over","the"});
theModel.addRow(new String[]{"dog","the","quick"});
add(theView);
}
class HeaderTemplate extends DataTemplate {
LabelField field1 = new LabelField("field1");
LabelField field2 = new LabelField("field2");
LabelField field3 = new LabelField("field3");
public HeaderTemplate(DataView view,int rows,int columns){
super(view, rows, columns);
}
public Field[] getDataFields(int modelRowIndex) {
TableModel theModel = (TableModel) getView().getModel();
//Get the data for the row.
Object[] data = {field1, field2, field3};
data = (Object[]) theModel.getRow(modelRowIndex);
//Create a array to hold all fields.
Field[] theDataFields = new Field[data.length];
theDataFields[0] = new LabelField(field1/*, DrawStyle.ELLIPSIS*/);
theDataFields[1] = new LabelField(field2/*, DrawStyle.ELLIPSIS*/);
theDataFields[2] = new LabelField(field3/*, DrawStyle.ELLIPSIS*/);
return theDataFields;
}
}
I know you probably are using some of this code just to test your table model, but I think your template should look more like this:
class HeaderTemplate extends DataTemplate {
public HeaderTemplate(DataView view,int rows,int columns){
super(view, rows, columns);
}
public Field[] getDataFields(int modelRowIndex) {
TableModel theModel = (TableModel) getView().getModel();
//Get the data for the row.
Object[] data = (Object[]) theModel.getRow(modelRowIndex);
//Create a array to hold all fields.
Field[] theDataFields = new Field[data.length];
theDataFields[0] = new LabelField((String)data[0], DrawStyle.ELLIPSIS);
theDataFields[1] = new LabelField((String)data[1], DrawStyle.ELLIPSIS);
theDataFields[2] = new LabelField((String)data[2], DrawStyle.ELLIPSIS);
return theDataFields;
}
}
And then add your data as an Object[]:
theModel.addRow(new Object[]{"the","quick","brown"});
Here is the BlackBerry example on this

Blackberry: Drawing TableModel focus properly

I need help with drawing the focus of the selected row properly.
Currently if I select the first item of a category the separatorrow gets highlighted too. So how can I implement my custom focus drawing so that only the selected row gets focused/highlighted?
I am using the posted source code from here: Blackberry Tablemodel gets messed up when scrolling
I am using the Eclipse IDE from RIM and JRE 7.0.0
public class ProductsScreen extends MainScreen
{
private TableModel _tableModel;
private static final int ROW_HEIGHT = 40;
public ProductsScreen(MainCategory mc)
{
super(Manager.NO_VERTICAL_SCROLL | Manager.HORIZONTAL_SCROLL);
DBManager dbman = DBManager.getInstance();
AllProductByCategory[] products = null;
try {
products = dbman.getProducts(mc.getID().intValue());
} catch (DatabaseException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setTitle(mc.getName());
_tableModel = new TableModel();//(StringComparator.getInstance(true), 0);
if(products != null)
{
for(int i = 0; i < products.length; i++)
{
ViewableData[] data = products[i].getData().getViewableData();
for(int j = 0; j < data.length; j++)
{
_tableModel.addRow(new Object[] {products[i].getCategoryName(), data[j].getTitle2()});
}
}
}
RegionStyles style = new RegionStyles(BorderFactory.createSimpleBorder(new XYEdges(1, 1, 1, 1), Border.STYLE_SOLID), null, null,
null, RegionStyles.ALIGN_LEFT, RegionStyles.ALIGN_TOP);
TableView tableView = new TableView(_tableModel);
final TableController tableController = new TableController(_tableModel, tableView);
tableController.setFocusPolicy(TableController.ROW_FOCUS);
tableController.setCommand(new Command(new CommandHandler()
{
public void execute(ReadOnlyCommandMetadata metadata, Object context)
{
}
}));
tableView.setController(tableController);
DataTemplate dataTemplate = new DataTemplate(tableView, 2, 2)
{
public Field[] getDataFields(int modelRowIndex)
{
final Object[] data = (Object[]) _tableModel.getRow(modelRowIndex);
Field[] fields = new Field[3];
String rowGroup = (String)data[0];
// we're in a new group if this is the very first row, or if this row's
// data[0] value is different from the last row's data[0] value
boolean isNewGroup = (modelRowIndex == 0) ||
(rowGroup.compareTo((String) ((Object[])_tableModel.getRow(modelRowIndex - 1))[0]) != 0);
if (isNewGroup) {
// make a separator row
fields[0] = new HeaderField((String)data[0],
Field.USE_ALL_WIDTH | Field.NON_FOCUSABLE);
} else {
// this is in the same group as the last product, so don't add anything here
fields[0] = new NullField();
}
// now, add the actual product information
fields[1] = new LabelField((String)data[1],
Field.USE_ALL_WIDTH | Field.FOCUSABLE | Field.USE_ALL_HEIGHT | DrawStyle.ELLIPSIS);
fields[2] = new BitmapField(Bitmap.getBitmapResource("img/bullet_arrow_right.png"));
return fields;
}
};
dataTemplate.createRegion(new XYRect(0, 0, 2, 1)); // group separator (maybe a null field)
dataTemplate.createRegion(new XYRect(0, 1, 1, 1)); // actual rows with product information
dataTemplate.createRegion(new XYRect(1, 1, 1, 1));
dataTemplate.setColumnProperties(0, new TemplateColumnProperties(95, TemplateColumnProperties.PERCENTAGE_WIDTH));
dataTemplate.setColumnProperties(1, new TemplateColumnProperties(5, TemplateColumnProperties.PERCENTAGE_WIDTH));
dataTemplate.setRowProperties(0, new TemplateRowProperties(ROW_HEIGHT)); // separator
dataTemplate.setRowProperties(1, new TemplateRowProperties(ROW_HEIGHT)); // product data
dataTemplate.useFixedHeight(false);
tableView.setDataTemplate(dataTemplate);
add(tableView);
}
}
SOLUTION:
I was able to solve the problem on my own with the following approach.
I just added a overridden LabelField as headerfield and didn't implement its focus drawing. So only the "subfields" get the focus drawn.
Maybe some people would implement it in another way (take a look at the answer from Nate) but it worked for me.
So, I didn't have time to fully integrate your new code sample, which has data model code that I don't have, and which appears to have added a DataTemplate column for a BitmapField. Hopefully, you can adapt what I have to reintegrate those changes.
I'm sure there's more than one way to do this, and I'm not claiming this method to be the highest performance. However, it seems to draw the focus as you would expect, without the separator row getting highlighted when the row directly under it is focused.
What I did was abandon the concept of using multiple regions, and just made my data template 1 row by 1 column. If you want, you can probably make it 1 row by 2 columns, where the column I don't show is the BitmapField.
But, what I did was to place a VerticalFieldManager in the first row in each new group/category. That VerticalFieldManager then contained a separator/header row, a separator field (just a horizontal line), and then the actual product row. If the row was not the first in the group/category, I would just return a simple Field, not a VerticalFieldManager with three Field objects inside it.
Then, I changed the TableController focus policy to FIELD_FOCUS, not ROW_FOCUS. This allows focus to be taken by the VerticalFieldManager, when we're on the first row in a new group/category. However, inside that manager, only the actual product row is focusable. The separator row is not focusable, and will therefore not be drawn with focus.
Here's the code that changed. The rest is the same as in the previous sample I gave you:
_tableController.setFocusPolicy(TableController.FIELD_FOCUS);
_tableView.setController(_tableController);
DataTemplate dataTemplate = new DataTemplate(_tableView, 1, 1) // 1 row now!
{
public Field[] getDataFields(int modelRowIndex)
{
final Object[] data = (Object[]) _tableModel.getRow(modelRowIndex);
String rowGroup = (String)data[0];
// we're in a new group if this is the very first row, or if this row's data[0] value is
// different from the last row's data[0] value
boolean isNewGroup = (modelRowIndex == 0) ||
(rowGroup.compareTo((String) ((Object[])_tableModel.getRow(modelRowIndex - 1))[0]) != 0);
if (isNewGroup) {
LabelField header = new LabelField((String)data[0], Field.USE_ALL_WIDTH | Field.NON_FOCUSABLE);
SeparatorField line = new SeparatorField(Field.USE_ALL_WIDTH) {
public void paint(Graphics g) {
g.setColor(Color.BLACK);
super.paint(g);
}
};
LabelField productRow = new LabelField((String)data[1],
Field.USE_ALL_WIDTH | Field.FOCUSABLE | DrawStyle.HCENTER);
VerticalFieldManager manager = new VerticalFieldManager(Field.USE_ALL_WIDTH | Field.FOCUSABLE |
Manager.NO_VERTICAL_SCROLL | Manager.NO_VERTICAL_SCROLLBAR);
manager.add(header);
manager.add(line);
manager.add(productRow);
return new Field[] { manager };
} else {
return new Field[] { new LabelField((String)data[1],
Field.USE_ALL_WIDTH | Field.FOCUSABLE | DrawStyle.HCENTER) };
}
}
};
// create just one region, with one row and one full-width column
dataTemplate.createRegion(new XYRect(0, 0, 1, 1), _style); // may be a product row, or a product row + separator
dataTemplate.setColumnProperties(0, new TemplateColumnProperties(100, TemplateColumnProperties.PERCENTAGE_WIDTH));
dataTemplate.setRowProperties(0, new TemplateRowProperties(2 * ROW_HEIGHT)); // max height if row + separator
_tableView.setDataTemplate(dataTemplate);
dataTemplate.useFixedHeight(false);
The scrolling is a little funny when you get down to the bottom of the page, but I'm pretty sure I've built VerticalFieldManager subclasses before that acted like lists, that needed some custom scroll handling ... if I get some time tomorrow, I'll try to add that in.
One step at a time, though ...

Not getting the text from Edit Field

In my Application, i am adding a check box, a label field and a Edit Field in a Grid Field manager. Then this grid Field manager, i am adding multiple times in Vertical Field manager. So it is looking like List of items. Now when i checked five check box, i am trying to get the text of the correspondent edit field.
This is the code for Grid Field Manager:
int c[] = {screenWidth/6, (screenWidth)/3, (screenWidth)/2};
gm = new GridFieldManager(c, Manager.VERTICAL_SCROLL);
Logger.out("Grocery", "Here it is coming"+i);
cbfChecked = new CustomCheckBoxField();
cbfChecked.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
if(checked[i] == false)
{
checked[i] = true;
}
else if(checked[i] == true)
{
checked[i] = false;
Logger.out("Grocery", "It is UnChecked" +checked[i]);
}
}
});
gm.add(cbfChecked);
Logger.out("Grocery", "Adding first Label Field");
LabelFieldCustom lfFrom = new LabelFieldCustom((String) m_vtrItems.elementAt(i),Color.BROWN,FONT_FAMILY_0_SF_AS_16,Field.FIELD_LEFT);
gm.add(lfFrom);
Logger.out("Grocery", "Adding second Label Field");
efcAmount = new EditFieldCustom(Bitmap.getBitmapResource("dob_text_box.png"), 25);
efcAmount.setMargin(new XYEdges(30, 0, 0, 0));
gm.add(efcAmount);
return gm;
Here i am adding the grid field manager multiple times:
for (int i = 0;i < m_vtrItems.size();i++)
{
vfm.add(getRow(i));
vfm.add(new SeparatorField(SeparatorField.NON_FOCUSABLE));
}
Please help me.
I solve the problem. Now i am taking the Edit Field array.

How can I enable/disable cells using Vaadin table component?

I have a table with 2 columns: a checkbox and a textfield. I want to disable the textfield depending of the respective (same row) checkbox status. If the checkbox is checked then the textfield will be cleared and be read only. Is this possible ? Here is my code:
#SuppressWarnings("serial")
private Table filtersTable() {
final Table table = new Table();
table.setPageLength(10);
table.setSelectable(false);
table.setImmediate(true);
table.setSizeFull();
// table.setMultiSelectMode(MultiSelectMode.SIMPLE) ;
table.addContainerProperty("Tipo filtro", CheckBox.class, null);
table.addContainerProperty("Valor", String.class, null);
table.setEditable(true);
for (int i = 0; i < 15; i++) {
TextField t = new TextField();
t.setData(i);
t.setMaxLength(50);
t.setValue("valor " + i);
t.setImmediate(true);
t.setWidth(30, UNITS_PERCENTAGE);
CheckBox c = new CheckBox(" filtro " + i);
c.setWidth(30, UNITS_PERCENTAGE);
c.setData(i);
c.setImmediate(true);
c.addListener(new ValueChangeListener() {
#Override
public void valueChange(ValueChangeEvent event) {
// within this, could I access the respective row ID
// (i) then enable/disable TextField t on second column ?
System.out.println("event.getProperty().getValue()="
+ event.getProperty().getValue());
}
});
table.addItem(new Object[] { c, t }, i);
}
return table;
}
Thanks
Few changes to your code made it possible.
Not the finiest way, but te simpliest.
First,you have to set your second column (Valor) to TextField.class not String.class.
Here the change :
table.addContainerProperty("Valor", TextField.class, null);
Instead of keepin the variable i in the CheckBox.setData(), I suggest you to link your checkBox to the TextField of the same row, like this :
c.setData(t);
Finally I made little change to your listener :
c.addListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
CheckBox checkBox = (CheckBox)event.getProperty();
if((Boolean) checkBox.getValue())
{
TextField associatedTextField = (TextField)checkBox.getData();
//Do all your stuff with the TextField
associatedTextField.setReadOnly(true);
}
}
});
Hope it's work for you!
Regards, Éric
public class MyCheckBox extends CheckBox {
private TextBox t;
public MyCheckBox(TextBox t) {
this.t = t;
attachLsnr();
}
private void attachLsnr()
{
addListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
CheckBox checkBox = (CheckBox)event.getProperty();
if((Boolean) checkBox.getValue())
{
t.setReadOnly(true);
}
}
});
}
}

Resources