Adding items to TokenAutoComplete Android - android-edittext

I am using the TokenAutoComplete library for adding Gmail style chips to my textfield. Everything is working fine. The only problem is that i want to add items to my ChipTextView when the UI is loaded but i cannot find any way to do that. All the items that i add to adapter are displayed as suggestion instead.
My ChipTextView class:
public class ChipTextView extends TokenCompleteTextView {
public ChipTextView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public ChipTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public ChipTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
#Override
protected Object defaultObject(String text) {
return text;
}
#Override
protected View getViewForObject(Object text) {
String hashtag = (String) text;
LayoutInflater l = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout view = (LinearLayout) l.inflate(R.layout.chiptextview_item,
(ViewGroup) ChipTextView.this.getParent(), false);
((TextView) view.findViewById(R.id.tv_text)).setText(hashtag);
return view;
}
}
My fragment From where i am setting up ChipTextView :
ArrayList<String> list=new ArrayList<>();
list.add("hello");
list.add("hi");
list.add("how");
ChipTextView tv_chipview=(ChipTextView ) parentView.findViewById(R.id.tv_chipview);
ArrayAdapter<String> mAdapter;
mAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,list);
tv_chipview.setAdapter(mAdapter);
tv_chipview.allowDuplicates(false);
tv_chipview.setDeletionStyle(TokenDeleteStyle.Clear);
This is how it is shown when i add items to adapter using code
How i want the output to be displayed after setting up. This is how it is displayed when i use my keyboard:
How can i add items to ChipTextView from code so that it seems like i had added them by using keyboard ?

I found the solution to my problem on TokenAutoComplete github documentation. I don't know how i missed this before but i have finally found it. :)
For anyone who has faced the same problem i suggest you use addObject() method for adding items into ChipTextView.

Related

How to add converter to grid column in Vaadin 8?

I am using Vaadin 8 and I am facing a problem.
In my constructor, I create a grid which I add to a layout.
Grid<Row> grid = new Grid<>(); grid.removeAllColumns(); //Here, I add columns to the grid grid.addColumn(... grid.addColumn(… …
I then want to add a converter to my grid as follows:
grid.getColumn("delete").setConverter(new StringToUrlConverter("dustbin"));
What I do not understand is the error message indicating why I cannot add the converter. The error message is the folloing one:
The method setConverter(StringToUrlConverter) is undefined for the type >Grid.Column<ContactView.Row,capture#1-of ?>
So how do I have to set my converter?
This is my converter:
package com.example.vaadin;
import com.vaadin.data.Converter;
import com.vaadin.data.Result;
import com.vaadin.data.ValueContext;
public class StringToUrlConverter implements Converter<String, String> {
/**
*
*/
private static final long serialVersionUID = 1L;
String imagePath = "";
public StringToUrlConverter(String path) {
this.imagePath=path;
}
public String getImagePath() {
return imagePath;
}
#Override
public Result<String> convertToModel(String value, ValueContext context) {
return Result.ok(null);
}
#Override
public String convertToPresentation(String value, ValueContext context) {
if(value.equals("delete")) {
return "<span><img src='img/" + getImagePath() + ".jpg' width='20' height='20'></span>";
}
return "";
}
}
There is no setConverter method in Vaadin 8, it was in Vaadin 7. Instead in Vaadin 8 and newer versions you should use version of addColumn method with value provider. See old discussion in Vaadin's Forum.
StringToUrlConverter converter = new StringToUrlConverter (path);
grid.addColumn(row -> converter.convertToPresentation(row.getDelete(), String.class, ui.getLocale())).setCaption("Delete");
But, in your case you probably do not need that either. I see from your code that you simply want to add delete button or something like that in the Grid's cell.
You can add component in Grid from Vaadin 8 onwards using:
grid.addComponentColumn(row -> {
Image image = new Image();
image.setSrc(path);
image.addClickListener(event -> {
// add code to remove the row
grid.getDataProvider().refreshAll();
});
return image;
}

Binding between an Object and a SimpleIntegerProperty

I have a combo box over my GUI in JavaFX.
This Combo Box is composed of a complex type elements :
public class DureeChoiceBoxElement extends ObservableValueBase<DureeChoiceBoxElement> {
private IntegerProperty duree;
#Override
public String toString() {
return duree.get() + " an";
}
}
I want to map (or bind) the selected complex element with my model which contains the simple type :
public class Pel {
private IntegerProperty duree = new SimpleIntegerProperty(1);
public Property<Number> dureeProperty() {
return duree;
}
public void setDuree(Integer duree) {
this.duree.setValue(duree);
}
public Integer getDuree() {
return duree.getValue();
}
}
How to do it ?
I tried in the controller with :
public class PelController {
#FXML
private ChoiceBox<DureeChoiceBoxElement> duree;
//etc..
pel.dureeProperty().bind(createElapsedBindingByBindingsAPI2(duree.getValue()));
/*
* #return an ObjectBinding of immutable TimeElapsed objects for the player
*/
private ObjectBinding<Property<Number>> createElapsedBindingByBindingsAPI2(
final DureeChoiceBoxElement dureeChoiceBoxElement) {
return Bindings.createObjectBinding(new Callable<Property<Number>>() {
#Override
public IntegerProperty call() throws Exception {
return dureeChoiceBoxElement.dureeProperty();
}
}, dureeChoiceBoxElement.dureeProperty());
}
}
But it doesn't work (even not compile). I want to say that "Bind this simple property to this complex Object calling the method I give you through the method named "createElapsedBindingByBindingsAPI2(..)".
It is logical read but I didn't managed to make it works anyway.
That's poor ....
Any help please :).
Example that (obviously) works with legacy code style (Swing coding) :
duree.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<DureeChoiceBoxElement>() {
#Override
public void changed(ObservableValue<? extends DureeChoiceBoxElement> observable,
DureeChoiceBoxElement oldValue, DureeChoiceBoxElement newValue) {
// changement durée
log.debug("Durée sélectionnée : {}", duree.getSelectionModel().getSelectedItem().getDuree());
log.debug("Durée bindée ? : {}", pel.getDuree());
pel.setDuree(duree.getSelectionModel().getSelectedItem().getDuree());
}
});
Like this my model is set to selected item. But it implies some boilerplate code. Any better idea based on high level bindings of JavaFX ?

How to start a file download in vaadin without button?

I know that it is really easy to create a FileDownloader and call extend with a Button. But how do I start a download without the Button?
In my specific situation right now I have a ComboBox and the file I'd like to send to the user is generated after changing its value, based on the input. The file should be sent immediately without waiting for another click. Is that easily possible?
Thanks
raffael
I found a solution myself. Actually two.
The first one uses the deprecated method Page.open()
public class DownloadComponent extends CustomComponent implements ValueChangeListener {
private ComboBox cb = new ComboBox();
public DownloadComponent() {
cb.addValueChangeListener(this);
cb.setNewItemsAllowed(true);
cb.setImmediate(true);
cb.setNullSelectionAllowed(false);
setCompositionRoot(cb);
}
#Override
public void valueChange(ValueChangeEvent event) {
String val = (String) event.getProperty().getValue();
FileResource res = new FileResource(new File(val));
Page.getCurrent().open(res, null, false);
}
}
The javadoc here mentions some memory and security problems as reason for marking it deprecated
In the second I try to go around this deprecated method by registering the resource in the DownloadComponent. I'd be glad if a vaadin expert comments this solution.
public class DownloadComponent extends CustomComponent implements ValueChangeListener {
private ComboBox cb = new ComboBox();
private static final String MYKEY = "download";
public DownloadComponent() {
cb.addValueChangeListener(this);
cb.setNewItemsAllowed(true);
cb.setImmediate(true);
cb.setNullSelectionAllowed(false);
setCompositionRoot(cb);
}
#Override
public void valueChange(ValueChangeEvent event) {
String val = (String) event.getProperty().getValue();
FileResource res = new FileResource(new File(val));
setResource(MYKEY, res);
ResourceReference rr = ResourceReference.create(res, this, MYKEY);
Page.getCurrent().open(rr.getURL(), null);
}
}
Note: I do not really allow the user to open all my files on the server and you should not do that either. It is just for demonstration.
Here is my work-around. It works like a charm for me. Hope it will help you.
Create a button and hide it by Css (NOT by code: button.setInvisible(false))
final Button downloadInvisibleButton = new Button();
downloadInvisibleButton.setId("DownloadButtonId");
downloadInvisibleButton.addStyleName("InvisibleButton");
In your theme, add this rule to hide the downloadInvisibleButton:
.InvisibleButton {
display: none;
}
When the user clicks on menuItem: extend the fileDownloader to the downloadInvisibleButton, then simulate the click on the downloadInvisibleButton by JavaScript.
menuBar.addItem("Download", new MenuBar.Command() {
#Override
public void menuSelected(MenuBar.MenuItem selectedItem) {
FileDownloader fileDownloader = new FileDownloader(...);
fileDownloader.extend(downloadInvisibleButton);
//Simulate the click on downloadInvisibleButton by JavaScript
Page.getCurrent().getJavaScript()
.execute("document.getElementById('DownloadButtonId').click();");
}
});

AndroidAnnotations in CursorAdapter

I am developing for android using android annotations but I don't unterstand how to use it with CursorAdapters.
There is already a example for BaseAdapters, but if I add #EBean to a class that extents CursorAdapter I get the error message "#EBean annotated element should have a constructor with one parameter max, of type android.content.Context". CursorAdapter already has two constructors.
public class SongInfoAdapter extends CursorAdapter {
...
#Override
public void bindView(View view, Context context, Cursor cursor) {
...
rowData.id.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
itemOnClick(rowData);
}
});
}
public void itemOnClick(RowDataHolder rowData) {
switch(audioPlayer.getPlayingplayer()) {
case AudioPlayer.RIGHT:
case AudioPlayer.NONE:
audioPlayer.load(rowData.songInfo, AudioPlayer.LEFT);
break;
case AudioPlayer.LEFT:
audioPlayer.load(rowData.songInfo, AudioPlayer.RIGHT);
break;
}
}
...
}
AudioPlayer is a class that uses annotations (#EBean), but I can't write
#Bean
AudioPlayer audioPlayer;
because I can't use annotations in this class. How can I use AndroidAnnotations in CursorAdapter?
Many thanks in advance .
Create a constructor that takes one argument, the context.
SongInfoAdapter (Context context) {
super(context, null, FLAG_AUTO_REQUERY);
}
Create an init method and set the cursor for the adapter in init.
public void init(Cursor c) {
this.changeCursor(c);
}
Now you can annotate SongInfoAdapter with #EBean and use annotations.

How can i call dynamic object like a function?

I am studying orchard architecture.i have faced with a strange concept in display management section.
in Partial view page there is a 'function call like' syntax like so Display(Model.Head). that is not a function thought, it is a dynamic object defined in orchard WebViewPage.
I am wondering how to define a dynamic object so that you can call it (and pass it an argument as well) like a function as i mentioned.
thanks in advance.
A lighter weight way to do it without clay would be to subclass the built-in DynamicObject class.
public static dynamic Display;
void Main()
{
Display = new MyCallableObject();
//this is what i was after
Console.Write(Display("bla bla bla"));
}
public class MyCallableObject:DynamicObject
{
public override bool TryInvoke(InvokeBinder binder, object[] args, out Object result)
{
result = string.Format("This is response for {0}",args.FirstOrDefault());
return true;
}
}
I finally found it my self!
all the operations have done with Clay Library behind the scene.i have wrote a sample console app for demonstrating the process.
class Program
{
static void Main(string[] args)
{
Display = ClayActivator.CreateInstance<MyResponser>(new List<IClayBehavior> {new MyFunctionCallBehavior()});
//this is what i was after
Console.Write(Display("bla bla bla"));
}
public static dynamic Display;
}
public class MyFunctionCallBehavior : IClayBehavior
{
public object InvokeMember(Func<object> proceed, object self, string name, INamedEnumerable<object> args)
{
return ((MyResponser)self).ResponseForRequest(args.FirstOrDefault().ToString());
}
}
public class MyResponser
{
public string ResponseForRequest(string param)
{
return string.Format("This is response for {0}",param);
}
}

Resources