I'm receiving illegalstatexception when executing method from Timer - blackberry

When I run my method from the constructor of the mainscreen it works, but if invoked in the timer then I get the error.
Here is my method:
public void buildDesc(){
try {
JSONObject event = array.getJSONObject(currentPage);
String title = event.getString("title");
String by = event.getString("by");
String by_name = event.getString("by_name");
String summary = event.getString("summary");
int nid = event.getInt("nid");
vfm.add(new LabelField(title));
System.out.println("The Title:"+title);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And the timer:
timer = new Timer();//Create the timer to loop the events every 5 seconds
timer.scheduleAtFixedRate(new TimerTask(){
public void run() {
currentPage++;
if(currentPage > 3){
currentPage = 0;
}
System.out.println("Page Position:"+pagePosition(currentPage+1));
gallery.setHorizontalScroll(pagePosition(currentPage));
buildDesc();
}
}, 0, 10000);
I read a Android question that says, perhaps, I can't make changes to the UI if not on the UIThread?

I think your hunch is right, in BlackBerry you shouldn't do any work on the Ui thread. I guess the Timer thread is getting terminated for it's behaviour which is why you are getting an IllegalStateException. A quick guide to the UI thread can be found here.
Try :
timer = new Timer();//Create the timer to loop the events every 5 seconds
timer.scheduleAtFixedRate(new TimerTask(){
public void run() {
currentPage++;
if(currentPage > 3){
currentPage = 0;
}
System.out.println("Page Position:"+pagePosition(currentPage+1));
synchronized(UiApplication.getUiApplication().getEventLock())) {
// UI Code here
gallery.setHorizontalScroll(pagePosition(currentPage));
buildDesc();
}
}
}, 0, 10000);
Note: The above is untested.

Related

MQL4 Listenting to Candle Bar Open event

I am really new to MQL4, and still trying to grasp the concept. I would want to have an event handler to detect every candle bar opening (or every previous candle bar closing). Trying to wrap that around my head but it is not working:
So I have a function to check for the tick:
bool checkingFirstTick(){
datetime currentTime = iTime(Symbol(), Period(), 0);
if(currentTime - lastCandle > 0){
lastCandle = currentTime;
return true;
}
return false;
}
where lastCandle is a global variable.
Now when I put it into the OnTick() event:
void OnTick(){
Print("Ticking");
if(checkingFirstTick()){
Print("It's an opening!");
}
}
The It's an opening! statement never get printed.
Am I doing something fundamentally wrong? Or is there any more efficient way to listen to an opening of the candle bar, no matter what is the period I set?
Try this:
// --- Global Variable ----
datetime ArrayTime[], LastTime;
void OnTick() {
if(NewBar(PERIOD_H1)) {
// insert your program here
}
}
bool NewBar(int period) {
bool firstRun = false, newBar = false;
ArraySetAsSeries(ArrayTime,true);
CopyTime(Symbol(),period,0,2,ArrayTime);
if(LastTime == 0) firstRun = true;
if(ArrayTime[0] > LastTime) {
if(firstRun == false) newBar = true;
LastTime = ArrayTime[0];
}
return newBar;
}

How to delete a Dart future when it's no longer needed

This is related to is there any way to cancel a dart Future?
In my case, there are no HTTP, just expensive calculations. I have a table/list which I scroll through. As the elements become visible, I generate futures to show the calculation results. But if I (the end user) scroll quickly, some results will have "scrolled out of view" and will no longer required. This could be a large number, and would seriously delay the return of futures (results) that are to be usefully :-) displayed in currently visible elements. Can something be done about that? cheers, Steve
You could just set a flag which indicates to the delayed code (run from futures) that the result isn't needed anymore.
When the delayed code is called it just returns.
library cancel_future;
import 'dart:async' show Future, Timer;
import 'dart:math' show Random;
typedef void TaskFunction(Task task);
// Container for a task
class Task {
// an assigned task id
final id;
// data to process
int data;
// Indicate to the task function, that it should stop processing
bool isCanceled = false;
// The task function must set this flat to true when all work is done.
bool isFinished = false;
// The task function which processed the data and sets the result.
TaskFunction fn;
// The result set by the task function when it finished processing.
int result;
Task(this.id, this.data, this.fn);
// Start processing the task.
void execute() => fn(this);
}
final rnd = new Random();
void main(List<String> args) {
// create tasks
final tasks = new List<Task>.from(generate());
// start all tasks
tasks.forEach((t) => t.execute());
// after random delay cancel all unfinished tasks
new Future.delayed(new Duration(seconds: rnd.nextInt(10)), () {
tasks.forEach((t) {
if (!t.isFinished) {
t.isCanceled = true;
}
});
}).then((_) {
// check results
int done = 0;
int canceled = 0;
tasks.forEach((t) {
print(
'Task id: ${t.id}; isCanceled: ${t.isCanceled}; isFinished: ${t.isFinished}; data: ${t.data}; result: ${t.result}');
if (t.isFinished) {
done++;
}
if (t.isCanceled) {
canceled++;
}
});
print('Canceled: $canceled.');
print('Done: $done.');
});
}
// geneator for job 100 jobs
Iterable<Task> generate() sync* {
int i = 0;
while (i++ < 100) {
yield new Task(i, rnd.nextInt(100), calc);
}
}
// job function
void calc(Task t) {
// do a bit of work every 100ms to simulate longer processing
new Timer.periodic(new Duration(milliseconds: 100), (timer) {
var result = 0;
// check if jost was canceled and stop processing in case it was.
if (t.isCanceled) {
timer.cancel();
return;
}
// while not finished do a chunk of work
if (result < t.data) {
result++;
} else {
// finished - clean up and store result
t.isFinished = true;
t.result = result;
timer.cancel();
}
});
}

Updating a Button control with an NSTimer in Xamarin

I have created a very basic ios project that has a single button on it with it's title text property set to "Start". I am trying to have this button count down from 15.
I have added the event handler for the button as below.
void StartButton_TouchUpInside (object sender, EventArgs ea) {
_currentCount = 15;
_timer = NSTimer.CreateRepeatingScheduledTimer(TimeSpan.FromSeconds(1), () =>
{
if (_currentCount <= 0) {
StartButton.TitleLabel.Text = "Start";
_timer.Dispose();
} else {
string titleText = (_currentCount--).ToString ();
//Console.WriteLine(titleText);
StartButton.TitleLabel.Text = titleText;
//Console.WriteLine(StartButton.TitleLabel.Text);
//StartButton.SetNeedsDisplay();
}
});
}
So here is the strange thing. The Button changes to 15 just fine then it flashes back to "Start" then 14. Then 13 then "Start" then 12 etc... etc... etc...
Why is it doing this? And how do I prevent it from flashing back to start. Thanks in advance.
Try to use this.InvokeOnMainThread
private int counter = 0;
public override void WillActivate()
{
Console.WriteLine ("{0} will activate", this);
_timer = NSTimer.CreateRepeatingScheduledTimer(1, (timer) =>
{
this.InvokeOnMainThread(()=>{
Console.WriteLine("++++++++ NSTimer Call");
this.AlertTimeLabel.SetText(counter.ToString());
counter++;
});
});
}

How should I control the idle time of my app for this use case in BlackBerry?

I need to control the idle time of my app when the user is logged in.
This is my use-case:
When the idle time reaches the 4 minutes, an options dialog should be
displayed with the option to close it.
IF the user closes the dialog the dialog just closes
ELSE
the timer for the idle time should just continue and when it reaches the 5 minutes (1 minute later) the dialog must be closed.
a new message dialog must be displayed for 5 seconds.
after the 5 seconds the new dialog must be closed.
I must execute some code I already have to logout the user.
Actually, I have a working code but it's kind of nebulous.
To know the idle time, I do this: DeviceInfo.getIdleTime().
The method is controlled by a RealtimeClockListener, so when the user logs in, I do UiApplication.getUiApplication().addRealtimeClockListener and when it logs out I just do
UiApplication.getUiApplication().removeRealtimeClockListener.
I can post my code if needed but I really would like to see a new approach someone could suggest.
Update
This is the solution I'm using.
public static RealtimeClockListener realtimeClockListener = new RealtimeClockListener() {
int _4Minutes = 60 * 4;
int _5Minutes = 60 * 5;
int _5Seconds = 5 * 1000;
Dialog dialog4Minutes = null;
Dialog dialog5Minutes = null;
Timer timer5Seconds = null;
TimerTask timerTask5Seconds = null;
public void clockUpdated() {
if ( Application.getApplication().isForeground() ) {
appInactiveTime = (int) DeviceInfo.getIdleTime();
inForegroundFlag = true;
} else {
if ( inForegroundFlag ) {
appInactiveTime = 0;
} else {
appInactiveTime = appInactiveTime + 60;
}
inForegroundFlag = false;
}
synchronized (UiApplication.getEventLock()) {
UiEngine ui = Ui.getUiEngine();
if ( appInactiveTime < _4Minutes ){
if ( dialog4Minutes != null ) {
dialog4Minutes.close();
dialog4Minutes = null;
}
}
if ( appInactiveTime < _5Minutes ){
if ( dialog5Minutes != null ) {
dialog5Minutes.close();
dialog5Minutes = null;
}
}
if ( appInactiveTime >= _4Minutes && appInactiveTime < _5Minutes ) {
if ( dialog4Minutes == null ) {
dialog4Minutes = new Dialog("Stay Logged In?", new String[] {"SI", "NO"}, new int[]{1,2}, 2, null);
ui.pushGlobalScreen(dialog4Minutes, 1,UiEngine.GLOBAL_QUEUE);
}
} else if ( appInactiveTime >=_5Minutes ) {
if ( dialog5Minutes == null ) {
dialog5Minutes = new Dialog("You will be disconnected", new String[] {"OK"}, new int[]{1}, 1, null);
ui.pushGlobalScreen(dialog5Minutes, 1,UiEngine.GLOBAL_QUEUE);
timerTask5Seconds = new TimerTask() {
public void run() {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
dialog5Minutes.close();
try {
//logout in communication manager
//pop to initial screen
} catch (Exception e) {
//force logout (2nd way)
}finally{
UiApplication.getUiApplication().removeRealtimeClockListener(realtimeClockListener);
}
timerTask5Seconds.cancel();
timerTask5Seconds = null;
timer5Seconds.cancel();
timer5Seconds = null;
}
});
}
};
timer5Seconds = new Timer();
timer5Seconds.schedule(timerTask5Seconds, _5Seconds);
if ( dialog4Minutes != null ) {
dialog4Minutes.close();
dialog4Minutes = null;
}
}
}
}
}
};
Thanks Peter Strange!
I presume that you will use the RealtimeClockListener as a 'tick' that wakes up your application every minute. This works and is efficient, but does mean that your time out time will not be exactly 4 minutes - its actual duration will depend on whereabouts in the 'minute' the user becomes idle.
The trick is to determine what state your application is in when the tick happens or more accurately. I think the following sample code describes this, assuming that initially appInactiveTime is set to 0 and inForegrounFlag is true.
if ( Application.getApplication().isForeground() ) {
appInactiveTime = DeviceInfo.getIdleTime();
inForegrounFlag = true;
} else {
if ( inForegrounFlag ) {
// Was in foreground, start idle timing from now
appInactiveTime = 0;
} else {
appInactiveTime = appInactiveTime + 60;
}
inForegrounFlag = false;
}
I believe that using this code, appInactiveTime can now be used to find out if the app has been inactive for more than 4 minutes, by comparing it with 240 (60*4). .
At this point, your App should create and display a Global Screen, if you want it to show regardless of whether the app is in the Foreground or not. Then on the next tick, you can decide if you want to dismiss this screen or not, or if the user has dismissed it. I have the impression you need help with the timing rather than this part of the processing, so I will leave this with you.

How to stop progressbar in blackberry

In BlackBerry, my application is working perfectly fine. But one Requirement is when I load data from server, a progress bar is showing. If it takes so much time to load data from server, then I want to stop the progress bar. In BlackBerry, on back key pressed, it is not working. Please help me.
public class WaitScreen extends PopupScreen
{
public WaitScreen(String msg) {
super(new HorizontalFieldManager());
add(new LabelField(msg));
AnimatedGIFField testanimated = new AnimatedGIFField(
(GIFEncodedImage) (GIFEncodedImage.getEncodedImageResource("ajax_loader.gif")),
AnimatedGIFField.FIELD_HCENTER | AnimatedGIFField.FIELD_VCENTER);
add(testanimated);
}
}
public long timeout=0;
t.schedule(new TimerTask() {
public void run()
{
// TODO Auto-generated method stub
timeout+=1;
System.out.println("Timeout value:"+timeout);
if(timeout>=28)
{
//timeout every 1 munite
System.out.println("Timeout value:"+timeout);
System.out.println("closing connection");
try
{
parent.notifyDestroyed();
}
catch (Exception ex)
{
System.out.println("Exception is:"+ex);
}
this.cancel();
}
}
}, 0, 1000);
// Thread.sleep(30000);
httpconn_post = (HttpConnection) Connector.open(url);
httpconn_post.setRequestMethod(HttpConnection.POST);
httpconn_post.setRequestProperty("Accept_Language","en-US");
httpconn_post.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = httpconn_post.openOutputStream();
out.write(param.getBytes());
out.flush();
System.out.println("Status Line Code: " + httpconn_post.getResponseCode());
System.out.println("Status Line Message: " + httpconn_post.getResponseMessage());
if ( httpconn_post.getResponseCode()== HttpConnection.HTTP_OK )
{
is=httpconn_post.openDataInputStream();
// cancelling timer
t.cancel();
.....
.....
}
I had done this using this code..I had done it successfully..

Resources