JavaFX UI freeze hang - user-interface

My JavaFX app's UI freezes after consecutive times of executing webservice calls. Those process calls are asynchronous.
How do I fix this problem? Is there a way to "unfreeze" the UI?
Sorry for the newbie question. But I badly need anyone;'s help

Did you create a thread to execute it? JavaFX is executed on the EDT (event dispatch thread). That is why you experience GUI freeze. Here is what you do
import javafx.async.*
public class MyWebService extends RunnableFuture {
public var webserviceURL:String;
override run(): Void {
// your web service
}
}
public class MyWebServiceTask extends JavaTaskBase {
override create(): RunnableFuture {
return MyWebService {
webserviceURL: "http://...."
};
}
}
def webserviceTask: MyWebServiceTask = MyWebServiceTask { }
webserviceTask.start();

Related

Spring Boot Cucumber Java 8 Testing ApplicationOnReady Event

I have a reporting application that generates a report on ApplicationReadyEvent. I am trying to write cucumber tests for it but as the application event is fired even before my feature is executed , i am not sure what is the right way to test it. Can i control the event during testing ?
#EventListener(ApplicationReadyEvent.class)
private void generateAccuracyAnalysisReport() throws IOException
{
//some Logic
}
Cucumber Classes :
#SpringBootTest
#CucumberContextConfiguration
#ActiveProfiles("junit")
public class CucumberConfiguration
{
}
#RunWith(Cucumber.class)
#CucumberOptions(plugin = "pretty", features = "src/test/resources/cucumber/features")
public class CucumberFullIntegrationTest
{
}
Step Definition:
public class ReportStepDefs implements En {
public ReportStepDefs() {
When("^System sends an application event to generate report$", () -> {
});
Then("^Report should be generated successfully\\.$", () -> {
});
}
}
If your Cucumber tests involve Spring life-cycle you can not use cucumber-spring. Rather you have to use something like Springs ApplicationContextRunner to, configure, run and verify something about your application as part of each scenario.
// Given
ApplicationContextRunner contextRunner = new ApplicationContextRunner();
// When
contextRunner.withConfiguration(AutoConfigurations.of(...);
// Then
contextRunner.run(context -> assertThat(context).... /* something */ );
// Or assert something external to the application context.
Though it sounds like your application is doing something once and then exits. If so you should be using the CommandLineRunner instead of ApplicationReadyEvent in a web application. This is testable with cucumber-spring.
#RequiredArsConstructor
public class StepDefinitions {
final MyCommandLineRunner commandLineRunner;
#When(....)
public void something() {
commandLineRunner.run("input.txt", "input2.txt");
}
#Then(....)
public void assertSomething() {
// check if report was generated
}
}

How to work with IActivityLifecycleCallbacks with MVVMCross?

I am new to MVVMCross. I need to get details about whether my android application is running in background or not. To achieve this i have try to implement with IActivityLifecycleCallbacks with MVXApplication.But i get following error "implements Android.Runtime.IJavaObject but does not inherit Java.Lang.Object or Java.Lang.Throwable. This is not supported.". So could anyone suggest me to how to achieve my requirement with MVVM cross.
You can implement that interface in your main application of your Android project and on the OnTrimMemory comparing the level with TrimMemory.UiHidden you can know if the app is in background or not.
public class MainApplication : Application, Application.IActivityLifecycleCallbacks
{
...
public static bool IsApplicationInForeground { get; private set; }
public override void OnCreate()
{
base.OnCreate();
this.RegisterActivityLifecycleCallbacks(this);
}
public override void OnTerminate()
{
base.OnTerminate();
this.UnregisterActivityLifecycleCallbacks(this);
}
public virtual void OnActivityResumed(Activity activity)
{
IsApplicationInForeground = true;
}
public override void OnTrimMemory(TrimMemory level)
{
IsApplicationInForeground &= level != TrimMemory.UiHidden;
base.OnTrimMemory(level);
}
...
}
IDK if it covers all of the cases but I use it in my projects and it works like a charm in the scenarios I've tested
HIH

Using FluentScheduler - ASP.NET Core MVC

I currently have a simple website setup with ASP.NET Core MVC (.NET 4.6.1), and I would like to periodically do some processes like automatically send emails at the end of every day to the registered members.
After doing some searching, I came across two common solutions - Quartz.NET and FluentScheduler.
Based on this SO thread, I found the approach of using FluentScheduler more easier to digest and use for my simple task. After quickly implementing the following lines of code into my Program.cs class, I had the emails going out successfully every minute (for testing purposes).
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
var registry = new Registry();
JobManager.Initialize(registry);
JobManager.AddJob(() => MyEmailService.SendEmail(), s => s
.ToRunEvery(1)
.Minutes());
host.Run();
}
}
However, now apart from sending emails I also need to do some back-end processing for e.g. updating the user records in the DB when mails are being sent out. For this, I normally inject my Entity Framework Context into the constructor of my controllers and use it to get/update SQL records.
My question is, since I cannot really inject these services into the main method, where would be the appropriate place to initialize the registry and add jobs for scheduling?
Thanks for the help, I am a little new to this so a little guidance would be much appreciated!
Instead of Program's Main function, I initialized the same in Startup.cs before app.UseMvc..
public void Configure(...., IDependencyObject dependencyObject)
{
....
JobManager.Initialize(new MyRegistry(dependencyObject));
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "api/{controller}/{action}/{id?}");
});
}
My registry class looks like this:
public class MyRegistry: Registry
{
public MyRegistry(IDependencyObject dependencyObject)
{
Schedule(() => new SyncUpJob(dependencyObject)).ToRunNow().AndEvery(10).Seconds();
}
}
My Job class looks like this:
public class SyncUpJob: IJob
{
public SyncUpJob(IDependencyObject dependencyObject)
{
DependencyObject= dependencyObject;
}
public IDependencyObject DependencyObject{ get; set; }
public void Execute()
{
// call the method to run weekly here
}
}
You can define all your jobs and their schedules, by subclassing from FluentScheduler Registry class. something like:
public class JobRegistry : Registry {
public JobRegistry() {
Schedule<EmailJob>().ToRunEvery(1).Days();
Schedule<SomeOtherJob>().ToRunEvery(1).Seconds();
}
}
public class EmailJob : IJob {
public DbContext Context { get; } // we need this dependency, right?!
public EmailJob(DbContext context) //constructor injection
{
Context = context;
}
public void Execute()
{
//Job implementation code: send emails to users and update database
}
}
For injecting dependencies into jobs, you need to implement FluentScheduler IJobFactory interface. GetJobIntance method is called by FluentScheduler for creating job instances. Here you can use any DI library you want; In this sample implementation, I'm going to assume that you use Ninject:
public class MyNinjectModule : NinjectModule {
public override void Load()
{
Bind<DbContext>().To<MyDbContextImplemenation>();
}
}
public class JobFactory : IJobFactory {
private IKernel Kernel { get; }
public JobFactory(IKernel kernel)
{
Kernel = kernel;
}
public IJob GetJobInstance<T>() where T : IJob
{
return Kernel.Get<T>();
}
}
Now you can start your jobs in main method by calling:
JobManager.JobFactory = new JobFactory(new StandardKernel(new MyNinjectModule()));
JobManager.Initialize(new JobRegistry());

GwtEvent does not get dispatched

I have an application that uses EventBus for dispatching Application wide events. For some reason if I call one event and then try to register handler immediately before firing the second event it does not get dispatched. Is there any other way to dynamically register handlers on event ? Please see the code below:
MyEntry.java
package com.example.eventbus.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
public class MyEntry
implements EntryPoint {
SimpleEventBus bus;
#Override
public void onModuleLoad() {
bus = new SimpleEventBus();
fireEvent1();
}
private void fireEvent1(){
bus.addHandler(MyEvent1.TYPE,new MyEvent1.Handler() {
#Override
public void onEvent1(MyEvent1 event) {
RootPanel.get().add(new Label("Event1"));
fireEvent2();
}
});
bus.fireEvent(new MyEvent1());
}
private void fireEvent2(){
bus.addHandler(MyEvent2.TYPE,new MyEvent2.Handler() {
#Override
public void onEvent2(MyEvent2 event) {
RootPanel.get().add(new Label("Event2")); //!!!!!This line is not being called
}
});
bus.fireEvent(new MyEvent2());
}
}
MyEvent1.java
package com.example.eventbus.client;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
public class MyEvent1 extends GwtEvent<MyEvent1.Handler>{
public static Type<MyEvent1.Handler> TYPE=new Type<MyEvent1.Handler>();
#Override
public com.google.gwt.event.shared.GwtEvent.Type<Handler> getAssociatedType() {
return TYPE;
}
#Override
protected void dispatch(Handler handler) {
System.out.println("dispatch Event1");
handler.onEvent1(this);
}
public interface Handler extends EventHandler{
public void onEvent1(MyEvent1 event);
}
}
MyEvent2.java
package com.example.eventbus.client;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
public class MyEvent2 extends GwtEvent<MyEvent2.Handler>{
public static Type<MyEvent2.Handler> TYPE=new Type<MyEvent2.Handler>();
#Override
public com.google.gwt.event.shared.GwtEvent.Type<Handler> getAssociatedType() {
return TYPE;
}
#Override
protected void dispatch(Handler handler) {
System.out.println("dispatch Event2"); //!!!! This line is never called
handler.onEvent2(this);
}
public interface Handler extends EventHandler{
public void onEvent2(MyEvent2 event);
}
}
The issue is that while an event bus is firing events, it queues up any added or removed handler, and deals with them when it is finished. The idea is that if you only start listening to something while another event is still going off, then you are not interested for this round of events, but for the next round. The same thing happens when removing a handler - you will still hear about events that are still in the process of happening, but after the event bus is finished firing, it will deal with removal.
Try changing your code to wire up both handlers before firing anything, then try firing one event to the other.
Let me suggest to take a try to a new feature in gwtquery called 'custom events'.
We have introduced the new events mechanism during the recent GWT.create conferences, take a look to this slide (use arrows to move between slides).
You can attach custom events to any element in the DOM tree, widgets, and the window element.
Then you can trigger the event from any point in your code and every handler with this custom event name will be executed.
The main goal of the gQuery approach apart from being simpler, is that it performs significantly better than gwt eventbus, since the native browser selects in a low-level way which handlers to execute instead of using javascript to loop over a list, and execute handlers sequentially.
You might want to check out GWTP #ProxyEvent:
So when should you use #ProxyEvent? Basically, you use it every time that an event should have the ability to “wake up” your presenter. That is, whenever the presenter should be notified of an event even before it is first instantiated.

Android basics: running code in the UI thread

In the viewpoint of running code in the UI thread, is there any difference between:
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
}
});
or
MainActivity.this.myView.post(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
}
});
and
private class BackgroundTask extends AsyncTask<String, Void, Bitmap> {
protected void onPostExecute(Bitmap result) {
Log.d("UI thread", "I am the UI thread");
}
}
None of those are precisely the same, though they will all have the same net effect.
The difference between the first and the second is that if you happen to be on the main application thread when executing the code, the first one (runOnUiThread()) will execute the Runnable immediately. The second one (post()) always puts the Runnable at the end of the event queue, even if you are already on the main application thread.
The third one, assuming you create and execute an instance of BackgroundTask, will waste a lot of time grabbing a thread out of the thread pool, to execute a default no-op doInBackground(), before eventually doing what amounts to a post(). This is by far the least efficient of the three. Use AsyncTask if you actually have work to do in a background thread, not just for the use of onPostExecute().
I like the one from HPP comment, it can be used anywhere without any parameter:
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Log.d("UI thread", "I am the UI thread");
}
});
There is a fourth way using Handler
new Handler().post(new Runnable() {
#Override
public void run() {
// Code here will run in UI thread
}
});
The answer by Pomber is acceptable, however I'm not a big fan of creating new objects repeatedly. The best solutions are always the ones that try to mitigate memory hog. Yes, there is auto garbage collection but memory conservation in a mobile device falls within the confines of best practice.
The code below updates a TextView in a service.
TextViewUpdater textViewUpdater = new TextViewUpdater();
Handler textViewUpdaterHandler = new Handler(Looper.getMainLooper());
private class TextViewUpdater implements Runnable{
private String txt;
#Override
public void run() {
searchResultTextView.setText(txt);
}
public void setText(String txt){
this.txt = txt;
}
}
It can be used from anywhere like this:
textViewUpdater.setText("Hello");
textViewUpdaterHandler.post(textViewUpdater);
As of Android P you can use getMainExecutor():
getMainExecutor().execute(new Runnable() {
#Override public void run() {
// Code will run on the main thread
}
});
From the Android developer docs:
Return an Executor that will run enqueued tasks on the main thread associated with this context. This is the thread used to dispatch calls to application components (activities, services, etc).
From the CommonsBlog:
You can call getMainExecutor() on Context to get an Executor that will execute its jobs on the main application thread. There are other ways of accomplishing this, using Looper and a custom Executor implementation, but this is simpler.
If you need to use in Fragment you should use
private Context context;
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
((MainActivity)context).runOnUiThread(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
}
});
instead of
getActivity().runOnUiThread(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
}
});
Because There will be null pointer exception in some situation like pager fragment
use Handler
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// Code here will run in UI thread
}
});
Kotlin version:
Handler(Looper.getMainLooper()).post {
Toast.makeText(context, "Running on UI(Main) thread.", Toast.LENGTH_LONG).show()
}
Or if you are using Kotlin coroutines:
inside coroutine scope add this:
withContext(Dispatchers.Main) {
Toast.makeText(context, "Running on UI(Main) thread.", Toast.LENGTH_LONG).show()
}

Resources