TableView with custom type combobox - combobox

I would like to create a TableView where its columns have reference to type:
private Indicators(String tl, WindowsItem chrt, String pne, Boolean sel) {
this.tool_col = new SimpleStringProperty(tl);
if (chrt == null) {
this.chart_col = new SimpleStringProperty("");
} else {
this.chart_col = new SimpleStringProperty(chrt.toString());
}
this.pane_col = new SimpleStringProperty(pne);
this.on_col = new SimpleBooleanProperty(sel);
this.chrt = chrt;
}
public String getTool() {
return tool_col.get();
}
public void setTool(String tl) {
tool_col.set(tl);
}
public WindowsItem getChart() {
return chrt;
}
public void setChart(WindowsItem _chrt) {
System.out.println("Indicators::setChart "+chrt.toString());
chrt = _chrt;
}
public String getPane() {
return pane_col.get();
}
public void setPane(String pne) {
pane_col.set(pne);
}
public Boolean getOn() {
return on_col.get();
}
public void setOn(boolean sel) {
on_col.set(sel);
}
public SimpleBooleanProperty onProperty() {
return on_col;
}
public SimpleStringProperty toolProperty() {
return tool_col;
}
public SimpleStringProperty chartProperty() {
return chart_col;
}
public SimpleStringProperty paneProperty() {
return pane_col;
}
}
I have a
private TableView<Indicators> tableviewIndicators;
In this column
private TableColumn<Indicators, WindowsItem> tablecolumnFrame;
public static class WindowsItem {
InternalWindow chrt;
private WindowsItem(InternalWindow _chrt) {
chrt = _chrt;
}
public String toString() {
return chrt.getTitle();
}
}
I would like to have a combobox or choicebox where every item type is
WindowsItem
How can I accomplish this?
I have tried this code
tablecolumnFrame.setCellFactory(new Callback<TableColumn<Indicators, WindowsItem>, TableCell<Indicators, WindowsItem>>() {
#Override
public TableCell<Indicators, WindowsItem> call(TableColumn<Indicators, WindowsItem> param) {
TableCell<Indicators, WindowsItem> cell = new TableCell<Indicators, WindowsItem>() {
#Override
public void updateItem(WindowsItem item, boolean empty) {
super.updateItem(item, empty);
if(empty){
return;
}
if (item != null) {
//final ChoiceBox<WindowsItem> choice = new ChoiceBox<>();
final ComboBox<WindowsItem> choice = new ComboBox<>();
int itemsInTab = chartsInTab.getChildren().size();
InternalWindow winItem;
for (int i = 0; i < itemsInTab; i++) {
if (chartsInTab.getChildren().get(i) instanceof InternalWindow) {
winItem = (InternalWindow) chartsInTab.getChildren().get(i);
choice.getItems().add(new WindowsItem(winItem));
//choice.getItems().add(winItem.toString());
System.out.println("winItem.toString() "+winItem.toString());
}
}
But it return this error
SEVERE: javafx.scene.control.Control loadSkinClass Failed to load skin 'StringProperty [bean: TableRow[id=null, styleClass=cell indexed-cell table-row-cell], name: skinClassName, value: com.sun.javafx.scene.control.skin.TableRowSkin]' for control TableRow[id=null, styleClass=cell indexed-cell table-row-cell]

You can try this:
private TableColumn<Indicators, WindowsItem> tablecolumnFrame;
and
public static class Indicators {
private final SimpleStringProperty tool_col;
private final SimpleStringProperty pane_col;
private final SimpleBooleanProperty on_col;
private final SimpleObjectProperty<WindowsItem> chrt;
private Indicators(String tl, WindowsItem chrt, String pne, Boolean sel) {
this.tool_col = new SimpleStringProperty(tl);
this.chrt = new SimpleObjectProperty<>(chrt);
this.pane_col = new SimpleStringProperty(pne);
this.on_col = new SimpleBooleanProperty(sel);
}
public String getTool() {
return tool_col.get();
}
public void setTool(String tl) {
tool_col.set(tl);
}
public WindowsItem getChart(){
return chrt.getValue();
}
public void setChart(WindowsItem _chrt) {
chrt.set(_chrt);
}
public String getPane() {
return pane_col.get();
}
public void setPane(String pne) {
pane_col.set(pne);
}
public Boolean getOn() {
return on_col.get();
}
public void setOn(boolean sel) {
on_col.set(sel);
}
public SimpleBooleanProperty onProperty() {
return on_col;
}
public SimpleStringProperty toolProperty() {
return tool_col;
}
public SimpleObjectProperty<WindowsItem> chartProperty() {
return chrt;
}
public SimpleStringProperty paneProperty() {
return pane_col;
}
}
be careful to:
public SimpleObjectProperty<WindowsItem> chartProperty() {
return chrt;
}
in your previous code was:
public SimpleStringProperty chartProperty() {
return chart_col;
}
this is the reason for the
SEVERE: javafx.scene.control.Control loadSkinClass Failed to load skin 'StringProperty

Related

EXPECTED BEGIN_ARRAY BUT WAS BEGIN_OBJECT AT LINE 1 COLUMN 2 PATH $22

I want to access JSON array . so I created 2 Object !!Have a look at my code , Url
Url-cricapi.com/api/matches/?apikey=JimJAfsmRGOnDpCrRrqO6htlilg1
My MatchesArrayClass
package com.piyushjaiswal.jsonpractis;
public class MatchesArray {
private Matches matches;
private provider provider2;
public MatchesArray(Matches matches, provider provider2) {
this.matches = matches;
this.provider2 = provider2;
}
public Matches getMatches() {
return matches;
}
public void setMatches(Matches matches) {
this.matches = matches;
}
public provider getProvider2() {
return provider2;
}
public void setProvider2(provider provider2) {
this.provider2 = provider2;
}
}
Matches Class
package com.piyushjaiswal.jsonpractis;
import com.google.gson.annotations.SerializedName;
public class Matches {
private int unique_id;
private String date;
private String dateTimeGMT;
#SerializedName("team-1")
private String team1;
#SerializedName("team-2")
private String team2;
private String type;
private String toss_winner_team;
private boolean squad;
private boolean matchStarted;
public int getUnique_id() {
return unique_id;
}
public void setUnique_id(int unique_id) {
this.unique_id = unique_id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDateTimeGMT() {
return dateTimeGMT;
}
public void setDateTimeGMT(String dateTimeGMT) {
this.dateTimeGMT = dateTimeGMT;
}
public String getTeam1() {
return team1;
}
public void setTeam1(String team1) {
this.team1 = team1;
}
public String getTeam2() {
return team2;
}
public void setTeam2(String team2) {
this.team2 = team2;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getToss_winner_team() {
return toss_winner_team;
}
public void setToss_winner_team(String toss_winner_team) {
this.toss_winner_team = toss_winner_team;
}
public boolean isSquad() {
return squad;
}
public void setSquad(boolean squad) {
this.squad = squad;
}
public boolean isMatchStarted() {
return matchStarted;
}
public void setMatchStarted(boolean matchStarted) {
this.matchStarted = matchStarted;
}
}
My Provider class
package com.piyushjaiswal.jsonpractis;
public class provider {
private String source;
private String url;
private String pubDate;
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
}
MainActivity Class
package com.piyushjaiswal.jsonpractis;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private JsonPlaceHolderApi jsonPlaceHolderApi;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textview);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://cricapi.com/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();
jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
getMatchList();
}
private void getMatchList() {
Call<List<MatchesArray>> call = jsonPlaceHolderApi.getPosts("JimJAfsmRGOnDpCrRrqO6htlilg1");
call.enqueue(new Callback<List<MatchesArray>>() {
#Override
public void onResponse(Call<List<MatchesArray>> call, Response<List<MatchesArray>> response) {
if(!response.isSuccessful()){
textView.setText(response.message() + "123");
return;
}
List<MatchesArray> list = response.body();
textView.setText(list.get(0).getMatches().getDate());
}
#Override
public void onFailure(Call<List<MatchesArray>> call, Throwable t) {
textView.setText(t.getMessage() +"22");
}
});
}
}
But output on screenshot is
"Expected BEGIB_ARRAY but was BEGIN_OBJECT at line 1 column 2 patg $2"
Your JSON syntax is wrong. The response starts with {"matches":[, this means it is an object, with the parameter matches that is of type match[].
So, you need a new class along the lines of:
public class MatchesWrapper {
private List<Matches> matches;
}
And change all your Call<List<MatchesArray>> to Call<MatchesWrapper>.
The error you received tells you this. You expected an array of Matches (Expected BEGIN_ARRAY), but instead received an object (was BEGIN_OBJECT).

Prism INavigationAware Interface not invoking IsNavigationTarget

I am using prism 6 and on my application I have modules. I want to navigate to different views on different modules and I am using INavigationAware Interface. I can call OnNavigatedFrom every time I am navigating away from current view but when I enter a new view OnNavigatedTo is not fired which is giving me a headache. I will post my code from bootstrap to viewmodel for one module.
Bootstraper.cs
public class Bootstrapper : UnityBootstrapper
{
#region Members
private ILog _logger;
#endregion
#region Properties
#endregion
#region Methods
protected override DependencyObject CreateShell()
{
_logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
RegisterTypes();
return Container.Resolve<AppShell>();
}
protected override void InitializeShell()
{
App.Current.MainWindow = (Window)this.Shell;
App.Current.MainWindow.Show();
}
protected void RegisterTypes()
{
Container.RegisterType<ILogger, Log4NetLogger>(new InjectionConstructor(_logger));
Container.RegisterType<IEncryption, SymmetricEncryption>();
Container.RegisterType<IGetSavviUow, GetSavviUowMock>();
Container.RegisterType<ICustomAuthentication, MockCustomAuthentication>();
Container.RegisterType<ICustomPrincipal, CustomPrincipal>();
Container.RegisterType<IIdNumberValidation, IdNumberValidation>();
Container.RegisterType<ISalesValidation, SalesValidation>();
AutoMapperConfig.RegisterMappings();
}
protected override void ConfigureModuleCatalog()
{
ModuleCatalog.AddModule(new ModuleInfo()
{
InitializationMode = InitializationMode.WhenAvailable,
ModuleType = typeof(LoginModuleDefinition).AssemblyQualifiedName,
ModuleName = typeof(LoginModuleDefinition).Name
});
ModuleCatalog.AddModule(new ModuleInfo()
{
InitializationMode = InitializationMode.OnDemand,
ModuleType = typeof(AgentQueueModuleDefinition).AssemblyQualifiedName,
ModuleName = typeof(AgentQueueModuleDefinition).Name
});
ModuleCatalog.AddModule(new ModuleInfo()
{
InitializationMode = InitializationMode.OnDemand,
ModuleType = typeof(PreQualificationModuleDefinition).AssemblyQualifiedName,
ModuleName = typeof(PreQualificationModuleDefinition).Name
});
ModuleCatalog.AddModule(new ModuleInfo()
{
InitializationMode = InitializationMode.OnDemand,
ModuleType = typeof(SearchModuleDefinition).AssemblyQualifiedName,
ModuleName = typeof(SearchModuleDefinition).Name
});
ModuleCatalog.AddModule(new ModuleInfo()
{
InitializationMode = InitializationMode.OnDemand,
ModuleType = typeof(PlanSelectionModuleDefinition).AssemblyQualifiedName,
ModuleName = typeof(PlanSelectionModuleDefinition).Name
});
ModuleCatalog.AddModule(new ModuleInfo()
{
InitializationMode = InitializationMode.OnDemand,
ModuleType = typeof(BenefitsScriptModuleDefinition).AssemblyQualifiedName,
ModuleName = typeof(BenefitsScriptModuleDefinition).Name
});
ModuleCatalog.AddModule(new ModuleInfo()
{
InitializationMode = InitializationMode.OnDemand,
ModuleType = typeof(PersonalInfoModuleDefinition).AssemblyQualifiedName,
ModuleName = typeof(PersonalInfoModuleDefinition).Name
});
}
protected override void InitializeModules()
{
base.InitializeModules();
}
#endregion
#region Constructors
#endregion
}
ShellViewModel.cs
public class ShellViewModel : ViewModelBase
{
#region Members
private string _username;
private bool _isLoggedIn;
private string _viewName;
private bool _canCreateNewMembership;
private bool _canUpgrade;
private bool _canReinstate;
private bool _canContinue;
private ILogger _logger;
private IModuleManager _moduleManager;
private IRegionManager _regionManager;
private Guid _agentRefId;
#endregion
#region Properties
public string Username
{
get { return _username; }
set
{
SetProperty(ref _username, value);
}
}
public bool IsLoggedIn
{
get { return _isLoggedIn; }
set { SetProperty(ref _isLoggedIn, value); }
}
public string ViewName
{
get { return _viewName; }
set { SetProperty(ref _viewName, value); }
}
#endregion
#region Methods
private void InitDelegateCommands()
{
this.LogoutCommand = new DelegateCommand(Logout);
this.ContinueCommand = new DelegateCommand<string>(Continue, CanContinue);
this.CreateNewMembershipCommand = new DelegateCommand(CreateNewMembership, CanCreateNewMembership);
this.ExitApplicationCommand = new DelegateCommand(ExitApplication);
this.ReinstateCommand = new DelegateCommand(Reinstate, CanReinstate);
this.SaveAndExitCommand = new DelegateCommand(SaveAndExit);
this.SaveProgressCommand = new DelegateCommand(Save);
this.SetCallBackCommand = new DelegateCommand(SetCallBack);
this.UpgradeCommand = new DelegateCommand(Upgrade, CanUpgrade);
}
private bool CanContinue(string navigatingTo)
{
this.NavigatingToView = navigatingTo;
return _canContinue;
}
private void Continue(string currentView)
{
this.Aggregator.GetEvent<ContinueEvent>().Publish(
this.ViewNavigationList
.First(x =>
x.CurrentView == currentView).RequestedView);
}
private bool CanUpgrade()
{
return _canUpgrade;
}
private void Upgrade()
{
this.Aggregator.GetEvent<UpgradeEvent>().Publish(_agentRefId);
}
private void Logout()
{
ICustomPrincipal customPrincipal = Thread.CurrentPrincipal as ICustomPrincipal;
if (customPrincipal != null)
{
customPrincipal.CustomIdentity = new AnonymousIdentity();
this.Username = string.Empty;
this.IsLoggedIn = false;
ShowView(ModuleViewConstants.LoginView);
}
}
private void SetCallBack()
{
this.Aggregator.GetEvent<SetCallBackEvent>().Publish(_agentRefId);
}
private void Save()
{
this.Aggregator.GetEvent<SaveEvent>().Publish(_agentRefId);
}
private void SaveAndExit()
{
this.Aggregator.GetEvent<SaveEvent>().Publish(_agentRefId);
}
private bool CanReinstate()
{
return _canReinstate;
}
private void Reinstate()
{
this.Aggregator.GetEvent<ContinueEvent>().Publish(ModuleViewConstants.PlanSelectionView);
}
private bool CanCreateNewMembership()
{
return _canCreateNewMembership;
}
private void CreateNewMembership()
{
this.Aggregator.GetEvent<ContinueEvent>().Publish(ModuleViewConstants.PlanSelectionView);
}
private void ExitApplication()
{
this.Aggregator.GetEvent<ExitApplicationEvent>().Publish(_agentRefId);
}
private void OnLoggedOn(LoggedOnArgument args)
{
this.Username = args.Username;
this.IsLoggedIn = args.IsLoggedOn;
_agentRefId = args.AgentRefId;
LoadModules();
_regionManager.Regions[RegionConstants.QueueRegion].Context = _agentRefId;
ShowView(ModuleViewConstants.PreQualificationView);
}
private void LoadModules()
{
_moduleManager.LoadModule(typeof(AgentQueueModuleDefinition).Name);
_moduleManager.LoadModule(typeof(SearchModuleDefinition).Name);
_moduleManager.LoadModule(typeof(PreQualificationModuleDefinition).Name);
_moduleManager.LoadModule(typeof(PlanSelectionModuleDefinition).Name);
_moduleManager.LoadModule(typeof(BenefitsScriptModuleDefinition).Name);
_moduleManager.LoadModule(typeof(PersonalInfoModuleDefinition).Name);
}
private void ShowView(string view)
{
this.ViewName = view;
this.CurrentView = view;
_regionManager.RequestNavigate(
RegionConstants.OperationsRegion,
new Uri(view, UriKind.Relative));
}
private void AssingCanCreateNewMembership(bool canCreateMembership)
{
_canCreateNewMembership = canCreateMembership;
CreateNewMembershipCommand.RaiseCanExecuteChanged();
}
private void AssignCanContinue(bool canContinue)
{
_canContinue = canContinue;
ContinueCommand.RaiseCanExecuteChanged();
}
private void AssignCanUpgrade(bool canUpgrade)
{
_canUpgrade = canUpgrade;
UpgradeCommand.RaiseCanExecuteChanged();
}
private void AssignCanReinstate(bool canReinstate)
{
_canReinstate = canReinstate;
ReinstateCommand.RaiseCanExecuteChanged();
}
private void EventSubscriptions()
{
this.Aggregator.GetEvent<LoggedOnEvent>().Subscribe(OnLoggedOn);
this.Aggregator.GetEvent<ShowViewEvent>().Subscribe(ShowView);
this.Aggregator.GetEvent<CanCreateNewMembership>().Subscribe(AssingCanCreateNewMembership);
this.Aggregator.GetEvent<CanContinueEvent>().Subscribe(AssignCanContinue);
this.Aggregator.GetEvent<CanUpgradeEvent>().Subscribe(AssignCanUpgrade);
this.Aggregator.GetEvent<CanReinstateEvent>().Subscribe(AssignCanReinstate);
}
#endregion
#region Commands
public DelegateCommand LogoutCommand { get; set; }
public DelegateCommand ExitApplicationCommand { get; set; }
public DelegateCommand<string> ContinueCommand { get; set; }
public DelegateCommand SaveProgressCommand { get; set; }
public DelegateCommand SetCallBackCommand { get; set; }
public DelegateCommand SaveAndExitCommand { get; set; }
public DelegateCommand CreateNewMembershipCommand { get; set; }
public DelegateCommand ReinstateCommand { get; set; }
public DelegateCommand UpgradeCommand { get; set; }
#endregion
#region Events
#endregion
#region Construction
public ShellViewModel(
IRegionManager regionManager,
IUnityContainer container,
IEventAggregator aggregator,
IModuleManager moduleManager,
ILogger logger)
: base(aggregator, container)
{
_logger = logger;
_logger.Info("Starting Shell");
_moduleManager = moduleManager;
_regionManager = regionManager;
InitDelegateCommands();
EventSubscriptions();
}
#endregion
}
PreQualificationModule
PreQualificationModuleDefinition.cs
public class PreQualificationModuleDefinition : IModule
{
#region Members
private IRegionManager _regionManager;
private IUnityContainer _container;
#endregion
#region Properties
#endregion
#region Methods
public void Initialize()
{
_container.RegisterType<object, PreQualificationView>(ModuleViewConstants.PreQualificationView);
_regionManager.RegisterViewWithRegion(RegionConstants.OperationsRegion, typeof(PreQualificationView));
}
#endregion
#region Constructors
public PreQualificationModuleDefinition(
IRegionManager regionManager,
IUnityContainer container)
{
_regionManager = regionManager;
_container = container;
}
#endregion
}
PreQualificationViewModel.cs
public class PreQualificationViewModel : ViewModelBase, INavigationAware
{
#region Members
private string _name;
private int _selectedIdType;
private string _contactNumber;
private string _idNumber;
private DateTime? _dateOfBirth;
private int? _age;
private string _gender;
private string _passportNumber;
private bool _isCitizen;
private bool _isSearch;
private bool _showUserControl;
private bool _showPassportFields;
private bool _hasContactNumber;
private ObservableCollection<string> _genderList;
private int? _planId;
private IList<PolicyGrid> _policies;
private Principal _mainMember;
private Lead _lead;
private Membership _membership;
private IGetSavviUow _uow;
private IIdNumberValidation _idNumberValidation;
private ICustomPrincipal _principal;
private ISalesValidation _salesValidation;
private IRegionManager _regionManager;
#endregion
#region Properties
public string Name
{
get { return _name; }
set { SetProperty(ref _name, value); }
}
public int SelectedIdType
{
get { return _selectedIdType; }
set
{
SetProperty(ref _selectedIdType, value, this);
if (_selectedIdType == 2)
{
this.ShowPassportFields = true;
this.IsCitizen = false;
}
else
{
this.ShowPassportFields = false;
this.IsCitizen = true;
}
}
}
public ObservableCollection<KeyValuePair<int, string>> IdTypes
{
get
{
return new ObservableCollection<KeyValuePair<int, string>>()
{
new KeyValuePair<int, string>(1, "RSA ID Number"),
new KeyValuePair<int, string>(2, "Passport")
};
}
}
[Required]
public string ContactNumber
{
get { return _contactNumber; }
set
{
SetProperty(ref _contactNumber, value, this);
}
}
[IdValidation("SelectedIdType")]
[RequiredIf("SelectedIdType", 1)]
[Display(Name = "ID Number")]
public string IdNumber
{
get { return _idNumber; }
set
{
SetProperty(ref _idNumber, value, this);
if (_idNumberValidation.IsCitizen(_idNumber))
{
this.IsCitizen = true;
SetIdProperties();
}
}
}
[RequiredIf("SelectedIdType", 2)]
[Display(Name = "Date of Birth")]
public Nullable<DateTime> DateOfBirth
{
get { return _dateOfBirth; }
set
{
SetProperty(ref _dateOfBirth, value, this);
if (_dateOfBirth != null)
this.Age = DateTime.Today.Year - _dateOfBirth.Value.Year;
}
}
[AgeMinMax("PlanId")]
public Nullable<int> Age
{
get { return _age; }
set
{
SetProperty(ref _age, value, this);
}
}
[RequiredIf("SelectedIdType", 2)]
public string Gender
{
get { return _gender; }
set
{
SetProperty(ref _gender, value, this);
}
}
public ObservableCollection<string> GenderList
{
get { return _genderList; }
set
{
SetProperty(ref _genderList, value);
}
}
[RequiredIf("SelectedIdType", 2)]
[Display(Name = "Passport Number")]
public string PassportNumber
{
get { return _passportNumber; }
set
{
SetProperty(ref _passportNumber, value, this);
}
}
public bool IsCitizen
{
get { return _isCitizen; }
set { SetProperty(ref _isCitizen, value, this); }
}
public bool IsSearch
{
get { return _isSearch; }
set { SetProperty(ref _isSearch, value, this); }
}
public bool ShowUserControl
{
get { return _showUserControl; }
set { SetProperty(ref _showUserControl, value, this); }
}
public bool ShowPassportFields
{
get { return _showPassportFields; }
set { SetProperty(ref _showPassportFields, value, this); }
}
public bool HasContactNumber
{
get { return _hasContactNumber; }
set { SetProperty(ref _hasContactNumber, value, this); }
}
public Nullable<int> PlanId
{
get { return _planId; }
set { _planId = value; }
}
public IList<PolicyGrid> Policies
{
get { return _policies; }
set { SetProperty(ref _policies, value); }
}
#endregion
#region Methods
private void SetIdProperties()
{
this.Age = _idNumberValidation.GetAge(DateTime.Today, this.IdNumber);
this.DateOfBirth = _idNumberValidation.GetDateOfBirth(this.IdNumber);
this.Gender = _idNumberValidation.GetGender(this.IdNumber);
}
private void GetLeadInfo(int callQueueId)
{
ClearProperties();
var callQueue = _uow.RepoCallQueue.GetLeadByCallQueueIdRefId(callQueueId, _principal.CustomIdentity.RefId);
this.ShowUserControl = true;
var leadCallQueue = callQueue.Lead_CallQueue.FirstOrDefault(x => x.CallQueueId == callQueueId);
_lead = leadCallQueue.Lead;
this.Name = _lead.FirstName + " " + _lead.Surname;
this.IdNumber = _lead.IdNumber;
this.PlanId = _lead.PlanId;
if (!string.IsNullOrEmpty(_lead.Mobile))
{
this.HasContactNumber = true;
this.ContactNumber = _lead.Mobile;
}
if (!string.IsNullOrEmpty(_lead.IdNumber) &&
_idNumberValidation.IsCitizen(_lead.IdNumber))
{
this.SelectedIdType = 1;
}
else if (!string.IsNullOrEmpty(_lead.IdNumber))
{
this.SelectedIdType = 2;
}
}
private void ClearProperties()
{
this.IdNumber = string.Empty;
this.DateOfBirth = null;
this.Gender = null;
this.Age = null;
}
private void SearchedMembership(SearchArgs arg)
{
ClearProperties();
this.ShowUserControl = true;
List<Membership> memberships = new List<Membership>();
if (!string.IsNullOrEmpty(arg.SearchedId))
{
switch (arg.SearchingType)
{
case 1:
//Membership Number
memberships = _uow.RepoMembership.GetMembershipsByMembershipNumber(Convert.ToInt32(arg.SearchedId)).ToList();
break;
case 2:
//ID Number
memberships = _uow.RepoMembership.GetMembershipsByIdNumber(arg.SearchedId).ToList();
break;
case 3:
//Passport
memberships = _uow.RepoMembership.GetMembershipsByPassport(arg.SearchedId).ToList();
break;
default:
throw new ArgumentException("Uknown Searching type!");
}
_mainMember = memberships.FirstOrDefault().Principal;
if(memberships.Count > 0)
this.Policies = memberships.Select(x => new PolicyGrid(
x.Id,
_uow.Plan.GetById(x.PlanId.Value).Description,
_uow.MembershipStatus.GetById(x.MembershipStatusId).Description,
x.CommenceDate.HasValue?x.CommenceDate.Value.ToString("dd/MM/yyyy") : null,
x.ResignationDate.HasValue ? x.ResignationDate.Value.ToString("dd/MM/yyyy") : null)).ToList();
this.Name = _mainMember.FirstName + " " + _mainMember.Surname;
this.IdNumber = _mainMember.IdNumber;
this.PlanId = _uow.RepoMembership.GetLatestMembership(this.IdNumber).PlanId;
if (!string.IsNullOrEmpty(_mainMember.Mobile))
{
this.HasContactNumber = true;
this.ContactNumber = _mainMember.Mobile;
}
if (!string.IsNullOrEmpty(_mainMember.IdNumber) &&
_idNumberValidation.IsCitizen(_mainMember.IdNumber))
{
this.SelectedIdType = 1;
}
else if (!string.IsNullOrEmpty(_mainMember.IdNumber))
{
this.SelectedIdType = 2;
}
}
}
private void RaiseCommands(object value)
{
if (!string.IsNullOrEmpty(this.IdNumber))
{
if (!_salesValidation.IdNumberExists(this.IdNumber) && !this.HasErrors)
{
this.Aggregator.GetEvent<CanCreateNewMembership>().Publish(true);
}
else if (_salesValidation.IdNumberExists(this.IdNumber) &&
!_salesValidation.IncompleteApplication(this.IdNumber) &&
!_salesValidation.CanUpgrade(this.IdNumber) &&
!_salesValidation.CanReInstate(this.IdNumber))
{
//this.Aggregator.GetEvent<CanCreateNewMembership>().Publish(true);
}
else
{
this.Aggregator.GetEvent<CanCreateNewMembership>().Publish(false);
}
if (_salesValidation.IdNumberExists(this.IdNumber) &&
!this.HasErrors && _salesValidation.IncompleteApplication(this.IdNumber))
{
this.Aggregator.GetEvent<CanContinueEvent>().Publish(true);
}
else
{
this.Aggregator.GetEvent<CanContinueEvent>().Publish(false);
}
if (_salesValidation.IdNumberExists(this.IdNumber) &&
_salesValidation.CanUpgrade(this.IdNumber))
{
this.Aggregator.GetEvent<CanUpgradeEvent>().Publish(true);
}
else
{
this.Aggregator.GetEvent<CanUpgradeEvent>().Publish(false);
}
if (_salesValidation.IdNumberExists(this.IdNumber) &&
_salesValidation.CanReInstate(this.IdNumber))
{
this.Aggregator.GetEvent<CanReinstateEvent>().Publish(true);
}
else
{
this.Aggregator.GetEvent<CanReinstateEvent>().Publish(false);
}
if (this.HasErrors)
{
this.Aggregator.GetEvent<CanCreateNewMembership>().Publish(false);
this.Aggregator.GetEvent<CanContinueEvent>().Publish(false);
this.Aggregator.GetEvent<CanUpgradeEvent>().Publish(false);
this.Aggregator.GetEvent<CanReinstateEvent>().Publish(false);
}
}
}
private void Continue(string view)
{
if (view == ModuleViewConstants.PlanSelectionView)
this.Aggregator.GetEvent<ShowViewEvent>().Publish(
ModuleViewConstants.PlanSelectionView);
}
private void EventSubscriptions()
{
this.Aggregator.GetEvent<LoadLeadInfoEvent>().Subscribe(GetLeadInfo);
this.Aggregator.GetEvent<RaiseCommandAndEventsEvent>().Subscribe(RaiseCommands);
this.Aggregator.GetEvent<SearchEvent>().Subscribe(SearchedMembership);
this.Aggregator.GetEvent<ContinueEvent>().Subscribe(Continue);
this.Aggregator.GetEvent<SaveEvent>().Subscribe(SaveProgress);
}
bool INavigationAware.IsNavigationTarget(NavigationContext navigationContext)
{
_membership = GetMembership(navigationContext);
return _membership == null;
}
private Membership GetMembership(NavigationContext navigationContext)
{
if (navigationContext.NavigationService.Region.Context != null &&
navigationContext.NavigationService.Region.Context is Membership)
return (Membership)navigationContext.NavigationService.Region.Context;
return null;
}
void INavigationAware.OnNavigatedFrom(NavigationContext navigationContext)
{
var refId = (Thread.CurrentPrincipal as ICustomPrincipal).CustomIdentity.RefId;
this.SaveProgress(refId);
if (_membership != null)
{
navigationContext.NavigationService.Region.Context = _membership;
}
}
void INavigationAware.OnNavigatedTo(NavigationContext navigationContext)
{
}
private void SaveProgress(Guid refId)
{
var agentId = _uow.User.GetByRef(refId).Id;
_mainMember = new Principal();
if (_lead != null)
Mapper.Map(_lead, _mainMember);
if (_membership == null)
_membership = new Membership(
Guid.NewGuid(),
_lead.PlanId.HasValue?_lead.PlanId : null,
null,
null,
null,
DateTime.Now,
agentId,
_mainMember.Id,
(int)BillingStatusEnum.BAFP,
(int)MembershipStatusEnum.PWS,
null,
null,
null);
if (_mainMember != null)
{
//To Take out when Db is working
var principalId = _uow.Principal.GetAll().Max(x => x.Id);
_mainMember.Id = principalId + 1;
_membership.Principal = _mainMember;
}
//To Take out when Db is working
var id = _uow.Membership.GetAll().Max(x => x.Id);
_membership.Id = id + 1;
//===================================================\\
}
#endregion
#region Commands
#endregion
#region EventHandlers
#endregion
#region Constructors
public PreQualificationViewModel(
IEventAggregator aggregator,
IUnityContainer container,
IRegionManager regionManager,
IGetSavviUow uow,
IIdNumberValidation idNumberValidation,
ISalesValidation salesValidation) :
base(aggregator, container)
{
_uow = uow;
_regionManager = regionManager;
_principal = Thread.CurrentPrincipal as ICustomPrincipal;
_idNumberValidation = idNumberValidation;
_salesValidation = salesValidation;
EventSubscriptions();
this.GenderList = new ObservableCollection<string>()
{
"Male",
"Female"
};
}
#endregion
}
Please Help!!!

Why are Collection properties indexed in objectify, sometimes?

In objectify, when I define a collection property with String datatype,
#IgnoreSave(IfEmpty.class)
private Set<String> collectionProperty = new HashSet<>();
and then look at a record in datastore, it appears indexed even though I have not annotated it with #Index.
Contrary, when I use a complex Object instead String, it does not appear as indexed.
Why are Collection properties indexed sometimes and sometimes not? And is there a way to determine this?
--
Unmodified code and screenshot from admin console/datastore:
#Entity
#Cache(expirationSeconds = 900)
public class Item extends StringId implements Serializable {
private static final Logger log = Logger.getLogger(Item.class.getSimpleName());
private static final long serialVersionUID = 1;
// Constructors
private Item() {}
#Nonnull
private static Item create(#Nonnull String itemId) {
Item item = (Item) new Item().setId(itemId);
item.piecesFromId();
log.info("item = " + JsonHelper.logToJson(item));
return item;
}
#Nonnull
public static Item create(#Nonnull String provider, #Nonnull String type, #Nonnull String identifier) {
String itemId = IdHelper.createItemId(provider, type, identifier);
Item item = ((Item) new Item().setId(itemId))
.setProvider(provider)
.setType(type)
.setIdentifier(identifier);
log.info("item = " + JsonHelper.logToJson(item));
return item;
}
#Nonnull
public static Item loadOrCreate(#Nonnull String itemId) {
Item item = ofy().load().type(Item.class).id(itemId).now();
if (item == null) {
item = Item.create(itemId);
}
return item;
}
#Nullable
public static Item load(#Nonnull String itemId) {
return ofy().load().type(Item.class).id(itemId).now();
}
#OnLoad
private void piecesFromId() {
provider = IdHelper.getProvider(id);
type = IdHelper.getType(id);
identifier = IdHelper.getIdentifier(id);
}
public Item save() {
ofy().defer().save().entity(this);
return this;
}
#OnSave
private void integrity() {
if (id == null) { throw new RuntimeException("Id must not be null."); }
if (itemPreview == null) { throw new RuntimeException("itemPreview must not be null."); }
if (provider == null || type == null || identifier == null) { throw new RuntimeException("provider, type and identifier must not be null."); }
if (!id.equals(IdHelper.createItemId(provider, type, identifier))) { throw new RuntimeException("id does not coincide with provider, type and identifier."); }
if (!id.equals(itemPreview.getItemId())) { throw new RuntimeException("id does not coincide with id in itemPreview."); }
}
#OnSave
private void timestamp() {
if (created == null) {
created = System.currentTimeMillis();
}
}
// Properties
#Ignore
private String provider;
#Ignore
private String type;
#Ignore
private String identifier;
#Ignore // json
private ItemPreview itemPreview;
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfEmpty.class)
private Set<String> subscribedUserIds = new HashSet<>();
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfEmpty.class)
private Set<String> notifyUserIds = new HashSet<>();
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfEmpty.class)
private Set<String> blacklistingUserIds = new HashSet<>();
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
private Long created;
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfDefault.class)
#Index
private Status status = Status.ACTIVE;
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfNull.class)
private String suspensionNotice;
// Json
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfNull.class)
private String itemPreviewJson;
private static Type itemPreviewType = new TypeToken<ItemPreview>(){}.getType();
#OnLoad
private void itemPreviewFromJson() {
if (itemPreviewJson != null) {
itemPreview = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
.fromJson(itemPreviewJson, itemPreviewType);
}
}
#OnSave
private void itemPreviewToJson() {
itemPreviewJson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
.toJson(itemPreview, itemPreviewType);
}
// Accessors
public String getProvider() {
return provider;
}
public Item setProvider(String provider) {
this.provider = provider;
return this;
}
public String getType() {
return type;
}
public Item setType(String type) {
this.type = type;
return this;
}
public String getIdentifier() {
return identifier;
}
public Item setIdentifier(String identifier) {
this.identifier = identifier;
return this;
}
public ItemPreview getItemPreview() {
return itemPreview;
}
public Item setItemPreview(ItemPreview itemPreview) {
this.itemPreview = itemPreview;
return this;
}
public Set<String> getSubscribedUserIds() {
return subscribedUserIds;
}
public Item setSubscribedUserIds(Set<String> subscribedUserIds) {
this.subscribedUserIds = subscribedUserIds;
return this;
}
public Set<String> getNotifyUserIds() {
return notifyUserIds;
}
public Item setNotifyUserIds(Set<String> notifyUserIds) {
this.notifyUserIds = notifyUserIds;
return this;
}
public Set<String> getBlacklistingUserIds() {
return blacklistingUserIds;
}
public Item setBlacklistingUserIds(Set<String> blacklistingUserIds) {
this.blacklistingUserIds = blacklistingUserIds;
return this;
}
public Long getCreated() {
return created;
}
public Item setCreated(Long created) {
this.created = created;
return this;
}
public Status getStatus() {
return status;
}
public Item setStatus(Status status) {
this.status = status;
return this;
}
public String getSuspensionNotice() {
return suspensionNotice;
}
public Item setSuspensionNotice(String suspensionNotice) {
this.suspensionNotice = suspensionNotice;
return this;
}
// Collections
public static Map<String, Item> loadAll(Set<String> itemIds) {
return ofy().load().type(Item.class).ids(itemIds);
}
}

JavaFX - How do I access the result(ObservableList) from a service?

How do I access the returned result from a service? The result is queried from the database and added to a ObservableList. I have a checkbox and wanted its value to depend on the result from the database.
How do I bind the checkbox so that its value(checked/unchecked) will depend on the rs.getString("studentForm137") field.
//cboxForm137.selectedProperty().bind(//I don't know the codes to bind checkbox);
Service
final Service<ObservableList<Student>> service = new Service<ObservableList<Student>>()
{
#Override
protected Task<ObservableList<Student>> createTask()
{
return new Task<ObservableList<Student>>()
{
#Override
protected ObservableList<Student> call() throws Exception
{
for (int i = 0; i < 250; i++)
{
updateProgress(i, 250);
Thread.sleep(2);
}
return student.display();
}
};
}
};
service.start();
Student Class
public class Student extends Person {
private SimpleStringProperty form137;
private SimpleStringProperty form138;
private SimpleStringProperty goodMoralCertificate;
private SimpleStringProperty birthCertificate;
private SimpleStringProperty highschoolDiploma;
public Student()
{
super();
}
public Student(String lastName, String firstName, String middleName,
String cpNumber, String address, String dateOfBirth,
String placeOfBirth, String emailAddress, String gender,
String fathersName, String mothersName,
String form137, String form138, String goodMoralCertificate,
String birthCertificate, String highschoolDiploma)
{
super(lastName, firstName, middleName,
cpNumber, address, dateOfBirth, placeOfBirth, emailAddress, gender,
fathersName, mothersName);
this.form137 = new SimpleStringProperty(form137);
this.form138 = new SimpleStringProperty(form138);
this.goodMoralCertificate = new SimpleStringProperty(goodMoralCertificate);
this.birthCertificate = new SimpleStringProperty(birthCertificate);
this.highschoolDiploma = new SimpleStringProperty(highschoolDiploma);
}
//form137
public String getForm137()
{
return form137.get();
}
public void setForm137(String form137)
{
this.form137.set(form137);
}
public StringProperty form137Property()
{
return form137;
}
//form138
public String getForm138()
{
return form138.get();
}
public void setForm138(String form138)
{
this.form138.set(form138);
}
public StringProperty form138Property()
{
return form138;
}
//goodMoralCertificate
public String getGoodMoralCertificate()
{
return goodMoralCertificate.get();
}
public void setGoodMoralCertificate(String goodMoralCertificate)
{
this.goodMoralCertificate.set(goodMoralCertificate);
}
public StringProperty goodMoralCertificateProperty()
{
return goodMoralCertificate;
}
//birthCertificate
public String getBirthCertificate()
{
return birthCertificate.get();
}
public void setBirthCertificate(String birthCertificate)
{
this.birthCertificate.set(birthCertificate);
}
public StringProperty birthCertificateProperty()
{
return birthCertificate;
}
//highschoolDiploma
public String getHighschoolDiploma()
{
return highschoolDiploma.get();
}
public void setHighschoolDiploma(String highschoolDiploma)
{
this.highschoolDiploma.set(highschoolDiploma);
}
public StringProperty highschoolDiplomaProperty()
{
return highschoolDiploma;
}
#Override
public ObservableList display()
{
Connection c = null;
PreparedStatement pst = null;
ResultSet rs = null;
ObservableList<Student> student = FXCollections.observableArrayList();
try
{
c = MySqlConnection.connect();
String SQL = "SELECT * " +
"FROM students ";
pst = c.prepareStatement(SQL);
rs = pst.executeQuery();
while(rs.next())
{
student.add(new Student(rs.getString("studentLastName"),
rs.getString("studentFirstName"),
rs.getString("studentMiddleName"),
rs.getString("studentCPNumber"),
rs.getString("studentAddress"),
rs.getString("studentDateOfBirth"),
rs.getString("studentPlaceOfBirth"),
rs.getString("studentEmailAddress"),
rs.getString("studentGender"),
rs.getString("studentFathersName"),
rs.getString("studentMothersName"),
rs.getString("studentForm137"),
rs.getString("studentForm138"),
rs.getString("studentGMC"),
rs.getString("studentNSO"),
rs.getString("studentHSDiploma")));
}
}
catch(Exception e)
{
System.out.println("Error on Building Data");
}
finally
{
try
{
PublicClass.closeConnection(c, pst, rs);
}
catch (SQLException ex)
{
Logger.getLogger(Student.class.getName()).log(Level.SEVERE, null, ex);
}
}
return student;
}
}

WPF and State Machine Pattern

I want to implement functionality that give possibility switch tabItems (TabItem1,TabItem2,TabItem3), when user click button "next" on the Form. And for that reason I'd like to use State Machine Pattern.
These things I've already implemented, but I have no clue, is it right or not?:
public abstract class State
{
#region Constructros
public State()
{
}
public State(State state)
{
this.CurrentState = state.CurrentState;
this.PreviousState = state.PreviousState;
this.NextState = state.NextState;
}
public State(Machine machine,string strCurrentState,string strPreviousState,string strNextState)
{
this.CurrentState = strCurrentState;
this.PreviousState = strPreviousState;
this.NextState = strNextState;
this.SetParams();
}
#endregion
public const string WELCOME = "WELCOME";
public const string EMR_CONFIGURATION = "EMR_CONFIGURATION";
public const string MIGRATION = "MIGRATION";
public const string END_OF_STATES = "END_OF_STATES";
private Machine machine;
private string currentState;
private string previousState;
private string nextState;
private string nameState;
public virtual void SetParams() { }
public virtual void ChangeState(Machine m, State s)
{
m.ChangeState(s);
}
//Get The name of State
public Machine Machine
{
get { return this.machine; }
set { this.machine = value; }
}
//Current State
public string CurrentState
{
get { return this.currentState; }
set { this.currentState = value; }
}
//Previous State
public string PreviousState
{
get { return this.previousState; }
set { this.previousState = value; }
}
//Next State
public string NextState
{
get { return this.nextState; }
set { this.nextState = value; }
}
public string NameState
{
get { return this.nameState; }
set { this.nameState = value; }
}
}
public class Machine
{
public State currentState;
public Machine (string strCurrentState,string strPreviousState,string strNextState)
{
currentState = new WelcomeState(this, strCurrentState, strPreviousState, strNextState);
}
public void ChangeState(State setState)
{
currentState = setState;
}
public void SetCurrentState (string state)
{
currentState.CurrentState = state;
}
}
class Transition
{
public State state;
private static Transition getInstance;
protected Transition(){}
public static Transition GetInstance()
{
if (getInstance == null)
{
getInstance = new Transition();
}
return getInstance;
}
public void Transform(State state)
{
if (state == null)
{
return;
}
// Get the type of state.
string stateType = state.GetType().Name;
// WELCOME TabItem
if (state.CurrentState == State.WELCOME)
{
state.ChangeState(state.Machine, new WelcomeState(state));
}
//EMR_CONFIGURATION TabItem
if (state.CurrentState == State.EMR_CONFIGURATION)
{
state.ChangeState(state.Machine, new EMRConfigurationState(state));
}
//MIGRATION TabItem
if (state.CurrentState == State.EMR_CONFIGURATION)
{
state.ChangeState(state.Machine, new MigrationState(state));
}
}
}
public class WelcomeState : State
{
public WelcomeState(State state) : base(state)
{
}
public WelcomeState (Machine machine, string strCurrentState,string strPreviousState,string strNextState):
base(machine, strCurrentState, strPreviousState, strNextState)
{
}
public override void SetParams()
{
this.CurrentState = State.WELCOME;
this.PreviousState = State.WELCOME;
this.NextState = State.EMR_CONFIGURATION;
}
}
public class EMRConfigurationState : State
{
public EMRConfigurationState(State state) : base(state)
{
}
public EMRConfigurationState(Machine machine, string strCurrentState, string strPreviousState, string strNextState) :
base(machine, strCurrentState, strPreviousState, strNextState)
{
}
public override void SetParams()
{
this.CurrentState = State.EMR_CONFIGURATION;
this.PreviousState = State.WELCOME;
this.NextState = State.MIGRATION;
}
}
public class MigrationState: State
{
public MigrationState(State state) : base(state)
{
}
public MigrationState(Machine machine, string strCurrentState, string strPreviousState, string strNextState) :
base(machine, strCurrentState, strPreviousState, strNextState)
{
}
public override void SetParams()
{
this.CurrentState = State.MIGRATION;
this.PreviousState = State.EMR_CONFIGURATION;
this.NextState = State.END_OF_STATES;
}
}
public partial class Window1 : Window
{
private WizardPresenter wizPresenterWelcome = null;
public List<WizardPresenter> stateList;
public Window1()
{
InitializeComponent();
stateList = new List<WizardPresenter>
{
new WizardPresenter(StatePresenter.WELCOME,
StatePresenter.WELCOME,
StatePresenter.EMR_CONFIGURATION),
new WizardPresenter(StatePresenter.EMR_CONFIGURATION,
StatePresenter.WELCOME,StatePresenter.MIGRATION),
new WizardPresenter(StatePresenter.MIGRATION,
StatePresenter.EMR_CONFIGURATION,
StatePresenter.WELCOME),
};
tabControl.ItemsSource = stateList;
}
private WizardPresenter GetWizardPresenter(string strState)
{
foreach (WizardPresenter presenter in stateList)
{
if (presenter.currentStatePresenter.CurrentStatePresenter == strState)
{
return presenter;
break;
}
}
return null;
}
private void button_Click(object sender, RoutedEventArgs e)
{
if (this.wizPresenterWelcome == null)
{
try
{
{
WizardPresenter wp = (WizardPresenter)tabControl.SelectedItem;
string nextState = wp.currentStatePresenter.NextStatePresenter;
tabControl.SelectedIndex = stateList.IndexOf(GetWizardPresenter(nextState));
}
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.Message + "Error");
}
}
}
}
If when you run it works then you've got it right, if when you run it doesn't work then you've got it wrong.
In general:
When you're rephrasing a question, edit the original post and add explanations there.
You can create a context class that holds all the relevant states and the current, previous and next state. Each state can handle each change and decide the next state based on:
Runtime value of Context variables.
The context's previous state.
etc.

Resources