Fill JavaFX combobox by javascript class (Nashorn) - javafx

I try to use my custom class which I have created in my script (the script is written in Nashorn) and after that I try to use this custom class to fill in as items in combobox. I know that if I want to see correct values in combobox that the class has to override method toString, but in this case I do not know much how can be overriden this method in my custom class written in Nahorn.
Below I provide my code where the variables cmbCategories is JavaFX combobox and CategoryItem which I try to use as object to fill in the items in combobox and display as category name.
I would appreciate any suggestion or ideas how can be this problem resolved.
var ClientBuilder = Java.type("javax.ws.rs.client.ClientBuilder")
var Platform = Java.type("javafx.application.Platform")
var Executors = Java.type("java.util.concurrent.Executors")
var Response = Java.type("javax.ws.rs.core.Response")
var String = Java.type("java.lang.String")
var List = Java.type("java.util.ArrayList")
Executors.newSingleThreadExecutor().execute(function () {
print("Calling for category data...")
var categoryData = ClientBuilder
.newClient()
.target(String.format("%s%s", "http://localhost:8080", "/client/action/categories"))
.request()
.get()
if(categoryData.getStatus() == Response.Status.OK.getStatusCode()) {
var categories = JSON.parse(categoryData.readEntity(String.class))
var categoryItems = new List();
for each (var category in categories) {
categoryItems.add(new CategoryItem(category.id, category.category))
}
Platform.runLater(function() {
cmbCategory.getItems().addAll(categoryItems);
});
} else {
print(categoryData.getEntity().toString());
}
})
function CategoryItem(id, name) {
this.id = id;
this.name = name;
this.toString = function () {
return this.name;
}
}

Use the ScriptEngine to retrieve an appropriate string in the cellValueFactory of the ComboBox.
Simplified example
#Override
public void start(Stage primaryStage) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
final ScriptEngine engine = manager.getEngineByMimeType("application/javascript");
ComboBox<Object> comboBox = new ComboBox();
comboBox.setCellFactory(c -> new ListCell<Object>() {
#Override
protected void updateItem(Object item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText("");
} else {
Bindings bindings = new SimpleBindings();
bindings.put("a", item);
try {
// use script engine to retrieve text
setText(Objects.toString(engine.eval("a.name", bindings)));
} catch (ScriptException ex) {
setText("Error");
}
}
}
});
comboBox.setButtonCell(comboBox.getCellFactory().call(null));
Bindings b = new SimpleBindings();
b.put("cmbCategory", comboBox);
engine.eval("function CategoryItem(id, name) {this.id = id;this.name = name;}\n"
+"var Platform = Java.type(\"javafx.application.Platform\")\n"
+ "var categories = [new CategoryItem(1, 'a'), new CategoryItem(2, 'b'), new CategoryItem(3,'c')]\n"
+ "for each (var category in categories) {cmbCategory.getItems().add(category);}", b);
Scene scene = new Scene(new StackPane(comboBox));
primaryStage.setScene(scene);
primaryStage.show();
}
I don't see the purpose of using JavaScript for this though. Everything you do in the javascript code could be done from java code more efficiently...

Related

make a search in recylerview

I want to make a search on recyclerview, but the data appears if the phone is turned off and then turned on again, why is that?
the example photo
the app
When i'm search the recylerview is blank
but when the phones turned off and then turn on again, the data is appear
here's the code in fragment class
//search
editText = view.findViewById(R.id.searchServant);
searchButton = view.findViewById(R.id.button2);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String s = editText.getText().toString();
firebaseSearch(s);
}
});
//RecylerviewDatabaseServant
recyclerViewdatabase = view.findViewById(R.id.recyclerViewServant);
mManager = new LinearLayoutManager(getContext());
recyclerViewdatabase.setLayoutManager(mManager);
FirebaseRecyclerOptions<Servant> options =
new FirebaseRecyclerOptions.Builder<Servant>().setQuery(FirebaseDatabase.getInstance().getReference().child("Servant")
, Servant.class)
.build();
servantAdapter = new ServantAdapter(options);
recyclerViewdatabase.setAdapter(servantAdapter);
//End
here the function firebase search
private void firebaseSearch(String s) {
FirebaseRecyclerOptions<Servant> options = new FirebaseRecyclerOptions.Builder<Servant>().setQuery(FirebaseDatabase.getInstance()
.getReference().child("Servant").orderByChild("name").startAt(s).endAt(s + "\uf8ff"), Servant.class).build();
servantAdapter = new ServantAdapter(options);
recyclerViewdatabase.setAdapter(servantAdapter);
}
Try add this line in You search query
private void firebaseSearch(String s) {
FirebaseRecyclerOptions<Servant> options = new FirebaseRecyclerOptions.Builder<Servant>().setQuery(FirebaseDatabase.getInstance()
.getReference().child("Servant").orderByChild("name").startAt(s).endAt(s + "\uf8ff"), Servant.class).build();
servantAdapter = new ServantAdapter(options);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager({**context**}));
recyclerViewdatabase.setAdapter(servantAdapter);
servantAdapter.startListening();
}

Can I use ClassId in tabbedpage to differentiate their content

I'm trying to use the same page for 3 tabs in TabbedPage. But each tab has to display different data in the listview. Is there a way to set a parameter for each tab?
Example
<local:Sales Title="Pending"
Icon="ic_shortcut_home.png"
ClassId="pending"/>
<local:Sales Title="Posted"
Icon="ic_shortcut_home.png"
ClassId="posted"/>
<local:Sales Title="Uploaded"
Icon="ic_shortcut_home.png"
ClassId="uploaded"/>
I tried using ClassId, and Title to get their difference but I'm having trouble retrieving the ClassId in the Sales class constructor, are there any other ways to get the output I want?
public Sales()
{
InitializeComponent();
BindingContext = this;
salesCollection = new ObservableCollection<Head>();
initLvw();
Console.WriteLine(Title); //returns null
Console.WriteLine(ClassId); // returns null
}
You can load data in OnAppearing method:
protected override void OnAppearing()
{
base.OnAppearing();
Console.WriteLine(ClassId + "OnAppearing");
BindingContext = this;
salesCollection = new ObservableCollection<Head>();
initLvw();
}
Or load data with a little delay in constructor:
public AboutPage()
{
InitializeComponent();
Task.Run(async () =>
{
await Task.Delay(200);
Console.WriteLine(ClassId + "AboutPage");
BindingContext = this;
salesCollection = new ObservableCollection<Head>();
initLvw();
});
}

Caliburn Micro: How to add text to the bottom of a list box and display it

I'm trying to figure out how to add text to the bottom of a list box and display it. In WPF with code behind, I would grab the ScrollViewer and manipulate it, but I can't figure out how to do it with Caliburn...
You have a couple options.
1) In your ViewModel you can call GetView and cast it to your view type and get a reference to the ScrollViewer. Something like:
var myView = this.GetView() as MyView;
var myScrollView = myView.MyScrollView;
That works fine but isn't ideal if you're trying to not couple the view to the view model.
Option 2) is to implement IResult, see docs here.
public class ScrollViewResult : IResult
{
public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
private ScrollViewResult ()
{
}
public void Execute (ActionExecutionContext context)
{
var view = context.View as FrameworkElement;
var scrollViewer = FindVisualChild<ScrollViewer>(view);
//do stuff to scrollViewer here
Completed (this, new ResultCompletionEventArgs { });
}
private static TChildItem FindVisualChild<TChildItem> (DependencyObject obj)
where TChildItem : DependencyObject
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount (obj); i++)
{
var child = VisualTreeHelper.GetChild (obj, i);
if (child != null && child is TChildItem)
return (TChildItem)child;
var childOfChild = FindVisualChild<TChildItem> (child);
if (childOfChild != null)
return childOfChild;
}
return null;
}
//this isn't required of course but comes in handy for
//having a static method and passing parameters to the
//ctor of the IResult
public static IResult DoSomething ()
{
return new ScrollViewResult ();
}
Then you can call it like:
public IEnumerable<IResult> SomeAction()
{
yield return ScrollViewResult.DoSomething();
}

Data displayed redundantly on my UITableView in monotouch

I have problem in populating a table in monotouch using SQLite as database. My problem is it only selects the last data inserted and returns it as many as the number of data in the table selected.
ex. data=iPhone, number of data in a table = 30.
it returns the iPhone in the table 30 times.
Here is the code:
MainViewController
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
LoadToolbarButtons ();
LoadNavigationBarButtons ();
BL.Products MyProducts = new BL.Products();
List<Products> productList = new List<Products>();
POSDB.InitPOSDatabase ();
POSDB.GetAllProducts (productList, MyProducts);
tblProductList.Source = new ProductListDataSource(productList);
tblProductList.Delegate = new ProductListDelegate();
}
DataSource
public class ProductListDataSource : UITableViewSource
{
public List<Products> ProductList = new List<Products>();
public BL.Products myProducts = new BL.Products();
public ProductListDataSource(List<Products> productList):base()
{
this.ProductList = productList;
}
#region implemented abstract members of MonoTouch.UIKit.UITableViewSource
public override int RowsInSection (UITableView tableview, int section)
{
if (ProductList.Count == 0)
{
UIAlertView alert = new UIAlertView ("No Records!", "Please add some items to your table.", null, "OK", null);
alert.Show ();
}
return ProductList.Count;
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
string cellIdentifier = "Cell";
UITableViewCell cellProduct = tableView.DequeueReusableCell(cellIdentifier);
if (cellProduct == null)
{
cellProduct = new UITableViewCell(UITableViewCellStyle.Value1,cellIdentifier);
}
var products = this.ProductList[indexPath.Row];
cellProduct.TextLabel.Text =string.Format("({0}) {1}", products.ProductID, products.ProductName);
cellProduct.DetailTextLabel.Text = "$" + System.Convert.ToString(products.Price);
return cellProduct;
}
#endregion
}
Is there something wrong with my codes?
Thank you in advance!

How to map lists with ValueInjector

I am using ASP.NET MVC 3.
Can someone please help me clarify what's happening here:
var person = new PersonRepository().Get();
var personViewModel = new PersonViewModel();
personViewModel.InjectFrom<LoopValueInjection>(person)
.InjectFrom<CountryToLookup>(person);
I have a grid on my Index view. Each row is an instance of a CategoryViewModel. So what I do is to get a list of all the categories and then map each Category to a CategoryViewModel, and then pass this list of CategoryViewModels to the view. Hou would I do a mapping like that?
IEnumerable<Category> categoryList = categoryService.GetAll();
I thought the following would work but it doesn't:
// Mapping
IList<CategoryViewModel> viewModelList = new List<CategoryViewModel>();
viewModelList.InjectFrom(categoryList);
AFAIK value injecter doesn't support automatic collection mapping like AutoMapper but you could use a simple LINQ expression and operate on each element:
IEnumerable<Category> categoryList = categoryService.GetAll();
IList<CategoryViewModel> viewModelList = categoryList
.Select(x => new CategoryViewModel().InjectFrom(x)).Cast<CategoryViewModel>()
.ToList();
//source list
IEnumerable<string> items = new string[] { "1", "2" };
// target list
List<int> converted = new List<int>();
// inject all
converted.InjectFrom(items);
And the extension method:
public static ICollection<TTo> InjectFrom<TFrom, TTo>(this ICollection<TTo> to, IEnumerable<TFrom> from) where TTo : new()
{
foreach (var source in from)
{
var target = new TTo();
target.InjectFrom(source);
to.Add(target);
}
return to;
}
ICollection<T> is the interface that got least features but a Add method.
Update
An example using more proper models:
var persons = new PersonRepository().GetAll();
var personViewModels = new List<PersonViewModel>();
personViewModels.InjectFrom(persons);
Update - Inject from different sources
public static ICollection<TTo> InjectFrom<TFrom, TTo>(this ICollection<TTo> to, params IEnumerable<TFrom>[] sources) where TTo : new()
{
foreach (var from in sources)
{
foreach (var source in from)
{
var target = new TTo();
target.InjectFrom(source);
to.Add(target);
}
}
return to;
}
Usage:
var activeUsers = new PersonRepository().GetActive();
var lockedUsers = new PersonRepository().GetLocked();
var personViewModels = new List<PersonViewModel>();
personViewModels.InjectFrom(activeUsers, lockedUsers);
Use this function definition
public static object InjectCompleteFrom(this object target, object source)
{
if (target.GetType().IsGenericType &&
target.GetType().GetGenericTypeDefinition() != null &&
target.GetType().GetGenericTypeDefinition().GetInterfaces() != null &&
target.GetType().GetGenericTypeDefinition().GetInterfaces()
.Contains(typeof(IEnumerable)) &&
source.GetType().IsGenericType &&
source.GetType().GetGenericTypeDefinition() != null &&
source.GetType().GetGenericTypeDefinition().GetInterfaces() != null &&
source.GetType().GetGenericTypeDefinition().GetInterfaces()
.Contains(typeof(IEnumerable)))
{
var t = target.GetType().GetGenericArguments()[0];
var tlist = typeof(List<>).MakeGenericType(t);
var addMethod = tlist.GetMethod("Add");
foreach (var sourceItem in source as IEnumerable)
{
var e = Activator.CreateInstance(t).InjectFrom<CloneInjection>(sourceItem);
addMethod.Invoke(target, new[] { e });
}
return target;
}
else
{
return target.InjectFrom(source);
}
}
For those like me who prefer shortest notations possible
public static ICollection<TTarget> InjectFromList<TTarget, TOrig>(this ICollection<TTarget> target, ICollection<TOrig> source) where TTarget : new()
{
source.Select(r => new TTarget().InjectFrom(r))
.Cast<TTarget>().ToList().ForEach(e => target.Add(e));
return target;
}
public static ICollection<TTarget> InjectFromList<TTarget, TOrig>(this ICollection<TTarget> target, params ICollection<TOrig>[] sources) where TTarget : new()
{
sources.ToList().ForEach(s => s.ToList().Select(r => new TTarget().InjectFrom(r))
.Cast<TTarget>().ToList().ForEach(e => target.Add(e)));
return target;
}
Create a generic list mapper:
public class ValueMapper
{
public static TResult Map<TResult>(object item) where TResult : class
{
return item == null ? null : Mapper.Map<TResult>(item);
}
public static IEnumerable<TResult> MapList<TResult>(IEnumerable<object> items) where TResult : class
{
return items?.Select(i => Mapper.Map<TResult>(i));
}
}
Now you can reference the ValueMapper class wherever you want, and call both Map and MapList
var mydtos = ValueMapper.MapList<MyDto>(dtos);
var mydto = ValueMapper.Map<MyDto>(dto);

Resources