Enabling single column selection in org.eclipse.swt.widgets.Table - eclipse-rcp

I have used the org.eclipse.swt.widgets.Table
Code implementation will look like this
Table table = new Table(shell, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION);
But i need behavior like if mouse clicked on 'Sec_1' i want only 'Sec_1' to be selected not entire row and if mouse clicked on 'First_1' i don't want it to be Highlighted(FirstColumn no selection).
Can any one help me ?

Please see this code snippet for example (http://git.eclipse.org/c/platform/eclipse.platform.ui.git/tree/examples/org.eclipse.jface.snippets/Eclipse%20JFace%20Snippets/org/eclipse/jface/snippets/viewers/Snippet036FocusBorderCellHighlighter.java):
public class Test {
private class MyContentProvider implements IStructuredContentProvider {
/*
* (non-Javadoc)
*
* #see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
*/
public Object[] getElements(Object inputElement) {
return (MyModel[]) inputElement;
}
/*
* (non-Javadoc)
*
* #see org.eclipse.jface.viewers.IContentProvider#dispose()
*/
public void dispose() {
}
/*
* (non-Javadoc)
*
* #see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer,
* java.lang.Object, java.lang.Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
}
public static boolean flag = true;
public class MyModel {
public int counter;
public MyModel(int counter) {
this.counter = counter;
}
public String toString() {
return "Item " + this.counter;
}
}
public class MyLabelProvider extends LabelProvider implements
ITableLabelProvider, ITableFontProvider, ITableColorProvider {
FontRegistry registry = new FontRegistry();
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
public String getColumnText(Object element, int columnIndex) {
return "Column " + columnIndex + " => " + element.toString();
}
public Font getFont(Object element, int columnIndex) {
return null;
}
public Color getBackground(Object element, int columnIndex) {
return null;
}
public Color getForeground(Object element, int columnIndex) {
return null;
}
}
public Test(Shell shell) {
final TableViewer v = new TableViewer(shell, SWT.BORDER|SWT.FULL_SELECTION);
v.setLabelProvider(new MyLabelProvider());
v.setContentProvider(new MyContentProvider());
v.setCellEditors(new CellEditor[] { new TextCellEditor(v.getTable()), new TextCellEditor(v.getTable()), new TextCellEditor(v.getTable()) });
v.setCellModifier(new ICellModifier() {
public boolean canModify(Object element, String property) {
return true;
}
public Object getValue(Object element, String property) {
return "Column " + property + " => " + element.toString();
}
public void modify(Object element, String property, Object value) {
}
});
v.setColumnProperties(new String[] {"1","2","3"});
TableViewerFocusCellManager focusCellManager = new TableViewerFocusCellManager(v,new FocusCellOwnerDrawHighlighter(v));
ColumnViewerEditorActivationStrategy actSupport = new ColumnViewerEditorActivationStrategy(v) {
protected boolean isEditorActivationEvent(
ColumnViewerEditorActivationEvent event) {
return event.eventType == ColumnViewerEditorActivationEvent.TRAVERSAL
|| event.eventType == ColumnViewerEditorActivationEvent.MOUSE_DOUBLE_CLICK_SELECTION
|| (event.eventType == ColumnViewerEditorActivationEvent.KEY_PRESSED && event.keyCode == SWT.CR)
|| event.eventType == ColumnViewerEditorActivationEvent.PROGRAMMATIC;
}
};
TableViewerEditor.create(v, focusCellManager, actSupport, ColumnViewerEditor.TABBING_HORIZONTAL
| ColumnViewerEditor.TABBING_MOVE_TO_ROW_NEIGHBOR
| ColumnViewerEditor.TABBING_VERTICAL | ColumnViewerEditor.KEYBOARD_ACTIVATION);
TableColumn column = new TableColumn(v.getTable(), SWT.NONE);
column.setWidth(200);
column.setMoveable(true);
column.setText("Column 1");
column = new TableColumn(v.getTable(), SWT.NONE);
column.setWidth(200);
column.setMoveable(true);
column.setText("Column 2");
column = new TableColumn(v.getTable(), SWT.NONE);
column.setWidth(200);
column.setMoveable(true);
column.setText("Column 3");
MyModel[] model = createModel();
v.setInput(model);
v.getTable().setLinesVisible(true);
v.getTable().setHeaderVisible(true);
}
private MyModel[] createModel() {
MyModel[] elements = new MyModel[10];
for (int i = 0; i < 10; i++) {
elements[i] = new MyModel(i);
}
return elements;
}
/**
* #param args
*/
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
new Test(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}

Related

assertion failed: Unknown column layout data

When I create combo box in particular only one 3rd column using table viewer in Eclipse SWT.
I think I've done everything ok until now, however when I compile the code then i get error:
Code:
public void createPartControl(Composite parent) {
Composite tableComposite = new Composite(parent, SWT.NONE);
tableColumnLayout = new TableColumnLayout();
tableComposite.setLayout(tableColumnLayout);
tableComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
true));
tableViewer = new TableViewer(tableComposite, SWT.MULTI | SWT.H_SCROLL
| SWT.V_SCROLL);
tableViewer.setContentProvider(ArrayContentProvider.getInstance());
// TODO viewer.setLabelProvider(new ViewLabelProvider());
table = tableViewer.getTable();
// Table table = tableViewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
String[] titles = { "Threat Name", "Category Name", "Status",
"Priority", "Description", "Justification" };
int[] bounds = { 100, 100, 100, 100 };
TableViewerColumn col = createTableViewerColumn(titles[2], bounds[2], 2);
col.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
Dummy p = (Dummy) element;
return p.getValue();
}
});
col.setEditingSupport(new FirstValueEditingSupport(tableViewer));
}
private SelectionAdapter getSelectionAdapter(final TableColumn column,
final int index) {
SelectionAdapter selectionAdapter = new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
tableViewer.refresh();
}
};
return selectionAdapter;
}
private static class Dummy {
public String value;
public Dummy(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public static class FirstValueEditingSupport extends EditingSupport {
private final TableViewer viewer;
private final CellEditor editor;
private final String[] possibleValues = { "Mitigated",
"Not Applicable", "Not Started", "Needs Investigation" };
public FirstValueEditingSupport(TableViewer viewer) {
super(viewer);
this.viewer = viewer;
this.editor = new ComboBoxCellEditor(viewer.getTable(),
possibleValues);
}
#Override
protected CellEditor getCellEditor(Object element) {
return editor;
}
#Override
protected boolean canEdit(Object element) {
return true;
}
#Override
protected Object getValue(Object element) {
Dummy dummy = (Dummy) element;
int index = 0;
for (int i = 0; i < possibleValues.length; i++) {
if (Objects.equals(possibleValues[i], dummy.getValue())) {
index = i;
break;
}
}
return index;
}
#Override
protected void setValue(Object element, Object value) {
Dummy dummy = (Dummy) element;
int index = (Integer) value;
dummy.setValue(possibleValues[index]);
viewer.update(element, null);
}
}
private void fillRows(String shortdesc, String categ, String descp) {
System.out.println("fillRows call from above method.");
TableColumn status_Name_Col = tableViewer.getTable().getColumn(2);
System.out.println("**************** status_Name_Col ************ "
+ status_Name_Col);
tableViewer
.addSelectionChangedListener(new ISelectionChangedListener() {
#Override
public void selectionChanged(
SelectionChangedEvent selectionChangedEvent) {
StructuredSelection selection = (StructuredSelection) selectionChangedEvent
.getSelection();
System.out.println(((Dummy) selection.getFirstElement())
.getValue());
}
});
List<Dummy> elements = new ArrayList<>();
for (int i = 0; i < Connection.Number_Of_Connection; i++) {
elements.add(new Dummy("First option"));
}
tableViewer.setInput(elements);
tableColumnLayout.setColumnData(status_Name_Col, new ColumnWeightData(
1, true));
tableViewerColumn.setEditingSupport(new FirstValueEditingSupport(
tableViewer));
}
Questions:
how to display combo box in particular only one column?
You must not do the TableViewer setInput call until you have set up everything on the table. All the content providers, label providers, column layouts, editing support, .... must be set before setInput is called.
You must also call setColumnData for every column you create.

How do i get The answers selected in testFragment which is set in the customlistadapter?

This is my testfragment where i build the list based on a switch:
public class TestFragment extends Fragment {
public String Workshop;
public int NumberOfQuestions;
public Button SaveButton;
public TextView GradeView;
public String Grades;
private OnFragmentInteractionListener mListener;
public TestFragment() {}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle bundle){
View rootView = inflater.inflate(R.layout.questionscomplete,
container, false);
Workshop = getArguments().getString("Workshoptitle");
GradeView = ((TextView) rootView.findViewById(R.id.GradeView));
// Inflate the layout for this fragment
if (!Workshop.equals("Doodlz Drawing")) {
rootView = inflater.inflate(R.layout.fragment_test,
container, false);
final ListView lv1 = (ListView) rootView.findViewById(R.id.listview);
ArrayList image_details = getListData();
lv1.setAdapter(new CustomListAdapter(getActivity(), image_details));
SaveButton = ((Button) rootView.findViewById(R.id.Save));
SaveButton.setOnClickListener(Grading);
}
return rootView;
}
private ArrayList getListData() {
ArrayList<QuestionItem> results = new ArrayList<QuestionItem>();
switch (Workshop) {
case "Android Studio":
Workshop = "Android Studio";
QuestionItem[] Item1 = new QuestionItem[3];
QItem WS1 = new QItem();
NumberOfQuestions = Item1.length;
String[] WS1Q = WS1.getQuestions(Workshop, NumberOfQuestions);
String[] WS1QA = WS1.getAnswers(Workshop);
for (int i = 0; i < NumberOfQuestions; i++) {
Item1[i] = new QuestionItem();
Item1[i].setQuestion(WS1Q[i]);
Item1[i].setAnswer1(WS1QA[i * 10 + 0]);
Item1[i].setAnswer2(WS1QA[i * 10 + 1]);
Item1[i].setAnswer3(WS1QA[i * 10 + 2]);
Item1[i].setAnswer4(WS1QA[i * 10 + 3]);
// Toast.makeText(getActivity(), Item1[i].GetAnswer(),
// Toast.LENGTH_LONG).show();
results.add(Item1[i]);
}
break;
case "Java Basics":
Workshop = "Java Basics";
QuestionItem[] Item2 = new QuestionItem[5];
QItem WS2 = new QItem();
NumberOfQuestions = Item2.length;
String[] WS2Q = WS2.getQuestions(Workshop, NumberOfQuestions);
String[] WS2QA = WS2.getAnswers(Workshop);
for (int i = 0; i < NumberOfQuestions; i++) {
Item2[i] = new QuestionItem();
Item2[i].setQuestion(WS2Q[i]);
Item2[i].setAnswer1(WS2QA[i * 10 + 0]);
Item2[i].setAnswer2(WS2QA[i * 10 + 1]);
Item2[i].setAnswer3(WS2QA[i * 10 + 2]);
Item2[i].setAnswer4(WS2QA[i * 10 + 3]);
results.add(Item2[i]);
// Toast.makeText(getActivity(), Item2[i].GetAnswer(),
// Toast.LENGTH_LONG).show();
}
break;
My listadapter:
public class CustomListAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
public String Answer;
public String[] Answers;
private ArrayList<QuestionItem> listData;
public CustomListAdapter(Context aContext, ArrayList<QuestionItem> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(aContext);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View v = convertView;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.questions, null);
holder = new ViewHolder(
);
holder.QuestionView = (TextView) convertView.findViewById(R.id.q);
holder.Answer1View = (TextView) convertView.findViewById(R.id.qa1);
holder.Answer2View = (TextView) convertView.findViewById(R.id.qa2);
holder.Answer3View = (TextView) convertView.findViewById(R.id.qa3);
holder.Answer4View = (TextView) convertView.findViewById(R.id.qa4);
//
holder.Answer1Button = (RadioButton) convertView.findViewById(R.id.qa1);
holder.Answer2Button = (RadioButton) convertView.findViewById(R.id.qa2);
holder.Answer3Button = (RadioButton) convertView.findViewById(R.id.qa3);
holder.Answer4Button = (RadioButton) convertView.findViewById(R.id.qa4);
holder.ButtonGroupView = (RadioGroup) convertView.findViewById(R.id.group);
convertView.setTag(holder);
holder.ButtonGroupView.getCheckedRadioButtonId();
holder.ButtonGroupView
.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group,
int checkedId) {
Integer pos = (Integer) group.getTag(); // To identify the Model object i get from the RadioGroup with getTag()
// an integer representing the actual position
QuestionItem element = listData.get(pos);
switch (checkedId) { //set the Model to hold the answer the user picked
case R.id.qa1:
element.setAnswer("1");
"Log.d(listData.get(pos).toString(), element.GetAnswer());
break;
case R.id.qa2:
element.setAnswer("2");
"Log.d(listData.get(pos).toString(), element.GetAnswer());
break;
case R.id.qa3:
element.setAnswer("3");
"Log.d(listData.get(pos).toString(), element.GetAnswer());
break;
case R.id.qa4:
element.setAnswer("4");
"Log.d(listData.get(pos).toString(), element.GetAnswer());
break;
default:
element.setAnswer(null); // Something was wrong set to the default
}
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
QuestionItem element = (QuestionItem) getItem(position);
holder.QuestionView.setText(listData.get(position).getQuestion());
holder.Answer1View.setText(listData.get(position).Getanswer1());
holder.Answer2View.setText(listData.get(position).Getanswer2());
holder.Answer3View.setText(listData.get(position).Getanswer3());
holder.Answer4View.setText(listData.get(position).Getanswer4());
holder.ButtonGroupView.setTag(new Integer(position)); // I passed the current position as a tag
return convertView;
}
//
class ViewHolder {
TextView t = null;
TextView QuestionView;
TextView Answer1View;
TextView Answer2View;
TextView Answer3View;
TextView Answer4View;
RadioButton Answer1Button, Answer2Button, Answer3Button, Answer4Button;
RadioGroup ButtonGroupView;
}}
My question Item:
public class QuestionItem {
private String Question;
private String Answer1;
private String Answer2;
private String Answer3;
private String Answer4;
private String Answer;
public String getQuestion() {
return Question;
}
public void setQuestion(String Question) {
this.Question = Question;
}
public String Getanswer1() {
return Answer1;
}
public void setAnswer1(String Answer1) {
this.Answer1 = Answer1;
}
public String Getanswer2() {
return Answer2;
}
public void setAnswer2(String Answer2) {
this.Answer2 = Answer2;
}
public String Getanswer3() {
return Answer3;
}
public void setAnswer3(String Answer3) {
this.Answer3 = Answer3;
}
public String Getanswer4() {
return Answer4;
}
public void setAnswer4(String Answer4) {
this.Answer4 = Answer4;
}
public String GetAnswer() {
return Answer;
}
public void setAnswer(String Answer) {
this.Answer = Answer;
}
}
I want to save all the answers and compare them to the right answers and save the score to be used as a variable in another fragment.
UPDATE: added "Log.d(listData.get(pos).toString(), element.GetAnswer());" And i can see it is storing the choses answers so how do i request them in the testfragment and check them
Ive tried several things but cannot find the solution. pls help:)?

CustomdataGrid is not being displayed in the browser

I have a custom datagrid which is defined as follows
public class CustomDataGrid<T> extends DataGrid<T> {
private static final int PAGE_SIZE = 10;
public CustomDataGrid(ProvidesKey<T> keysProvider) {
super(PAGE_SIZE, keysProvider);
}
public CustomDataGrid() {
super(PAGE_SIZE);
}
public void redrawRow(int absRowIndex) {
int relRowIndex = absRowIndex - getPageStart();
checkRowBounds(relRowIndex);
setRowData(absRowIndex, Collections.singletonList(getVisibleItem(relRowIndex)));
}
}
I am using ui binder and in my xml file I have defined the elements as follows
<com:CustomDataGrid ui:field="commissionListDataGrid"></com:CustomDataGrid>
Now the custom datagrid is initialised as follows
#UiField
CustomDataGrid commissionListDataGrid;
private final Set<Long> showingFriends = new HashSet<Long>();
private Column<ServiceCategorywiseCommissionDetails, String> viewFriendsColumn;
private Column<ServiceCategorywiseCommissionDetails, String> serviceType;
public ZoneCommissionListView() {
commissionListDataGrid = new CustomDataGrid<ServiceCategorywiseCommissionDetails>(new ProvidesKey<ServiceCategorywiseCommissionDetails>() {
#Override
public Object getKey(ServiceCategorywiseCommissionDetails item) {
return item == null ? null : item.getId();
}
});
commissionListDataGrid.setWidth("100%");
commissionListDataGrid.setEmptyTableWidget(new Label("Empty data"));
commissionListDataGrid.setHeight("100%");
// commissionListLayoutPanel = new SimpleLayoutPanel();
initCommissionListDataGrid();
// commissionListLayoutPanel.add(commissionListDataGrid);
//RootLayoutPanel.get().add(commissionListLayoutPanel);
}
#Override
public Widget asWidget() {
return this.widget;
}
#Override
public void setUiHandlers(ZoneCommissionListUiHandlers uiHandlers) {
this.uiHandlers = uiHandlers;
}
public void initCommissionListDataGrid() {
// View friends.
SafeHtmlRenderer<String> anchorRenderer = new AbstractSafeHtmlRenderer<String>() {
#Override
public SafeHtml render(String object) {
SafeHtmlBuilder sb = new SafeHtmlBuilder();
sb.appendHtmlConstant("(").appendEscaped(object).appendHtmlConstant(")");
return sb.toSafeHtml();
}
};
viewFriendsColumn = new Column<ServiceCategorywiseCommissionDetails, String>(new ClickableTextCell(anchorRenderer)) {
#Override
public String getValue(ServiceCategorywiseCommissionDetails object) {
if (showingFriends.contains(object.getId())) {
return "-";
} else {
return "+";
}
}
};
viewFriendsColumn.setFieldUpdater(new FieldUpdater<ServiceCategorywiseCommissionDetails, String>() {
#Override
public void update(int index, ServiceCategorywiseCommissionDetails object, String value) {
if (showingFriends.contains(object.getId())) {
showingFriends.remove(object.getId());
} else {
showingFriends.add(object.getId());
}
// Redraw the modified row.
commissionListDataGrid.redrawRow(index);
}
});
// First name.
serviceType = new Column<ServiceCategorywiseCommissionDetails, String>(new TextCell()) {
#Override
public String getValue(ServiceCategorywiseCommissionDetails object) {
return object.getServiceType();
}
};
commissionListDataGrid.setTableBuilder(new CustomTableBuilder());
commissionListDataGrid.setHeaderBuilder(new CustomHeaderBuilder());
// commissionListDataGrid.setFooterBuilder(new CustomFooterBuilder());
// GWT.log("list size is " + ContactDatabase.get().getDataProvider().getList().size());
// commissionListDataGrid.setRowData(ContactDatabase.get().getDataProvider().getList());
// Button button = new Button();
// button.setText("hello");
// commissionListLayoutPanel.add(commissionListDataGrid);
this.widget = uiBinder.createAndBindUi(this);
}
private class CustomTableBuilder extends AbstractCellTableBuilder<ServiceCategorywiseCommissionDetails> {
private final String childCell = " ";
private final String rowStyle;
private final String selectedRowStyle;
private final String cellStyle;
private final String selectedCellStyle;
#SuppressWarnings("deprecation")
public CustomTableBuilder() {
super(commissionListDataGrid);
// Cache styles for faster access.
Style style = commissionListDataGrid.getResources().style();
rowStyle = style.evenRow();
selectedRowStyle = " " + style.selectedRow();
cellStyle = style.cell() + " " + style.evenRowCell();
selectedCellStyle = " " + style.selectedRowCell();
}
public void buildRowImpl(ServiceCategorywiseCommissionDetails rowValue, int absRowIndex) {
buildServiceTypeRow(rowValue, absRowIndex, false);
GWT.log("Inside build row impl");
// Display list of friends.
if (showingFriends.contains(rowValue.getId())) {
TableRowBuilder row = startRow();
TableCellBuilder th = row.startTH();
th.text("").endTH();
TableCellBuilder th2 = row.startTH();
th2.text("Service Name").endTH();
TableCellBuilder th3 = row.startTH();
th3.text("SuperZone Commission").endTH();
TableCellBuilder th4 = row.startTH();
th4.text("Zone Commission").endTH();
row.endTR();
List<ServiceCommissionDetails> friends = rowValue.getServiceCommissionDetails();
for (ServiceCommissionDetails friend : friends) {
buildServiceCommissionDetailRow(friend, absRowIndex, true);
}
}
}
#SuppressWarnings("deprecation")
private void buildServiceTypeRow(ServiceCategorywiseCommissionDetails rowValue, int absRowIndex, boolean isFriend) {
GWT.log("inside build service Type row");
SelectionModel<? super ServiceCategorywiseCommissionDetails> selectionModel = commissionListDataGrid.getSelectionModel();
boolean isSelected = (selectionModel == null || rowValue == null) ? false : selectionModel.isSelected(rowValue);
boolean isEven = absRowIndex % 2 == 0;
StringBuilder trClasses = new StringBuilder(rowStyle);
if (isSelected) {
trClasses.append(selectedRowStyle);
}
// Calculate the cell styles.
String cellStyles = cellStyle;
if (isSelected) {
cellStyles += selectedCellStyle;
}
if (isFriend) {
cellStyles += childCell;
}
TableRowBuilder row = startRow();
row.className(trClasses.toString());
/*
* Checkbox column.
*
* This table will uses a checkbox column for selection. Alternatively, you can call dataGrid.setSelectionEnabled(true) to
* enable mouse selection.
*/
TableCellBuilder td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
td.endTD();
/*
* View friends column.
*
* Displays a link to "show friends". When clicked, the list of friends is displayed below the contact.
*/
td = row.startTD();
td.className(cellStyles);
if (!isFriend) {
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
renderCell(td, createContext(1), viewFriendsColumn, rowValue);
}
td.endTD();
// First name column.
td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
if (isFriend) {
td.text(rowValue.getServiceType());
} else {
renderCell(td, createContext(2), serviceType, rowValue);
}
td.endTD();
// Last name column.
row.endTR();
}
#SuppressWarnings("deprecation")
private void buildServiceCommissionDetailRow(ServiceCommissionDetails rowValue, int absRowIndex, boolean isFriend) {
GWT.log("inside build service commission detail row");
// Calculate the row styles.
// boolean isSelected = (selectionModel == null || rowValue == null)
// ? false : selectionModel.isSelected(rowValue);
// boolean isEven = absRowIndex % 2 == 0;
StringBuilder trClasses = new StringBuilder(rowStyle);
// if (isSelected) {
// trClasses.append(selectedRowStyle);
// }
// Calculate the cell styles.
String cellStyles = cellStyle;
// cellStyles += selectedCellStyle;
cellStyles += childCell;
TableRowBuilder row = startRow();
row.className(trClasses.toString());
/*
* Checkbox column.
*
* This table will uses a checkbox column for selection. Alternatively, you can call dataGrid.setSelectionEnabled(true) to
* enable mouse selection.
*/
TableCellBuilder td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
td.endTD();
/*
* View friends column.
*
* Displays a link to "show friends". When clicked, the list of friends is displayed below the contact.
*/
// First name column.
td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
td.text(rowValue.getServiceName());
td.endTD();
td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
td.text(rowValue.getSuperZoneCommission());
td.endTD();
td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
td.text(rowValue.getZoneCommission());
td.endTD();
// Last name column.
row.endTR();
}
}
private class CustomHeaderBuilder extends AbstractHeaderOrFooterBuilder<ServiceCategorywiseCommissionDetails> {
private Header<String> firstNameHeader = new TextHeader("Co mmission List");
public CustomHeaderBuilder() {
super(commissionListDataGrid, false);
setSortIconStartOfLine(false);
}
#Override
protected boolean buildHeaderOrFooterImpl() {
Style style = commissionListDataGrid.getResources().style();
String groupHeaderCell = "Header Cell";
// Add a 2x2 header above the checkbox and show friends columns.
TableRowBuilder tr = startRow();
tr.startTH().colSpan(2).rowSpan(2).className(style.header() + " " + style.firstColumnHeader());
tr.endTH();
/*
* Name group header. Associated with the last name column, so clicking on the group header sorts by last name.
*/
// Get information about the sorted column.
ColumnSortList sortList = commissionListDataGrid.getColumnSortList();
ColumnSortInfo sortedInfo = (sortList.size() == 0) ? null : sortList.get(0);
Column<?, ?> sortedColumn = (sortedInfo == null) ? null : sortedInfo.getColumn();
boolean isSortAscending = (sortedInfo == null) ? false : sortedInfo.isAscending();
// Add column headers.
tr = startRow();
buildHeader(tr, firstNameHeader, serviceType, sortedColumn, isSortAscending, false, false);
tr.endTR();
return true;
}
private void buildHeader(TableRowBuilder out, Header<?> header, Column<ServiceCategorywiseCommissionDetails, ?> column, Column<?, ?> sortedColumn, boolean isSortAscending, boolean isFirst,
boolean isLast) {
// Choose the classes to include with the element.
Style style = commissionListDataGrid.getResources().style();
boolean isSorted = (sortedColumn == column);
StringBuilder classesBuilder = new StringBuilder(style.header());
if (isFirst) {
classesBuilder.append(" " + style.firstColumnHeader());
}
if (isLast) {
classesBuilder.append(" " + style.lastColumnHeader());
}
// if (column.isSortable()) {
// classesBuilder.append(" " + style.sortableHeader());
// }
if (isSorted) {
classesBuilder.append(" " + (isSortAscending ? style.sortedHeaderAscending() : style.sortedHeaderDescending()));
}
// Create the table cell.
TableCellBuilder th = out.startTH().className(classesBuilder.toString());
// Associate the cell with the column to enable sorting of the
// column.
enableColumnHandlers(th, column);
// Render the header.
Context context = new Context(0, 2, header.getKey());
renderSortableHeader(th, context, header, isSorted, isSortAscending);
// End the table cell.
th.endTH();
}
}
public void setCommissionListDataGrid(ListDataProvider<ServiceCategorywiseCommissionDetails> dataProvider) {
GWT.log("inside set commissionListDataGrid size is " + dataProvider.getList().size());
commissionListDataGrid.setRowData(dataProvider.getList());
}
And I have a method in the presenter which calls the method set CommissionListDataGrid and sets its row value.
While doing this the data grid is not displayed. However if i add simplelayoutpanel in the following way in the constructor 'ZoneCommissionListView()'
RootPanel.get().add(commissionListLayoutPanel);
Then the data grid is displayed .What exactly am I missing .Any suggestion would be appreciated
DataGrid requires to be put in a LayoutPanel or Panel that implements
the ProvidesResize interface to be visible.
Source
And the SimpelLayoutPanel which you tested also implements the ProvidesResize Interface.

how to get data from database with parameter

I'm trying to show a list with the list items from my database having 2 parameters, but the list didn't show.
Here's my query database from php:
$query = mysql_query("SELECT d.model_name from detail_product d join brand b on d.id_brandtype = b.id_brand join biketype t on d.id_biketype = t.id_type where d.id_brandtype = 1 and d.id_biketype=1");
I've set the parameter there.
and here's my DAO:
public class info_xc_dao {
public final static int VIEW_POL_XC = 0;
private static final String URL_VIEW_POL_XC = ServerConfiguration.SERVER_URL
+ "polygon_xc.php";
private int Action;
pol_xc_Result pol_xc_Result;
public info_xc_dao(pol_xc_Result pol_xc_Result) {
// TODO Auto-generated constructor stub
this.pol_xc_Result = pol_xc_Result;
}
public void view_pol_xc() {
Action = VIEW_POL_XC;
new ConnectionHandler(connectionResult, null, URL_VIEW_POL_XC,
ConnectionHandler.GET);
}
public ConnectionResult connectionResult = new ConnectionResult() {
#Override
public void gotResult(String result, String message) {
// TODO Auto-generated method stub
if (result != null) {
switch (Action) {
case VIEW_POL_XC:
try {
JSONObject jsonObject = null;
jsonObject = new JSONObject(result);
int response = jsonObject.getInt("result");
if (response != 0) {
JSONArray jsonArray = new JSONArray(
jsonObject.getString("data"));
ArrayList<Entity_Detail_Product> arrayList = new ArrayList<Entity_Detail_Product>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject pol_xc = new JSONObject(jsonArray
.get(i).toString());
Entity_Detail_Product ent_detail_product = new Entity_Detail_Product();
ent_detail_product.setModel_name(pol_xc
.getString("model_name"));
arrayList.add(ent_detail_product);
}
pol_xc_Result.gotResult(arrayList, null, Action);
} else {
String error_message = jsonObject
.getString("message");
pol_xc_Result.gotResult(null, error_message,
Action);
}
} catch (JSONException e) {
// TODO: handle exception
pol_xc_Result.gotResult(null,
"Failed parsing data from database. Please try again.. "
+ e.getMessage(), Action);
Log.e("CON ERROR", e.getMessage());
}
}
} else {
pol_xc_Result.gotResult(null, message, Action);
Log.e("CON ERROR", message);
}
}
};
public static abstract class pol_xc_Result {
public abstract void gotResult(Object obj, String message, int action);
}
and here's my activity to call DAO.
public class Information_XC_Activity extends ListActivity {
WebView mWebView;
TextView tv;
private Adapter_DetailPolXC adapterDetailPolXC;
private ListView mainListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info_xc);
final ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
actionBar.setTitle(getString(R.string.app_name));
int index = getIntent().getIntExtra("text", 0);
mWebView = (WebView) findViewById(R.id.webview_xc);
String temp = "<html><body>" + "<p align=\"justify\">"
+ getString(R.string.xc_info + index) + "</p> "
+ "</body></html>";
mWebView.loadData(temp, "text/html", "utf-8");
ArrayList<Entity_Detail_Product> arraylist = new ArrayList<Entity_Detail_Product>();
adapterDetailPolXC = new Adapter_DetailPolXC(this, R.layout.info_row,
arraylist);
setListAdapter(adapterDetailPolXC);
new info_xc_dao(response).view_pol_xc();
}
pol_xc_Result response = new pol_xc_Result() {
#Override
public void gotResult(Object obj, String message, int action) {
// TODO Auto-generated method stub
// actionBar.setProgressBarVisibility(View.INVISIBLE);
#SuppressWarnings("unchecked")
ArrayList<Entity_Detail_Product> arrayList = (ArrayList<Entity_Detail_Product>) obj;
AlertDialog.Builder builder = new AlertDialog.Builder(
Information_XC_Activity.this);
if (arrayList == null) {
builder.setIcon(R.drawable.alert_warning);
builder.setTitle("Error");
builder.setMessage("Data Not Found !");
builder.setNegativeButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
for (Entity_Detail_Product entity_Detail_Product : arrayList) {
adapterDetailPolXC.add(entity_Detail_Product);
}
adapterDetailPolXC.notifyDataSetChanged();
}
}
};
private class Adapter_DetailPolXC extends
ArrayAdapter<Entity_Detail_Product> {
private ArrayList<Entity_Detail_Product> items;
public Adapter_DetailPolXC(Context context, int textViewResourceId,
ArrayList<Entity_Detail_Product> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if (v == null) {
LayoutInflater layoutInflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = (View) layoutInflater.inflate(R.layout.info_xc, null);
}
Entity_Detail_Product adapter_Detail_Product = items.get(position);
if (adapter_Detail_Product != null) {
TextView textView = (TextView) v.findViewById(R.id.tv_test);
if (textView != null)
textView.setText(adapter_Detail_Product.getModel_name());
}
return v;
}
}
and here's my logcat :
09-22 12:41:30.239: W/IInputConnectionWrapper(12808): showStatusIcon on inactive InputConnection
09-22 12:41:33.129: E/HttpResponse(12808): {"result":1,"data":[{"0":"1","id_brand":"1","1":"Polygon","brand_name":"Polygon"},{"0":"2","id_brand":"2","1":"United Bike","brand_name":"United Bike"},{"0":"3","id_brand":"3","1":"WimCycle","brand_name":"WimCycle"}]}
09-22 12:41:35.009: E/HttpResponse(12808): {"result":1,"data":[{"0":"1","id_type":"1","1":"Cross Country (XC)","type_name":"Cross Country (XC)"},{"0":"2","id_type":"2","1":"Bicycle Motocross (BMX)","type_name":"Bicycle Motocross (BMX)"},{"0":"3","id_type":"3","1":"Free Ride (FR)","type_name":"Free Ride (FR)"},{"0":"4","id_type":"4","1":"DownHill (DH)","type_name":"DownHill (DH)"},{"0":"5","id_type":"5","1":"DirtJump (DJ)","type_name":"DirtJump (DJ)"},{"0":"6","id_type":"6","1":"Road Bike (RB)","type_name":"Road Bike (RB)"}]}
09-22 12:41:37.219: D/PhoneWindow(12808): couldn't save which view has focus because the focused view com.android.internal.policy.impl.PhoneWindow$DecorView#405440f0 has no id.
09-22 12:41:37.519: I/webclipboard(12808): clipservice: android.sec.clipboard.ClipboardExManager#405d4d40
09-22 12:41:37.839: V/webview(12808): OnSizeChanged: Enter
09-22 12:41:37.859: E/HttpResponse(12808): {"result":1,"data":[{"0":"1","id_type":"1","1":"Cross Country (XC)","type_name":"Cross Country (XC)"},{"0":"2","id_type":"2","1":"Bicycle Motocross (BMX)","type_name":"Bicycle Motocross (BMX)"},{"0":"3","id_type":"3","1":"Free Ride (FR)","type_name":"Free Ride (FR)"},{"0":"4","id_type":"4","1":"DownHill (DH)","type_name":"DownHill (DH)"},{"0":"5","id_type":"5","1":"DirtJump (DJ)","type_name":"DirtJump (DJ)"},{"0":"6","id_type":"6","1":"Road Bike (RB)","type_name":"Road Bike (RB)"}]}
09-22 12:41:38.169: E/CON ERROR(12808): No value for model_name
09-22 12:41:38.859: V/webview(12808): ZoomScale 3 mPreserveZoom: false
09-22 12:41:38.889: D/CONTEXT(12808): m_mainFrame->editor()->hasComposition not
09-22 12:41:38.959: D/CONTEXT(12808): m_mainFrame->editor()->hasComposition not

Building a custom row on demand with GWT CellTableBuilder

In GWT 2.5 RC CellTableBuilder API was introduced but there are no comprehensive documentation available yet. Is there any tutorial\example of implementing on-demand custom row building with CellTableBuilder? The only example I've found so far was this one http://showcase2.jlabanca-testing.appspot.com/#!CwCustomDataGrid but it is quite confusing for me.
So, my goal is to create extra row containing widget that provides details about clicked row in a table.
I've found suitable solution for this problem. Here is the code sample:
public class CustomCellTableBuilder extends AbstractCellTableBuilder<Object>{
//here go fields, ctor etc.
//ids of elements which details we are going to show
private Set elements;
#Override
protected void buildRowImpl(Object rowValue, int absRowIndex){
//building main rows logic
if(elements.contains(absRowIndex)){
buildExtraRow(absRowIndex, rowValue);
elements.add(absRowIndex);
}
}
private void buildExtraRow(int index, Object rowValue){
TableRowBuilder row = startRow();
TableCellBuilder td = row.startTD().colSpan(getColumns().size());
DivBuilder div = td.startDiv();
Widget widget = new Widget();
//update widget state and appearance here depending on rowValue
div.html(SafeHtmlUtils.fromTrustedString(widget.getElement().getInnerHTML()));
div.end();
td.endTD();
row.endTR();
}}
It should be mentioned, that when you handle some event which leads to appearance of extra row, you should invoke redrawRaw(rowIndex) on CellTable which is attached to TableBuilder. And before this call it is necessary to add target row ID to elements Set.
Hope this was helpful.
I have created this class for expanding rows in GWT. It takes a column that you want to expand and replaces it with a place holder that can have 2 states.
I use it like this:
PlaceHolderColumn<Notification, SafeHtml> placeholder = new PlaceHolderColumn<Notification, SafeHtml>(new SafeHtmlCell()) {
#Override
public SafeHtml getValue(Notification object) {
return SafeHtmlUtils.fromSafeConstant(getSelected() ? "<i class=\"glyphicon glyphicon-chevron-down\"></i>"
: "<i class=\"glyphicon glyphicon-chevron-right\"></i>");
}
};
notificationsTable.setTableBuilder(new ExpandableCellTableBuilder<Notification, SafeHtml>(notificationsTable, columnBody, placeholder));
I have access to glyphicon so I use those instead of the default placeholder column which is +/-
< Image here... but for lack of reputation :( >
columnBody in the above code sample is just a standard column that will span the width of the table. The place holder will be displayed in its place in whatever position columnBody was configured to sit at.
Hope that helps someone :)
public class ExpandableCellTableBuilder<T, U> extends AbstractCellTableBuilder<T> {
private Column<T, U> expandColumn = null;
private PlaceHolderColumn<T, ?> placeholderColumn = null;
private final String evenRowStyle;
private final String oddRowStyle;
private final String selectedRowStyle;
private final String cellStyle;
private final String evenCellStyle;
private final String oddCellStyle;
private final String firstColumnStyle;
private final String lastColumnStyle;
private final String selectedCellStyle;
public static class ExpandMultiSelectionModel<T> extends AbstractSelectionModel<T> {
Map<Object, T> selected = new HashMap<Object, T>();
/**
* #param keyProvider
*/
public ExpandMultiSelectionModel(ProvidesKey<T> keyProvider) {
super(keyProvider);
}
/*
* (non-Javadoc)
*
* #see com.google.gwt.view.client.SelectionModel#isSelected(java.lang.Object)
*/
#Override
public boolean isSelected(T object) {
return isKeySelected(getKey(object));
}
protected boolean isKeySelected(Object key) {
return selected.get(key) != null;
}
/*
* (non-Javadoc)
*
* #see com.google.gwt.view.client.SelectionModel#setSelected(java.lang.Object, boolean)
*/
#Override
public void setSelected(T object, boolean selected) {
Object key = getKey(object);
if (isKeySelected(key)) {
this.selected.remove(key);
} else {
this.selected.put(key, object);
}
scheduleSelectionChangeEvent();
}
}
public static abstract class PlaceHolderColumn<T, C> extends Column<T, C> {
private boolean isSelected;
/**
* #param cell
*/
public PlaceHolderColumn(Cell<C> cell) {
super(cell);
}
protected boolean getSelected() {
return isSelected;
}
}
private int expandColumnIndex;
public ExpandableCellTableBuilder(AbstractCellTable<T> cellTable, Column<T, U> expandColumn) {
this(cellTable, expandColumn, new ExpandMultiSelectionModel<T>(cellTable.getKeyProvider()), null);
}
public ExpandableCellTableBuilder(AbstractCellTable<T> cellTable, Column<T, U> exandColumn, SelectionModel<T> selectionModel) {
this(cellTable, exandColumn, selectionModel, null);
}
public ExpandableCellTableBuilder(AbstractCellTable<T> cellTable, Column<T, U> exandColumn, PlaceHolderColumn<T, ?> placeHolder) {
this(cellTable, exandColumn, new ExpandMultiSelectionModel<T>(cellTable.getKeyProvider()), placeHolder);
}
/**
* #param cellTable
* #param columnBody
*/
public ExpandableCellTableBuilder(AbstractCellTable<T> cellTable, Column<T, U> expandColumn, SelectionModel<T> selectionModel,
PlaceHolderColumn<T, ?> placeHolder) {
super(cellTable);
this.expandColumn = expandColumn;
this.cellTable.setSelectionModel(selectionModel);
if (placeHolder == null) {
this.placeholderColumn = new PlaceHolderColumn<T, String>(new TextCell()) {
#Override
public String getValue(T object) {
return getSelected() ? "-" : "+";
}
};
} else {
this.placeholderColumn = placeHolder;
}
// Cache styles for faster access.
Style style = cellTable.getResources().style();
evenRowStyle = style.evenRow();
oddRowStyle = style.oddRow();
selectedRowStyle = " " + style.selectedRow();
cellStyle = style.cell();
evenCellStyle = " " + style.evenRowCell();
oddCellStyle = " " + style.oddRowCell();
firstColumnStyle = " " + style.firstColumn();
lastColumnStyle = " " + style.lastColumn();
selectedCellStyle = " " + style.selectedRowCell();
}
/*
* (non-Javadoc)
*
* #see com.google.gwt.user.cellview.client.AbstractCellTableBuilder#buildRowImpl(java.lang.Object, int)
*/
#Override
protected void buildRowImpl(T rowValue, int absRowIndex) {
// Calculate the row styles.
SelectionModel<? super T> selectionModel = cellTable.getSelectionModel();
final boolean isSelected = (selectionModel == null || rowValue == null) ? false : selectionModel.isSelected(rowValue);
boolean isEven = absRowIndex % 2 == 0;
StringBuilder trClasses = new StringBuilder(isEven ? evenRowStyle : oddRowStyle);
if (isSelected) {
trClasses.append(selectedRowStyle);
}
// Add custom row styles.
RowStyles<T> rowStyles = cellTable.getRowStyles();
if (rowStyles != null) {
String extraRowStyles = rowStyles.getStyleNames(rowValue, absRowIndex);
if (extraRowStyles != null) {
trClasses.append(" ").append(extraRowStyles);
}
}
// Build the row.
TableRowBuilder tr = startRow();
tr.className(trClasses.toString());
// Build the columns.
int columnCount = cellTable.getColumnCount();
for (int curColumn = 0; curColumn < columnCount; curColumn++) {
Column<T, ?> column = cellTable.getColumn(curColumn);
if (column == expandColumn) {
expandColumnIndex = curColumn;
column = placeholderColumn;
placeholderColumn.isSelected = isSelected;
}
// Create the cell styles.
StringBuilder tdClasses = new StringBuilder(cellStyle);
tdClasses.append(isEven ? evenCellStyle : oddCellStyle);
if (curColumn == 0) {
tdClasses.append(firstColumnStyle);
}
if (isSelected) {
tdClasses.append(selectedCellStyle);
}
// The first and last column could be the same column.
if (curColumn == columnCount - 1) {
tdClasses.append(lastColumnStyle);
}
// Add class names specific to the cell.
Context context = new Context(absRowIndex, curColumn, cellTable.getValueKey(rowValue));
String cellStyles = column.getCellStyleNames(context, rowValue);
if (cellStyles != null) {
tdClasses.append(" " + cellStyles);
}
// Build the cell.
HorizontalAlignmentConstant hAlign = column.getHorizontalAlignment();
VerticalAlignmentConstant vAlign = column.getVerticalAlignment();
TableCellBuilder td = tr.startTD();
td.className(tdClasses.toString());
if (hAlign != null) {
td.align(hAlign.getTextAlignString());
}
if (vAlign != null) {
td.vAlign(vAlign.getVerticalAlignString());
}
// Add the inner div.
DivBuilder div = td.startDiv();
div.style().outlineStyle(OutlineStyle.NONE).endStyle();
// Render the cell into the div.
renderCell(div, context, column, rowValue);
// End the cell.
div.endDiv();
td.endTD();
}
// End the row.
tr.endTR();
if (isSelected) {
buildExpandedRow(rowValue, absRowIndex, columnCount, trClasses, isEven, isSelected);
}
}
/**
* #param trClasses
*
*/
private void buildExpandedRow(T rowValue, int absRowIndex, int columnCount, StringBuilder trClasses, boolean isEven, boolean isSelected) {
TableRowBuilder tr = startRow();
tr.className(trClasses.toString());
Column<T, ?> column = expandColumn;
// Create the cell styles.
StringBuilder tdClasses = new StringBuilder(cellStyle);
tdClasses.append(isEven ? evenCellStyle : oddCellStyle);
tdClasses.append(firstColumnStyle);
if (isSelected) {
tdClasses.append(selectedCellStyle);
}
tdClasses.append(lastColumnStyle);
// Add class names specific to the cell.
Context context = new Context(absRowIndex, expandColumnIndex, cellTable.getValueKey(rowValue));
String cellStyles = column.getCellStyleNames(context, rowValue);
if (cellStyles != null) {
tdClasses.append(" " + cellStyles);
}
// Build the cell.
HorizontalAlignmentConstant hAlign = column.getHorizontalAlignment();
VerticalAlignmentConstant vAlign = column.getVerticalAlignment();
TableCellBuilder td = tr.startTD();
td.colSpan(columnCount);
td.className(tdClasses.toString());
if (hAlign != null) {
td.align(hAlign.getTextAlignString());
}
if (vAlign != null) {
td.vAlign(vAlign.getVerticalAlignString());
}
// Add the inner div.
DivBuilder div = td.startDiv();
div.style().outlineStyle(OutlineStyle.NONE).endStyle();
// Render the cell into the div.
renderCell(div, context, column, rowValue);
// End the cell.
div.endDiv();
td.endTD();
// End the row.
tr.endTR();
}