I use xml parser to read asynctask parallel (multiple thread) in viewpager.
Here my problem is while I swipe my viewpager fastly app get crashed.
Here is my code
private void doTheAutoRefresh(final int n) {
final ExecutorService es = Executors.newFixedThreadPool(7);
//final CountDownLatch latch = new CountDownLatch(n);
t=new Thread(){
#Override
public void run() {
this.setPriority(10);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
load =new LoadWebPageASYNC(n);
load.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}else{
load=new LoadWebPageASYNC(n);
load.execute();}
}
};
t.setPriority(10);
es.execute(t);
}
Could you please help me what I am gets wrong.
I think the problem is with update current fragment.
I am new to android so please guide me for right direction.
I do not understand why you are creating a thread pool and then start single new Thread. At first sight it seems you do not want to call final ExecutorService es = Executors.newFixedThreadPool(7); every time you call doTheAutoRefresh
do you start a new Thread in LoadWebPageASYNC(n) as well ?
Maybe you can post the error message and a bit more code.
kind regards
Anton
Related
I've been looking for ages for direction on this matter and I finally post here.
I have a JavaFX application with MediaPlayer. One day, seeking at a later position in video (that had not been accessed previously) started hanging the player. No status change before it gets to PLAYING, the buffer is loaded, status at READY before I call seek().
First I thought it is because I went out of Application thread, tried to put the MediaPlayer back on the root to be sure, and the seek method worked as before, fast enough for me.
But then for a reason I can't get, it started hanging again all the time, with same symptoms.
Now, even with the most simple code, it hangs too.
I'm desperate, the waiting time can be 30 seconds to reach a position 2 minutes later in the video. Looks like the Media Player is scanning again all video until it finds the good position it's seeking, thus taking more time for a later position. If the position has been accessed before though, seek() won't hang...
Am I the only one with this problem?
I'm on Mac os EL Capitan, but tried on Windows VM too and I get the same behaviour.
Here is a standalone code, but I don't see how it will help, I don't even hope for ppl to reproduce:
public class VideoPlayerExample extends Application {
public static void main(String[] args) throws Exception {
launch(args);
}
#Override
public void start(final Stage stage) throws Exception {
File file = new FileChooser().showOpenDialog(stage);
Media media = new Media(file.toURI().toString());
MediaPlayer mp = new MediaPlayer(media);
mp.statusProperty().addListener(new ChangeListener<MediaPlayer.Status>() {
#Override
public void changed(ObservableValue<? extends Status> observable, Status oldValue, Status newValue) {
System.out.println(newValue);
}
});
Group gp = new Group(new MediaView(mp));
Button buttonTest = new Button("It's gonna hang...");
buttonTest.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
mp.pause();
System.out.println(mp.getCurrentTime().toMillis());
mp.seek(new Duration(mp.getCurrentTime().toMillis() +10000));
mp.play();
}
});
gp.getChildren().add(buttonTest);
stage.setScene(new Scene(gp, 540, 208));
stage.show();
}
}
Any help will be so greatly appreciated!
You're right - I can't reproduce your problem. I have macOS Sierra 10.12.6. All I can say is check the type of movie you're trying to play - not all encodings are supported. Also, according to the documentation, if the movie's duration is Duration.INDEFINITE, seek() will have no effect.
Place the seek method in a new thread not on your JavaFX thread.
new Thread(() -> mp.seek(new Duration(mp.getCurrentTime().toMillis() +10000)))).start();
I'm trying to get a responsive JavaFX graphical interface while executing a cmd command.
The command I'm executing is the following.
youtube-dl.exe --audio-format mp3 --extract-audio https://www.youtube.com/watch?v=l2vy6pJSo9c
As you see this is a youtube-downloader that converts a youtube link to an mp3-file.
I want this to be executed in a second thread and not in the main FX thread.
I've solved this by implementing interface Callable in the class StartDownloadingThread.
#Override
public Process call() throws Exception {
Process p = null;
p = ExecuteCommand(localCPara1, localCPara2, localDirectory).start();
try {
Thread.sleep(30);
}catch (InterruptedException e){}
return p;
}
The method ExecuteCommand just returns a ProcessBuilder object.
I try to use Thread.sleep to make the program return to the main thread and thus making the application responsive. Unfortunately the program still freezes.
This is how the method call is called.
ExecutorService pool = Executors.newFixedThreadPool(2);
StartDownloadingThread callable = new StartDownloadingThread(parameter1, parameter2, directory);
Future future = pool.submit(callable);
Process p = (Process) future.get();
p.waitFor();
How do I make my GUI responsive using the interface Callable?
Using a executor to run a task just for you to use the get method of the Future that is returned when submitting the task does not actually free the original thread to continue with other tasks. Later you even use the waitFor method on the original thread, which is likely to take even more time than anything you do in your Callable.
For this purpose the Task class may be better suited, since it allows you to handle success/failure on the application thread using event handlers.
Also please make sure an ExecutorService is shut down after you're done submitting tasks.
Task<Void> task = new Task<Void>() {
#Override
protected Void call() throws Exception {
Process p = null;
p = ExecuteCommand(localCPara1, localCPara2, localDirectory).start();
// why are you even doing this?
try {
Thread.sleep(30);
}catch (InterruptedException e){}
// do the rest of the long running things
p.waitFor();
return null;
}
};
task.setOnSucceeded(event -> {
// modify ui to show success
});
task.setOnFailed(event -> {
// modify ui to show failure
});
ExecutorService pool = Executors.newFixedThreadPool(2);
pool.submit(task);
// add more tasks...
// shutdown the pool not keep the jvm alive because of the pool
pool.shutdown();
I got some operations in my Controller class which could take some time. So I want to show a loading dialog while this operation is running.
I tried this:
Platform.runLater(new Runnable() {
#Override
public void run() {
loadingDialog.show();
}
});
Boolean opSuccess = myService.operate();
Platform.runLater(new Runnable() {
#Override
public void run() {
loadingDialog.hide();
}
});
if (opSuccess) {
// continue
}
Now, the Problem is, the loadingDialog is never show. The UI only blocks for some time and than continues on "//continue".
So it seems, the runLater call is blocked by the blocking operation (operate)?
I also tried CoundDownLatch, to wait for loadingDialog.show() to complete, before running myService.operate(). But the latch.await() method never completes.
So my question is, how my I show the loadingDialog until myService.operate() finished and returned true or false? Do I have to put the operate() call into another thread and run it async or is there an easier way?
Thanks for help.
Are you sure your entire code does not run in the JavaFX Thread?
Methods of your controller class usually do and I assume it due to your description.
However, better use the Task class. Here you'll find a tutorial and a short snippet for your application:
// here runs the JavaFX thread
// Boolean as generic parameter since you want to return it
Task<Boolean> task = new Task<Boolean>() {
#Override public Boolean call() {
// do your operation in here
return myService.operate();
}
};
task.setOnRunning((e) -> loadingDialog.show());
task.setOnSucceeded((e) -> {
loadingDialog.hide();
Boolean returnValue = task.get();
// process return value again in JavaFX thread
});
task.setOnFailed((e) -> {
// eventual error handling by catching exceptions from task.get()
});
new Thread(task).start();
I assumed Java 8 and the possibility to use Lambda expressions. Of course it is possible without them.
You are better off making use of concurrency mechanisms/Worker interfaces in JavaFx - Tasks and services instead of using Platform.runLater(). The tasks and services allow you to manage the long running tasks in a separate thread. They also provide callbacks to indicate the progress of the tasks.
You could explore further at http://docs.oracle.com/javafx/2/threads/jfxpub-threads.htm
Also have a look at the Ensemble JavaFX samples for Tasks and Services - http://www.oracle.com/technetwork/java/javase/overview/javafx-samples-2158687.html
I'm currently working on ListViews in Fragments. The Listviews are loaded by Cursorloader, but without ContentManager. So the code looks like this and it works:
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
Log.d("SoapERP", "onCreateLoader");
CursorLoader loader = new CursorLoader(getActivity()) {
final DBHelper dbhelper1= new DBHelper(getActivity());
#Override
public Cursor loadInBackground() {
Cursor c = null;
dbhelper1.open();
c = dbhelper1.fetchAllMatnameswithID();
// dbhelper1.close();
return c;
}
};
return loader;
My problem is that I get an LogCat-Error-Message that the database wasn't closed. But if I use dbhelper.close(); I get the Error "Database is already closed" wich is also understandable because it is just before the return statement. After the return statement code is not reachable and if I declare DBHelper dbhelper1 final the program crashes without any information in logcat. So what is my fail???
Finally I found here the right statement as of Dianne Hackborn from android framework development: "A content provider is created when its hosting process is created, and remains around for as long as the process does, so there is no need to close the database -- it will get closed as part of the kernel cleaning up the process's resources when the process is killed. Dianne Hackborn Android framework engineer hack...#android.com " - so let's use Content Provider.
I'm trying to get Quartz.net working by embedding into my .Net MVC2 application. I know this is not ideal, but I'm just trying to get it up and running before moving it over to a service. I can't get my jobs to fire off, but I think I'm configured correctly. In my Global.asax.cs:
protected void Application_Start()
{
Quartz.IScheduler scheduler = BuildQuartzScheduler();
...
}
And the method, taken straight from the tutorial:
private IScheduler BuildQuartzScheduler()
{
// construct a scheduler factory
ISchedulerFactory schedFact = new StdSchedulerFactory();
// get a scheduler
IScheduler sched = schedFact.GetScheduler();
sched.Start();
// construct job info
JobDetail jobDetail = new JobDetail("myJob", null, typeof(QuartzController));
// fire every hour
Trigger trigger = TriggerUtils.MakeMinutelyTrigger();
// start on the next even hour
trigger.StartTimeUtc = TriggerUtils.GetEvenMinuteDate(DateTime.UtcNow);
trigger.Name = "myTrigger";
sched.ScheduleJob(jobDetail, trigger);
return sched;
}
And the "controller:"
public class QuartzController : IJob
{
public QuartzController() {
}
public void Execute(JobExecutionContext context) {
throw new NotImplementedException();
}
}
Nothing ever gets fired. What's going on? I'm sure there must be a simple syntax mistake, but it is driving me crazy!
If Application_Start looks like that, then I reckon your scheduler variable is likely to be garbage collected as soon as that method finishes executing.
I'd store a reference to the scheduler as a static variable in your HttpApplication class. This way, the reference hangs around for the duration of the process. A guess, but worth a shot.