JFoenix Drawer .hide(); and .drawer(); functions are not working - javafx

I am tired on this point, JFoenix Drawer .hide(); and .drawer(); functions are not working
try {
VBox box = FXMLLoader.load(getClass().getResource("/chatroom/ui/chatingwindow/DrawerContent.fxml"));
drawer.setSidePane(box);
HamburgerBackArrowBasicTransition arrowBasicTransition = new HamburgerBackArrowBasicTransition(hamburger);
arrowBasicTransition.setRate(-1);
hamburger.addEventHandler(MouseEvent.MOUSE_PRESSED, (e) -> {
arrowBasicTransition.setRate(arrowBasicTransition.getRate() * -1);
arrowBasicTransition.play();
if (drawer.isShown()) {
drawer.hide();
} else {
drawer.draw();
}
});
} catch (IOException ex) {
Logger.getLogger(ChatingWindowController.class.getName()).log(Level.SEVERE, null, ex);
}
why is that, any Jfoenix tutorials are used that functions, but I couldn't use that?

It is because they do not exist it should be:
if (drawer.isOpened()) {
drawer.close();
} else {
drawer.open();
}

Related

can not show alertcontroller when page is displayed using PushModalAsync

I am trying to show toast message in android and iOS from xamarin.forms project using Dependency Service. In iOS project message is shown on MainPage or NavigationPage. but when I navigate a second page on button click using PushModalAsync, message is not displayed.
How I navigate the page
public LoginPage()
{
Device.BeginInvokeOnMainThread(() =>
{
CustomToast.LongMessage("Hiiiiii"); // Message shown
});
Navigation.PushModalAsync(new RegisterPage()); //Doesn't show
//var reg = new RegisterPage();
//Application.Current.MainPage = reg; // toast shown here
}
Code for alertController in iOS :
const double SHORT_DELAY = 2.0;
NSTimer alertDelay;
UIAlertController alert;
public void LongAlert(string message)
{
ShowAlert(message, LONG_DELAY);
}
public void ShortAlert(string message)
{
ShowAlert(message, SHORT_DELAY);
}
void ShowAlert(string message, double seconds)
{
try
{
if (alert == null && alertDelay == null)
{
alertDelay = NSTimer.CreateScheduledTimer(seconds, (obj) =>
{
Device.BeginInvokeOnMainThread(() =>
{
DismissMessage();
});
});
Device.BeginInvokeOnMainThread(() =>
{
try
{
alert = UIAlertController.Create("", message, UIAlertControllerStyle.ActionSheet);
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(alert, true, null);
}
catch (Exception ex)
{
var Error = ex.Message;
}
});
}
}
catch (Exception ex)
{
TraceLog("Message iOS ShowAlert : " + ex.Message);
}
}
void DismissMessage()
{
if (alert != null)
{
alert.DismissViewController(true, null);
alert = null;
}
if (alertDelay != null)
{
alertDelay.Dispose();
alertDelay = null;
}
}
And I call this from my register page constructor
Device.BeginInvokeOnMainThread(() =>
{
CustomToast.LongMessage("Hiiiiii");
});
It doesn't go in catch anywhere but its not displayed also. can anyone please suggest some advice ?
This is because RegisterPage is a presented page on your LoginPage, UIApplication.SharedApplication.KeyWindow.RootViewController this code can't retrieve a correct view controller for RegisterPage. It just presented an action sheet on the previous page, but your app has reached a new page then this Toast can be shown on the screen.
Firstly, you have to find out the top page on the window:
UIViewController topViewControllerWithRootViewController(UIViewController rootViewController)
{
if (rootViewController is UITabBarController)
{
UITabBarController tabBarController = (UITabBarController)rootViewController;
return topViewControllerWithRootViewController(tabBarController.SelectedViewController);
}
else if (rootViewController is UINavigationController)
{
UINavigationController navigationController = (UINavigationController)rootViewController;
return topViewControllerWithRootViewController(navigationController.VisibleViewController);
}
else if (rootViewController.PresentedViewController != null)
{
UIViewController presentedViewController = rootViewController.PresentedViewController;
return topViewControllerWithRootViewController(presentedViewController);
}
return rootViewController;
}
Secondly, adjust your presenting code like:
Device.BeginInvokeOnMainThread(() =>
{
try
{
alert = UIAlertController.Create("", messages, UIAlertControllerStyle.ActionSheet);
topViewControllerWithRootViewController(UIApplication.SharedApplication.KeyWindow.RootViewController).PresentViewController(alert, true, null);
}
catch (Exception ex)
{
var Error = ex.Message;
}
});
At last, you could show your toast using Navigation.PushModalAsync(new RegisterPage());

Calling Async task in button click in xamarin.forms

I have xamarin.forms app contains a listview which will load values from Rest API.Which is working fine.I have button just above the listview.When I click on the button, the listview API call will be placed again and the listview should update. But stuck at this update part.I am not using MVVM pattern.The listview listing portion is an async Task.I am calling the async task again when the button click, but App gets crash. Is it due to calling the async task again from button click? Any help is appreciated.
Here is My code.
namespace app
{
public partial class List : ContentPage
{
PendingWeekRange pendingWeekRange = new PendingWeekRange();
public TimeSheetList()
{
InitializeComponent();
Task.Run(async () =>
{
await LoadScreenItems();
});
}
async Task LoadScreenItems()
{
await Task.Run(async () => {
try
{
// Doing some stuff
await loadTimeSheetList();
}
catch (Exception)
{
}
});
}
async Task loadTimeSheetList()
{
await Task.Run(() => { + string postdataForPendingList = "{\"date\":\"" + "1" + "\"}";
APICall callForAPICallResult = new APICall("/API/ListMobile/ListForApproval", postdataForList, loadingIndicator);
try
{
List<ListData> resultObjForPendingTimeSheetList = callForAPICallResult<List<ListData>>();
if (resultObjForPendingTimeSheetList != null)
{
TimesheetList.ItemsSource = resultObjForPendingTimeSheetList;
screenStackLayout.VerticalOptions = LayoutOptions.FillAndExpand;
TimesheetList.IsVisible = true;
}
else
{
}
}
catch (Exception)
{
}
});
}
async void Button_Tapped(object sender, EventArgs e)
{
try
{
// Calling my listview again. After calling app gets crash
Task.Run(async () => await loadTimeSheetList());
}
catch (Exception ex) { }
}
}
}
A few things before getting to the problem. You've got async/await all wrong, go though Async Programming
Task.Run runs the passed action on a different thread, if you make changes to UI elements on this thread, your app will definitely(take my word) crash.
If you want to make async call at page launch, make use of OnAppearing method (if you only want to call once, maintain a flag)
Do not change the ItemsSource of a list view frequently, just clear and add items to it.
namespace app
{
public partial class List : ContentPage
{
PendingWeekRange pendingWeekRange = new PendingWeekRange();
private ObservableCollection<ListData> TimesheetObservableCollection = new ObservableCollection<ListData>();
public TimeSheetList()
{
InitializeComponent();
TimesheetList.ItemsSource = TimesheetObservableCollection;
}
protected override async OnAppearing()
{
// flag for first launch?
await LoadScreenItems();
}
async Task LoadScreenItems()
{
try
{
// Doing some stuff
TimesheetObservableCollection.Clear();
TimesheetObservableCollection.AddRange(await GetTimeSheetList());
}
catch (Exception)
{
//handle exception
}
}
async Task<List<ListData>> GetTimeSheetList()
{
string postdataForPendingList = "{\"date\":\"" + "1" + "\"}";
APICall callForAPICallResult = new APICall("/API/ListMobile/ListForApproval", postdataForList, loadingIndicator);
try
{
return callForAPICallResult<List<ListData>>();
}
catch (Exception)
{
// handle exception
}
}
async void Button_Tapped(object sender, EventArgs e)
{
try
{
// Calling my listview again. After calling app gets crash
TimesheetObservableCollection.Clear();
TimesheetObservableCollection.AddRange(await GetTimeSheetList());
}
catch (Exception ex) { }
}
}
}
#Androdevil,
Update your loadTimeSheetList with this,
async Task loadTimeSheetList()
{
try
{
// I am calling my API for Listview here.
List<TimeSheetListData> resultObjForPendingTimeSheetList = await callForPendingTimeSheetList.APICallResult<List<TimeSheetListData>>();
if (resultObjForPendingTimeSheetList != null)
{
TimesheetList.ItemsSource = resultObjForPendingTimeSheetList;
screenStackLayout.VerticalOptions = LayoutOptions.FillAndExpand;
TimesheetList.IsVisible = true;
}
else
{
}
}
catch (Exception)
{
}
}

Xamarin forms: Selected picture is not showing in UI from gallery and camera for IOS

Complete Scenario
I have an add icon on one page, it will show camera and gallery options when tap. If choose the camera, I will open another content page and open camera there. But the captured picture is not showing in the UI. Same for the gallery, selected image from the gallery is not showing in UI. This feature is working fine in android and not working in IOS.
Codes
When click add icon
string action = await DisplayActionSheet(null, "Cancel", null, "Camera", "Gallery");
if (action == "Camera")
{
await Navigation.PushModalAsync(new NewTweetPage("Camera"));
}
else if (action == "Gallery")
{
await Navigation.PushModalAsync(new NewTweetPage("Gallery"));
}
When entering next page
public NewTweetPage(String medium)
{
InitializeComponent();
if (medium == "Camera" )
{
OpenMyCamera();
}
else if(medium == "Gallery")
{
OpenMygallery();
}
}
public async void OpenMyCamera()
{
try
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("Camera", "No camera available.", "OK");
return;
}
_mediaFile = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "Sample",
Name = "test.jpg",
AllowCropping = true
});
if (_mediaFile == null)
return;
tweetPicture.Source = ImageSource.FromStream(() =>
{
isPicture = true;
return _mediaFile.GetStream();
});
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception:>" + ex);
}
}
public async void OpenMygallery()
{
try
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsPickPhotoSupported)
{
await DisplayAlert("Gallery", ":( No photos available.", "OK");
return;
}
_mediaFile = await CrossMedia.Current.PickPhotoAsync();
if (_mediaFile == null)
return;
tweetPicture.Source = ImageSource.FromStream(() =>
{
isPicture = true;
return _mediaFile.GetStream();
});
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception:>" + ex);
}
}
The same code is working fine in profile page part, but in that case, there is no page navigation, everything is happening on the same page.
Don't know what is the problem with the current code, please help me to solve this issue.
Putting navigation commands in the constructor can cause issues. I would recommend putting them in the OnAppearing override. Also, instead of having a try...catch around a large section of code, you should handle null-checks or similar in code.

How to give keycodes from a properties file in javafx

Currently i have configured JavaFX keyEvents for key board controllers for each task. What i want is to configure there keys from a properties file rather than hard coding in the code.
The implementation :
final KeyCombination keyCombinationShiftC = new KeyCodeCombination(
KeyCode.ENTER, KeyCombination.CONTROL_DOWN);
javafx.event.EventHandler<javafx.scene.input.KeyEvent> handler = event -> {
if (keyCombinationShiftC.match(event)) {
try {
if (finalSubTotalPrice > 0) {
paymentAction();
} else {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle(app.values.getProperty("WARNING_TITLE"));
alert.setHeaderText(app.values.getProperty("INVALID_NO_OF_ITEMS"));
alert.setContentText(app.values.getProperty("INVALID_NO_OF_ITEMS_DIALOG"));
alert.showAndWait();
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
switch (event.getCode()) {
case F10:
try {
removeAction();
} catch (Exception e1) {
e1.printStackTrace();
}
break;
case F1:
try {
searchField.requestFocus();
} catch (Exception e1) {
e1.printStackTrace();
}
break;
case F5:
try {
customVatDiscountCalculation();
} catch (Exception e1) {
e1.printStackTrace();
}
break;
}
The ENTER+CNTRL_DOWN, F5, F10, F1 keys need to be assign for other keys without changing the code using a properties file.
If i try to get the Strings from the properties file, i fail to do that. as below. It says a constant expression is required for the case.
public static final KeyCode REMOVE_KEY = KeyCode.getKeyCode(app.values.getProperty("REMOVE_KEY"));
switch (event.getCode()) {
case REMOVE_KEY:
try {
removeAction();
} catch (Exception e1) {
e1.printStackTrace();
}
break;
}

JavaFX8 change from predicate binding to KeyPress action instead

I have a TableView with textboxes in each column. If I write something in one of the textboxes, the tableview gets filtered based on all the textboxes. For now the code I have listens to change in the textboxes, and filters as soon as the text changes. The following code works fine, but is it any way to make it more efficient?
Probably the best way would be to listen to a enter press instead of filtering on every change in the textfield? Does predicateProperty support this? If not, how can I change from predicateProperty/binding to onKey press instead?
filteredItems.predicateProperty().bind(Bindings.createObjectBinding(()
-> li -> {
for (int i = 0; i < li.size(); i++) {
{
if (!li.get(i).toLowerCase().
contains(
listOfTxtFields.get(i).getText().toLowerCase()
)) {
return false;
}
}
}
return true;
},
listOfTxtFields.stream().map(TextField::textProperty)
.collect(Collectors.toList())
.toArray(new StringProperty[listOfTxtFields.size()])));
I actually managed to fix this by some experimenting. It's pretty efficient, but could be a tad faster when it becomes tons of rows, so if you have any suggestions to making it faster, I would love to hear them. This is what I did:
Created a method that will be called each time a user presses enter on a textField in the columns:
void filter() {
DateTest dateTest = new DateTest();
filteredItems.setPredicate(li -> {
for (int i = 0; i < li.size(); i++) {
if (dateTest.isValidDate(listOfTxtFields.get(i).getText().replace("a", "").replace("b", ""))) {
try {
dateTest.isValidDate(li.get(i));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse(li.get(i));
Date date2 = sdf.parse(listOfTxtFields.get(i).getText().replace("a", "").replace("b", ""));
if (listOfTxtFields.get(i).getText().contains("a")) {
if (date1.after(date2)) {
return true;
}
}
if (listOfTxtFields.get(i).getText().contains("b")) {
if (!date1.before(date2)) {
return false;
}
} else {
if (!date1.equals(date2)) {
return false;
}
}
} catch (ParseException ex) {
Logger.getLogger(Table.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
if (!li.get(i).toLowerCase().
contains(
listOfTxtFields.get(i).getText().toLowerCase()
)) {
return false;
}
}
}
return true;
});
}

Resources