Vaadin, Table generated column value - vaadin

I use table component and generate column for optiongroup.
when change optionGroup's value, and click the save button,
the table get the before value - not changed value..
How to get the chaged value ? Not origin value.
here code...
public class MyTypeColumnGenerator implements ColumnGenerator{
public Object generateCell( Table source, Object itemId, Object columnId) {
BeanItem<MyType> beanItem = (BeanItem<MyType>)source.getItem(itemId);
MyType view = beanItem.getBean() ;
if(view.getValueType().equals(ValueType.Flag)){
// radio
OptionGroup opt = new OptionGroup() ;
opt.addItem(1) ; // y
opt.addItem(0) ; // n
opt.setItemCaption(1, Messages.getString(Messages.Opt_Y));
opt.setItemCaption(0, Messages.getString(Messages.Opt_N));
opt.setStyleName("horizontal");
if(view.getFactorValue() == 0){
opt.select(0);
}else if(view.getFactorValue() == 1){
opt.select(1);
}
return opt ;
}else{
Label label = new Label();
label.setValue("N/A");
return label;
}
}
}
btnSave.addClickListener(new ClickListener() {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public void buttonClick(ClickEvent event) {
Collection<?> items = table.getItemIds() ;
for (Object item : items) {
Property pName = table.getContainerProperty(item, "name");
Property pVal = table.getContainerProperty(item, "value");
}
pVal gets only origin value , not changes value.

You have to add a ValueChangeListener to the OptionGroup and inside the listener actually set the value on your MyType view using something like view.setValue(...).
Your code would then look something like that:
OptionGroup opt = new OptionGroup() ;
opt.addValueChangeListener(new Property.ValueChangeListener() {
#Override
public void valueChange (Property.ValueChangeEvent event){
view.setValue(event.getProperty().getValue());
}
});

Related

tableView Filter , no input in the table

The goal is to filter the tableView .So, when I input something to filter it works just fine , but then when I hit backspace or remove the inputs on the textField Area to go back,the tableView shows no content in the table ,Then I have to restart the program to reload and show the data.The data is saved and loaded from an xml file.
Also, I put an ObservaleList of contacts on the Data Class to load and store the contactList ,But on the Controller I have a similar list for the filter then the controller extends the data class to getContacts from there and add the filtredList to it. I am pretty much sure that the problem comes from that
public Data() {
contacts = FXCollections.observableArrayList();
}
public ObservableList<Contact> getContacts() {
return contacts;
}
This is below the filter handle
public void filterContactList(String oldValue, String newValue) {
ObservableList<Contact> filteredList = FXCollections.observableArrayList();
if (filterInput == null || newValue.length() < oldValue.length() || newValue == null){
contactsTable.setItems(getContacts());
}else {
newValue = newValue.toUpperCase();
for (Contact contact: contactsTable.getItems()){
String filterFirstName = contact.getFirstName();
String filterLastName = contact.getFirstName();
if (filterFirstName.toUpperCase().contains(newValue) || filterLastName.toUpperCase().contains(newValue)){
filteredList.add(contact);
}
}
contactsTable.setItems(filteredList);
}
}
and this is the init listener
filterInput.textProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
filterContactList((String) oldValue, (String) newValue);
}
});
Do yourself a favor an use FilteredList for this:
private FilteredList<Contact> filteredContacts = new FilteredList<>(getContacts());
...
contactsTable.setItems(filteredList);
...
public void filterContactList(String oldValue, String newValue) {
if (newValue == null) {
filteredContacts.setPredicate(null);
} else {
final String lower = newValue.toLowerCase();
filteredContacts.setPredicte(contact -> contact.getFirstName().toLowerCase().contains(lower) || contact.getLastName().toLowerCase().contains(lower));
}
}
BTW: since this is called from a listener to filterInput's textProperty, I removed the check for null.

Vaadin can't get combo box field value at 0 position

I'm trying to set field at index 0 in Vaadin combo box to default value, so I could avoid error message if user doesen't select anything. So I would like that instead of blank field I have populated field at index 0.
I have tried to set it and managed it with this:
field.setNullSelectionAllowed(true);
field.setNullSelectionItemId(container.getIdByIndex(0));
So I don't have blank value at index 0, instead my previous value of index 1 is now at index 0. And that is exactly what I want and need and in combo box looks just as I want.
But, unfortunately, when I submit my form, value is not passed. Only values after index 0 are passed. It's so frustrating, can somebody help me? Value passed to setNullSelectionItemId exists 100%.
How can I grab value from index at place 0 in combo box?
p.s. here is my code:
public Field<?> buildAndBindComboBox(final String caption, final BeanItemContainer<?> container,
final Object propertyId, final String title, final ValueChangeListener listener, final boolean nullAllowed,
final boolean required, final boolean enabled, final boolean visible) {
#SuppressWarnings("serial")
ComboBox field = new ComboBox(caption, container) {
// http://dev.vaadin.com/ticket/10544
// - typing in ComboBox causes Internal Error
private boolean inFilterMode;
#Override
public void containerItemSetChange(com.vaadin.data.Container.ItemSetChangeEvent event) {
if (inFilterMode) {
super.containerItemSetChange(event);
}
}
#Override
protected List<?> getOptionsWithFilter(boolean needNullSelectOption) {
try {
inFilterMode = true;
return super.getOptionsWithFilter(needNullSelectOption);
} finally {
inFilterMode = false;
}
}
};
field.setStyleName("comboBox");
field.setInputPrompt("Select");
if(defaultValue == true){
field.setNullSelectionAllowed(false);
field.setNullSelectionItemId(container.getIdByIndex(0).toString());
//field.select(container.getIdByIndex(0));
//field.setValue(container.getIdByIndex(0));
//field.setRequired(false);
defaultValue = false;
} else {
field.setNullSelectionAllowed(nullAllowed);
field.setRequired(required);
}
field.setImmediate(true);
field.setNewItemsAllowed(false);
field.setFilteringMode(FilteringMode.CONTAINS);
if (title != null) {
field.setItemCaptionPropertyId(title);
}
//field.setNullSelectionAllowed(nullAllowed);
//field.setRequired(required);
field.setVisible(visible);
if (listener != null) {
field.addValueChangeListener(listener);
}
this.bind(field, propertyId);
field.setEnabled(enabled);
return field;
}
public void setDefaultValueFirstItem(boolean def){
defaultValue = def;
}
It is binded like this:
commitmentFeeBinder.setDefaultValueFirstItem(true);
commitmentFeeBinder.buildAndBindComboBox("No working day labels", noWorkingDays, "noWorkingDaysCF", "title", null, false, !transaCF, true, !transaCF);
If I understood your question correctly, Steffen Harbich is correct in suggesting that if you want the first item to be selected by default you should disable null selection and select the first item by default. E.g. this works:
ComboBox cb = new ComboBox("", Arrays.asList("First", "Second", "Third"));
cb.setNullSelectionAllowed(false);
cb.select("First");
Or alternatively with a BeanItemContainer:
List<MyBean> beans = Arrays.asList(new MyBean("First"), new MyBean("Second"), new MyBean("Third"));
BeanItemContainer<MyBean> bic = new BeanItemContainer<>(MyBean.class, beans);
ComboBox cb = new ComboBox("", bic);
cb.setNullSelectionAllowed(false);
cb.select(bic.getIdByIndex(0));
private void resetComboBoxToIndex(ComboBox combo, int index) {
BeanItemContainer<Bean_ComboBox> items_combo = (BeanItemContainer<Bean_ComboBox>)combo.getContainerDataSource();
if(items_combo != null && items_combo.size() > index) {
Bean_ComboBox primerItem = items_combo.getIdByIndex(index);
if(primerItem != null) {
combo.select(primerItem);
}
}
}

ContactsContract.CommonDataKinds.Phone CONTENT_FILTER_URI is not loading correct data

I'm trying to list all the available phone numbers with display name from contacts app in a ListView with search. Also if a contact has more than one phone number, it has to be displayed in separate list item (as different contact not as same contact in Contacts App).
I've successfully retrived all the phone numbers with display name and displayed in ListView. Multiple phone numbers of a contact also displayed as separate contact.
But, when I search - either it gives irrelevant phone number for the display name or it fails to filter when I entered single character. Please suggest on this.
Here is my code:
public class ContactsListFragment extends ListFragment implements
AdapterView.OnItemClickListener, LoaderManager.LoaderCallbacks<Cursor> {
// Defines a tag for identifying log entries
private static final String TAG = "ContactsListFragment";
private ContactsAdapter mAdapter; // The main query adapter
private String mSearchTerm; // Stores the current search query term
// Contact selected listener that allows the activity holding this fragment to be notified of
// a contact being selected
private OnContactsInteractionListener mOnContactSelectedListener;
/**
* Fragments require an empty constructor.
*/
public ContactsListFragment() {}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
// Let this fragment contribute menu items
setHasOptionsMenu(true);
// Create the main contacts adapter
mAdapter = new ContactsAdapter(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
// Inflate the list fragment layout
return inflater.inflate(R.layout.contact_list_fragment, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
// Set up ListView, assign adapter and set some listeners. The adapter was previously
// created in onCreate().
setListAdapter(mAdapter);
getListView().setOnItemClickListener(this);
getListView().setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
try{
// Assign callback listener which the holding activity must implement. This is used
// so that when a contact item is interacted with (selected by the user) the holding
// activity will be notified and can take further action such as extracting the contact
//details and pass it to AddNewUserDialogFragment
mOnContactSelectedListener = (OnContactsInteractionListener) activity;
}catch(ClassCastException e){
throw new ClassCastException(activity.toString()
+ " must implement OnContactsInteractionListener");
}
}
#Override
public void onPause(){
super.onPause();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// Gets the Cursor object currently bound to the ListView
final Cursor cursor = mAdapter.getCursor();
// Moves to the Cursor row corresponding to the ListView item that was clicked
cursor.moveToPosition(position);
final String displayName = cursor.getString(ContactMobileNumbQuery.DISPLAY_NAME);
final String mobileNumb = cursor.getString(ContactMobileNumbQuery.NUMBER);
mOnContactSelectedListener.onContactSelected(displayName, mobileNumb);
}
/**
* Called when ListView selection is cleared, for example
* when search mode is finished and the currently selected
* contact should no longer be selected.
*/
private void onSelectionCleared() {
// Uses callback to notify activity this contains this fragment
mOnContactSelectedListener.onSelectionCleared();
// Clears currently checked item
getListView().clearChoices();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
// Inflate the menu items
inflater.inflate(R.menu.contact_list_menu, menu);
// Locate the search item
MenuItem searchItem = menu.findItem(R.id.menu_search);
//sets up and configures the ActionBar SearchView
final SearchManager mSearchManager = (SearchManager)getActivity().getSystemService(Context.SEARCH_SERVICE);
// Retrieves the SearchView from the search menu item
final SearchView mSearchView = (SearchView) searchItem.getActionView();
// Assign searchable info to SearchView
mSearchView.setSearchableInfo(mSearchManager.getSearchableInfo(getActivity().getComponentName()));
// Set listeners for SearchView
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// Called when the action bar search text has changed. Updates
// the search filter, and restarts the loader to do a new query
// using the new search string.
String newFilter = !TextUtils.isEmpty(newText) ? newText : null;
// Don't do anything if the filter is empty
if(mSearchTerm == null && newText == null){
return true;
}
// Don't do anything if the new filter is the same as the current filter
if(mSearchTerm != null && mSearchTerm.equals(newText)){
return true;
}
// Updates current filter to new filter
mSearchTerm = newFilter;
// Restarts the loader. This triggers onCreateLoader(), which builds the
// necessary content Uri from mSearchTerm.
getLoaderManager().restartLoader(ContactMobileNumbQuery.QUERY_ID, null, ContactsListFragment.this);
return true;
}
});
searchItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Nothing to do when the action item is expanded
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// When the user collapses the SearchView the current search string is
// cleared and the loader restarted.
if(!TextUtils.isEmpty(mSearchTerm)){
onSelectionCleared();
}
mSearchTerm = null;
getLoaderManager().restartLoader(ContactMobileNumbQuery.QUERY_ID, null, ContactsListFragment.this);
return true;
}
});
getLoaderManager().restartLoader(ContactMobileNumbQuery.QUERY_ID, null, ContactsListFragment.this);
}
#Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
if(!TextUtils.isEmpty(mSearchTerm)){
// Saves the current search string
outState.putString(SearchManager.QUERY, mSearchTerm);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
return super.onOptionsItemSelected(item);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.i(TAG, "onCreateLoader starts");
//If this is the loader for finding contacts in the Contacts Provider
if(id == ContactMobileNumbQuery.QUERY_ID){
Uri contentUri;
// There are two types of searches, one which displays all contacts and
// one which filters contacts by a search query. If mSearchTerm is set
// then a search query has been entered and the latter should be used.
if(mSearchTerm == null){
// Since there's no search string, use the content URI that searches the entire
// Contacts table
contentUri = ContactMobileNumbQuery.CONTENT_URI;
}else{
// Since there's a search string, use the special content Uri that searches the
// Contacts table. The URI consists of a base Uri and the search string.
contentUri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(mSearchTerm));
}
// Returns a new CursorLoader for querying the Contacts table. No arguments are used
// for the selection clause. The search string is either encoded onto the content URI,
// or no contacts search string is used. The other search criteria are constants. See
// the ContactsQuery interface.
return new CursorLoader(getActivity(),
contentUri,
ContactMobileNumbQuery.PROJECTION,
ContactMobileNumbQuery.SELECTION,
null,
ContactMobileNumbQuery.SORT_ORDER);
}
Log.e(TAG, "onCreateLoader - incorrect ID provided (" + id + ")");
return null;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// This swaps the new cursor into the adapter.
if(loader.getId() == ContactMobileNumbQuery.QUERY_ID){
mAdapter.swapCursor(data);
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
if(loader.getId() == ContactMobileNumbQuery.QUERY_ID){
// When the loader is being reset, clear the cursor from the adapter. This allows the
// cursor resources to be freed.
mAdapter.swapCursor(null);
}
}
/**
* This is a subclass of CursorAdapter that supports binding Cursor columns to a view layout.
* If those items are part of search results, it will be bind to the view layout.
*/
private class ContactsAdapter extends CursorAdapter implements SectionIndexer {
private LayoutInflater mInflater; // Stores the layout inflater
private TextAppearanceSpan highlightTextSpan; // Stores the highlight text appearance style
/**
* Instantiates a new Contacts Adapter.
* #param context A context that has access to the app's layout.
*/
public ContactsAdapter(Context context) {
super(context, null, 0);
// Stores inflater for use later
mInflater = LayoutInflater.from(context);
}
#Override
public Object[] getSections() {
// TODO Auto-generated method stub
return null;
}
#Override
public int getPositionForSection(int section) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getSectionForPosition(int position) {
// TODO Auto-generated method stub
return 0;
}
/**
* Binds data from the Cursor to the provided view.
*/
#Override
public void bindView(View view, Context context, Cursor cursor) {
// Gets handles to individual view resources
final ViewHolder holder = (ViewHolder) view.getTag();
final String displayName = cursor.getString(ContactMobileNumbQuery.DISPLAY_NAME);
final String mobileNumb = cursor.getString(ContactMobileNumbQuery.NUMBER);
final int startIndex = indexOfSearchQuery(displayName);
if (startIndex == -1) {
// If the user didn't do a search, or the search string didn't match a display
// name, show the display name without highlighting
holder.text1.setText(displayName);
holder.mobile_text.setText(mobileNumb);
if (TextUtils.isEmpty(mSearchTerm)) {
} else {
}
}else {
// If the search string matched the display name, applies a SpannableString to
// highlight the search string with the displayed display name
// Wraps the display name in the SpannableString
final SpannableString highlightedName = new SpannableString(displayName);
// Sets the span to start at the starting point of the match and end at "length"
// characters beyond the starting point
highlightedName.setSpan(highlightTextSpan, startIndex,
startIndex + mSearchTerm.length(), 0);
// Binds the SpannableString to the display name View object
holder.text1.setText(highlightedName);
}
}
private int indexOfSearchQuery(String displayName) {
if (!TextUtils.isEmpty(mSearchTerm)) {
return displayName.toLowerCase(Locale.getDefault()).indexOf(
mSearchTerm.toLowerCase(Locale.getDefault()));
}
return -1;
}
/**
* Overrides newView() to inflate the list item views.
*/
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
// Inflates the list item layout.
final View itemLayout = mInflater.inflate(R.layout.contacts_list_view_item, viewGroup,false);
// Creates a new ViewHolder in which to store handles to each view resource. This
// allows bindView() to retrieve stored references instead of calling findViewById for
// each instance of the layout.
final ViewHolder holder = new ViewHolder();
holder.text1 = (TextView) itemLayout.findViewById(android.R.id.text1);
holder.text2 = (TextView) itemLayout.findViewById(android.R.id.text2);
holder.mobile_text = (TextView) itemLayout.findViewById(R.id.mobile_text);
// Stores the resourceHolder instance in itemLayout. This makes resourceHolder
// available to bindView and other methods that receive a handle to the item view.
itemLayout.setTag(holder);
// Returns the item layout view
return itemLayout;
}
}
/**
* A class that defines fields for each resource ID in the list item layout. This allows
* ContactsAdapter.newView() to store the IDs once, when it inflates the layout, instead of
* calling findViewById in each iteration of bindView.
*/
private class ViewHolder {
TextView text1;
TextView text2;
TextView mobile_text;
}
/**
* This interface must be implemented by any activity that loads this fragment. When an
* interaction occurs, such as touching an item from the ListView, these callbacks will
* be invoked to communicate the event back to the activity.
*/
public interface OnContactsInteractionListener {
/**
* Called when a contact is selected from the ListView.
* #param contactUri The contact Uri.
*/
public void onContactSelected(String name, String mobile);
/**
* Called when the ListView selection is cleared like when
* a contact search is taking place or is finishing.
*/
public void onSelectionCleared();
// Uses callback to notify activity this contains this fragment
}
/**
* This interface defines constants used by mobile number retrieval queries.
*/
public interface ContactMobileNumbQuery{
final static int QUERY_ID = 1;
//A Content Uri for Phone table
final static Uri CONTENT_URI = Phone.CONTENT_URI;
//The search or filter query Uri
final static Uri FILTER_URI = Phone.CONTENT_FILTER_URI;
final static String SELECTION = Phone.HAS_PHONE_NUMBER + "=1" + " AND " + Phone.DISPLAY_NAME_PRIMARY + "<>''";
final static String SORT_ORDER = Phone.SORT_KEY_PRIMARY;
final static String[] PROJECTION = {
Phone._ID,
Phone.DISPLAY_NAME_PRIMARY,
Phone.LOOKUP_KEY,
Phone.HAS_PHONE_NUMBER,
Phone.NUMBER,
Phone.TYPE,
SORT_ORDER
};
final static int ID = 0;
final static int DISPLAY_NAME = 1;
final static int LOOKUP_KEY = 2;
final static int HAS_PHONE = 3;
final static int NUMBER = 4;
final static int TYPE = 5;
}
}
Can somebody help me to fix it? Thanks in advance!
The below code fixes my issue.
#Override
public void bindView(View view, Context context, Cursor cursor) {
// Gets handles to individual view resources
final ViewHolder holder = (ViewHolder) view.getTag();
final String displayName = cursor.getString(ContactMobileNumbQuery.DISPLAY_NAME);
final String mobileNumb = cursor.getString(ContactMobileNumbQuery.NUMBER);
holder.text1.setText(displayName);
holder.mobile_text.setText(mobileNumb);
}

Blackberry - Clickable BitmapField With Different ID's

i'm creating one application in which i get gift images with id's from web server through JSON. When i click on any gift image, it goes on next page where it shows all information of that image (get image information with its id from web server through JSON).
Problem is: When i click on any gift image on page to see its relevant information, it gets the last gift image id every time, i want when i click on any image, it gets the specific image id which i click. How it is possible??
Screenshot of the page is : http://ugo.offroadstudios.com/gifts.png
Here is sample code:
public class Gifts extends MainScreen {
String giftsid;
BitmapField giftimg;
public Gifts(){
setTitle("Gift Store");
creategifts();
}
public void creategifts()
{
//Link URL
String strURL = "http://ugo.offroadstudios.com/api/frndgift/?loginusername=adil;deviceside=true";
webConnection wb = new webConnection();
String res = wb.getJson(strURL);
try {
JSONObject object = new JSONObject(res);
if(object.getString("status") == "error")
{
Dialog.alert("Invalid "+object.getString("status"));
}
else
{
int totalgifts;
totalgifts = object.getInt("totalgifts");
Bitmap listThumb;
JSONArray imagearr;
JSONArray giftsidarr;
String imgname;
Bitmap bmpResized;
for(int i=0; i < totalgifts; i++){
imagearr = object.getJSONArray("gifts_image");
imgname = imagearr.getString(i);
giftsidarr = object.getJSONArray("gifts_id");
giftsid = giftsidarr.getString(i);
listThumb = getImage.getImageFromUrl("http://ugo.offroadstudios.com/wp-content/plugins/bp-gifts-rebirth/includes/images/"+imgname+";deviceside=true");
bmpResized = GPATools.ResizeTransparentBitmap(listThumb, 80, 80,
Bitmap.FILTER_LANCZOS, Bitmap.SCALE_TO_FIT);
giftimg =new BitmapField(bmpResized,FOCUSABLE)
{
protected boolean navigationClick(int status, int time)
{
Dialog.alert("giftsid "+giftsid);
UiApplication.getUiApplication().pushScreen(new SendGift(giftsid));
return true;
}
};
add(giftimg);
}
}
}
catch (JSONException e) {
System.out.println("EX is "+e);
e.printStackTrace();
}
}
}
You are always getting the gift id of the last gift in the list because you have created your buttons with this code:
giftimg =new BitmapField(bmpResized,FOCUSABLE)
{
protected boolean navigationClick(int status, int time)
{
Dialog.alert("giftsid "+giftsid);
UiApplication.getUiApplication().pushScreen(new SendGift(giftsid));
return true;
}
};
Your navigationClick() method used the giftsid variable, which is a persistent member variable of your class. You assign this variable in your for loop, so the final value it keeps is the last value assigned in the loop (giftsidarr.getString(totalgifts)).
Although you declare the navigationClick() method in a loop where the giftsid is many different values, the navigationClick() method uses the value of giftsid when it is run. The last value.
There's many ways to fix it. You can use a separate constant value in your loop:
final String nextGiftsId = giftsid;
giftimg =new BitmapField(bmpResized,FOCUSABLE)
{
protected boolean navigationClick(int status, int time)
{
Dialog.alert("nextGiftsId= "+nextGiftsId);
UiApplication.getUiApplication().pushScreen(new SendGift(nextGiftsId));
return true;
}
};
Or, as Signare suggested, attach a cookie to each button that identifies its corresponding gift:
giftimg =new BitmapField(bmpResized,FOCUSABLE)
{
protected boolean navigationClick(int status, int time)
{
String giftId = (String)getCookie(); // read gift id from the cookie
Dialog.alert("giftId= "+giftId);
UiApplication.getUiApplication().pushScreen(new SendGift(giftId));
return true;
}
};
giftimg.setCookie(giftsid); // set the cookie after creating the field
Inside your for loop, add the following code -
giftimg[i].setChangeListener(this);
Then -
public void fieldChanged(Field field, int context) {
for(int i=0;i<totalgifts;i++) {
if(field == giftimg[i]) {
// you can trigger your event
}
}
EDIT :-
giftimg[i].setChangeListener(listener);
listener = new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if ( field instanceof BitmapField ) {
for(int i=0;i<totalgifts;i++) {
if ( field == giftimg[i] ) {
// you can trigger your event
}
}
}
}
};

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