Cocos2D-X Layer::init() gets stuck when waiting for Leaderboard Service - cocos2d-x

I'm trying to integrate App42 Leaderboard Service to my Cocos2D-X Game. The core functionality (Sending Scores to Server and retrieving them, just the way shown on the App42 site...) is working fine.
Now i want to visualize my leaderboard data using a CCTableView.
So I got a Leaderboard class (inherited from CCLayer) and am doing something like this :
bool Leaderboard::init() {
...
// Initialize and send App42 Scoreboard API call
App42API::Initialize(API_KEY, SECRET_KEY);
ScoreBoardService *scoreBoardService = App42API::BuildScoreBoardService();
scoreBoardService->GetTopNRankers(gameName,MAX_SCORES, this,app42callfuncND_selector(Leaderboard::onGetTopNRankings));
// responseArrived is boolean, indicates if onGetTopRankings was called
while(!responseArrived);
CCTableView* tableView = CCTableView::create(this, CCSizeMake(400, 100));
tableView->setDirection(kCCScrollViewDirectionVertical);
tableView->setPosition(winSize.width/3 , winSize.height/2);
tableView->setDelegate(this);
tableView->setVerticalFillOrder(kCCTableViewFillTopDown);
this->addChild(tableView,5);
tableView->reloadData();
return true;
}
void HelloWorld::onGetTopNRankings(App42CallBack *sender, void *response){
App42GameResponse *scoreResponse = (App42GameResponse*)response;
if (scoreResponse->isSuccess)
{
// Save User scores to Array
responseScores = scoreResponse->scores;
}
else
{
printf("\nerrordetails:%s",scoreResponse->errorDetails.c_str());
printf("\nerrorMessage:%s",scoreResponse->errorMessage.c_str());
printf("\nappErrorCode:%d",scoreResponse->appErrorCode);
printf("\nhttpErrorCode:%d",scoreResponse->httpErrorCode);
}
// Response Data is saved, or Error occured, go back to init()
responseArrived = true;
}
So as you see, I am waiting for onGetTopNRankings to get called, because the data for my TableView would be empty else. But what happens is, that the I can't get back to init() when onGetTopNRankings returns, it gets stuck.
So anybody got an idea why i can't return to Leaderboard::init() or got any good idea to solve this in any other way, I am open for each suggestion ?

while(!responseArrived);
This blocks the thread (endless loop). You need to fill your table view in the callback method when you have actual data. It will be empty until then. That's something your app's design has to deal with. For instance you could display a "loading" animation in the meantime, with a cancel button on it.

I tested your code and it is working fine in my App42Cocos2dXSample
The only possible reason for the issue you are getting is the owner class name of callback method in your code snippet.
scoreBoardService->GetTopNRankers(gameName,MAX_SCORES,
this,app42callfuncND_selector(Leaderboard::onGetTopNRankings));
In the above statement, onGetTopNRankings belong to the class Leaderboard, but while defining the callback method, it belongs to the class Helloworld:
void HelloWorld::onGetTopNRankings(App42CallBack *sender, void *response){
So, try changing the class name from Helloworld to Leaderboard in the above statement. I hope it will work.

Related

Create delay in ActionScript 3 function

I have a function in Adobe Flex 4 (ActionScript 3) that accepts an object and returns an ArrayCollection...
If a certain global variable is set to true, I want the function to delay itself for 3 seconds before running. Otherwise I want the function to run as normal.
The problem is, if I use a Timer, that timer calls a separate function, and that function cannot return anything to my calling function, nor can the function it calls accept any parameters, so it's not like I can call my own function recursively after the TimerComplete event fires... And a recursive call wouldn't work anyway, because it would return the ArrayCollection to the timer-result function, not to the original calling function...
I need a delay within the function, not a delay that causes me to go outside that function. But I cannot figure out how to do it.
Something like this is what I need to do:
private function createArrayCollection(myObject:Object):ArrayCollection {
var myArrayCollection:ArrayCollection = new ArrayCollection();
if (globalWaitBoolean) {
//delay here for 3 seconds, somehow
}
//Here I do the stuff that uses the info in myObject to figure out what to
//put into the ArrayCollection I want to return
return (myArrayCollection);
}
So... Any ideas on how to accomplish this without calling an external Timer function that cannot return an object back to my original function?
Thanks,
The way you want it you will have your whole application to lag for 3 seconds, unresponsive to any user input and external events. But it is possible, sure:
import flash.utils.getTimer;
private function createArrayCollection(myObject:Object):ArrayCollection
{
var myArrayCollection:ArrayCollection = new ArrayCollection;
if (globalWaitBoolean)
{
var waitUntil:int = getTimer() + 3000;
// Method getTimer() returns time in ms passed since app start.
// So you just have to wait until it is greater than appointed time.
while (getTimer() < waitUntil)
{
// Do nothing.
}
}
return (myArrayCollection);
}
Still, if you want to do it in a correct way of doing it:
import flash.utils.setTimeout;
private function callerMethod():void
{
// Blah blah blah.
// ...
// Finally.
createArrayCollection(sourceData, asyncResult);
}
private function createArrayCollection(myObject:Object, handler:Function):void
{
var result:ArrayCollection = new ArrayCollection;
if (globalWaitBoolean) setTimeout(handler, 3000, result);
else handler(result);
}
private function asyncResult(source:ArrayCollection):void
{
// The rest of your processing code.
}
Normal (synchronous) code flow would not return until the value is prepared, so should you desire to actually wait for 3 seconds while not allowing your app to do anything, use getTimer() approach from #Organis's answer. If you'll go for an asynchronus result, you'll need to face and overcome some more problems.
First, when do you expect your returned ArrayCollection to actually arrive. Speaking of code design, asynchronous code requires a whole lot of assumptions, thread safety etc etc, and even while AS3/Flash does not have true multithreading unless you count Workers, the code flow with events is not as obvious. So, whoever called your createArrayCollection() MUST NOT expect value returned from it right away. So, speaking about your direct question, NO, you can't avoid timers of some sort if you desire a responsive application. But you can use them with an approach that would involve an indirectly returned result.
Second, whether there might be concurring requests for more array collections from objects if your app would require these - you have to prepare for any kind of interference that might be caused by this. Say your function is triggered by a button click - what if that button would get clicked more than once in 3 seconds?
Third, actual route to processing code is not direct with asynchronous return. You need either a callback, an event handler (which is essentially a semi-native callback), a code that periodically checks for value presence (enter frame handler, etc) or a similar trick to gather the value that's returned asynchronously, and then transfer it to any relevant code that would process it further. Therefore, you would need to design an interface capable of receiving complex data (source object forward, array collection backward) and then carefully test it against all the possible cases and flaws.
An example of implementing all that is very long, I'll try to outline it somehow. Ler's assume you have a sort of "server" class that accepts requests for data and processes it synchronously (no wait) or asynchronously (wait). It accepts a source object of type "T" and provides a newly created object of type ArrayCollection, supplied as a parameter to whatever callback function sent to it. Also it accepts a delay (a simple way to show sync/async return would be a boolean, but why not getting an int?) as a parameter, and guarantees (to the extent of event model limitations) that after this delay the callback will be called ASAP. The architecture will then look like this:
class Processor {
Dictionary requests; // here all the requests that are delayed will be stored
public function dpr(source:T,callback:Function,delay:int=0):void{...}
// creates requests and stores them
private function syncProcess(source:T):ArrayCollection {...}
// whatever routine you want to get variably delayed
private function processTimeout(e:Event=null):void {...}
// processes events from "setTimeout()" and calls callbacks
}
Note that asynchronous approach forced to create three more entities than a synchronous one. First is the request holding structure (the dictionary here), second is timeout event handler, third is whatever callback you'll desire to get called when the data is ready. The code flow would go like this:
Synchronous call would result in the callback directly called from within the class: request->processTimeout->syncProcess()->callback. Asynchronous call will have the callback called from within Timer::timerComplete event handler via setTimeout called within request, with data that originally came from request stored in requests.
You could use an embedded/inline function:
private function createArrayCollection(myObject:Object):ArrayCollection {
var myArrayCollection:ArrayCollection = new ArrayCollection();
if (globalWaitBoolean) {
var milliseconds:int = 3000;
//delay here for 3 seconds
setTimeout(function()
{
//Here I do the stuff that uses the info in myObject to figure out what to
//put into the ArrayCollection I want to return
return (myArrayCollection);
},
milliseconds);
}
else
{
//Here I do the stuff that uses the info in myObject to figure out what to
//put into the ArrayCollection I want to return
return (myArrayCollection);
}
}
The inner function will have access to all local vars of the outer function.

save load error 1010 array objects with sharedObjects as3

i cant figure out this one so maby you guys can help me out.
i store some data in the form of a array filled with Objects in this example cards.
in my main class i have the following code:
deckSprite.savedData = SharedObject.getLocal("cardsdata");
deckSprite.savedData.data.savedArray = deckSprite.deckArr;
deckSprite.savedData.flush();
trace(deckSprite.savedData.data.savedArray);
the trace will output something like [object card1, object card2, object card3]
now in a static class called "deckSprite" i have this:
savedData = sharedObject.getLocal("cardsdata");
if (savedData.data.savedArray == undefined)
{
trace("no save yet");
}
{
else
{
trace("save loaded");
deckArr = savedData.data.savedArray;
trace(savedData.data.savedArray);
now my trace data turns out only ", ," (somehow the cards are gone).
now after i got saved data i restart my application and whenever he tryes to acces the deckArr it crashes giving me the error "A term is undefined and has no properties".
how is it possible that when i save the array it saves all the cards inside the array and when i restart the application its suddenly only ",,"but the cards are gone?
When serializing objects in AS3, you have to register their class using registerClassAlias() from package flash.net. So you have to call something like
registerClassAlias('com.example.deck', Deck)
in the program before any saving or loading happens.
See full reference at AS3 API Reference
NOTE: As pointed out by #BadFeelingAboutThis in comments, you have to register all referenced class in your Deck, i.e. if your deck looks like this:
class Deck {
var firstCard:Card;
var type:DeckType;
}
to be able to save Deck to SharedObject you have to call
registerClassAlias('com.example.deck', Deck);
registerClassAlias('com.example.card', Card);
registerClassAlias('com.example.decktype', DeckType);
before any saving/loading is done.
EDIT
Everything depends on content of your array
If I assume, your deckSprite is declared like this:
var deck1:Deck = new Deck();
var deck2:Deck = new Deck();
var deckArr:Array = new Array(deck1, deck2);
var deckSprite:DeckSprite = new DeckSprite()
deckSprite.setDeckArr(deckArr);
then before adding deckArray to SharedObject, you have to call registerClassAlias(). Sou your save code will look like this:
registerClassAlias('com.example.deck', Deck);
deckSprite.savedData = SharedObject.getLocal("cardsdata");
deckSprite.savedData.data.savedArray = deckSprite.deckArr;
deckSprite.savedData.flush();
trace(deckSprite.savedData.data.savedArray);
(replace the Deck with actual class you use for representing your decks)
Similarly the first line has to be called before you do any loading.
Of course it is best not to repeat yourself, so you should call registerClassAlias('com.example.deck', Deck); only once in your program, so for example in some init() method in your main class, if you have something like that.

Deferring PropertyChanged events until view bindings setup complete

A number of our MVVMcross views depend remote services to fully display themselves. We typically kick this off a Task in ViewModel's Init() using to get it async. ViewModel properties are set in the Task upon completion, UI updated via PropertyChanged notifications.
Sometimes the remote data (and task) completes before the View has bound it's listeners and thus no property changed event is received.
This issue is touched on at async Init and Property Changed in MvvmCross but the solution feels like duplication of presentation logic.
We've had success buffering PropertyChanged notifications until the end of ViewDidLoad, but we'd like to turn below into a more generic solution by hooking into the MVX framework.
Is there a way to hook mvvmcross's view creation to fire our code off after viewDidLoad completes?
Base View Model
public abstract class BaseViewModel : MvxViewModel{
protected bool _deferPropertyChangedEvents = true;
private readonly List<PropertyChangedEventArgs> _deferedPropertyChangedEvents = new List<PropertyChangedEventArgs>();
public override void RaisePropertyChanged(PropertyChangedEventArgs changedArgs)
{
lock(_deferedPropertyChangedEvents){
if (!_deferPropertyChangedEvents)
{
base.RaisePropertyChanged(changedArgs);
}
else
{
// buffer it up
_deferedPropertyChangedEvents.Add(changedArgs);
}
}
}
public void EndDeferringPropertyChangedEvents()
{
lock(_deferedPropertyChangedEvents){
_deferPropertyChangedEvents = false;
// playback all buffered notifications
foreach (var e in _deferedPropertyChangedEvents)
{
RaisePropertyChanged(e);
}
_deferedPropertyChangedEvents.Clear();
}
}
}
Sample view
public class SomeView : MvxViewController
{
public override void ViewDidLoad()
{
base.ViewDidLoad();
var bindings = this.CreateBindingSet<StopView, SomeViewModel>();
.....
bindings.Apply();
// plays back any PropertyChanged() notifications that were buffered
// up while the view was initializing
// ---> want to find a way to have MVX call this
ViewModel.EndDeferringPropertyChangedEvents();
}
}
As a simple answer, I believe your own line can easily be called using a BaseViewModel cast:
// ---> want to find a way to have MVX call this
((BaseViewModel)ViewModel).EndDeferringPropertyChangedEvents();
However, on a more technical note, I think it might be useful to further examine and understand why this Deferring code is necessary - to further take a look at what the underlying threading problems are.
There are a number of factors that are puzzling me at present::
During the line bindings.Apply(); all current bound property values should be transferred from the ViewModel to the View - so calling EndDeferringPropertyChangedEvents(); in the next line should (in theory) only rarely get different values.
Further, the default MvvmCross RaisePropertyChanged method changed notifications across to the UI thread. Because ViewDidLoad is also invoked on the UI thread, this means that any RaisePropertyChanged calls made on background threads during ViewDidLoad should all be automatically deferred until after ViewDidLoad has finished and the UI thread becomes available.
Looking at the MvxNotifyPropertyChanged code, the only potential gap I can see where mutli-threading might find a way through this automatic RaisePropertyChanged deferral is in this optimisation check:
// check for subscription before potentially causing a cross-threaded call
if (PropertyChanged == null)
return;
(from https://github.com/MvvmCross/MvvmCross/blob/v3.1/Cirrious/Cirrious.MvvmCross/ViewModels/MvxNotifyPropertyChanged.cs#L76)
If your ViewModel Init method is also using async for it's Task management, then this async code should also be using the UI thread - so the "callback" of this async operation should also be marshalled back to the UI thread (and so shouldn't be executed during ViewDidLoad itself).
As I said, these factors are puzzling me - I don't have a definitive answer/explanation - sorry! But I'd love to see an example problem and to try to help solve it at a generic level.

Remove ViewController from stack

In our App we have a log-in ViewController A. On user log-in, a request navigate is automatically called to navigate to the next ViewController B. However when this is done we want to remove the log-in ViewController A from the stack so the user cannot "go back" to the log-in view but goes back the previous ViewController before the log-in instead.
We thought about removing the ViewController A from the stack when ViewController B is loaded, but is there a better way?
In the Android version of the App we've set history=no (if I recall correctly) and then it works.
Is there an similar way to achieve this in MonoTouch and MvvmCross?
I ended up with removing the unwanted viewcontroller from the navigation controller. In ViewDidDisappear() of my login ViewController I did the following:
public override void ViewDidDisappear (bool animated)
{
if (this.NavigationController != null) {
var controllers = this.NavigationController.ViewControllers;
var newcontrollers = new UIViewController[controllers.Length - 1];
int index = 0;
foreach (var item in controllers) {
if (item != this) {
newcontrollers [index] = item;
index++;
}
}
this.NavigationController.ViewControllers = newcontrollers;
}
base.ViewDidDisappear(animated);
}
This way I way remove the unwanted ViewController when it is removed from the view. I am not fully convinced if it is the right way, but it is working rather good.
This is quite a common scenario... so much so that we've included two mechanisms inside MvvmCross to allow this....
a ClearTop parameter available in all ViewModel navigations.
a RequestRemoveBackStep() call in all ViewModels - although this is currently NOT IMPLEMENTED IN iOS - sorry.
If this isn't enough, then a third technique might be to use a custom presenter to help with your display logic.
To use : 1. a ClearTop parameter available in all ViewModel navigations.
To use this, simply include the ClearTop flag when navigating.
This is a boolean flag - so to use it just change:
this.RequestNavigate<ChildViewModel>(new {arg1 = val1});
to
this.RequestNavigate<ChildViewModel>(new {arg1 = val1}, true);
For a standard simple navigation controller presenter, this will end up calling ClearBackStack before your new view is shown:
public override void ClearBackStack()
{
if (_masterNavigationController == null)
return;
_masterNavigationController.PopToRootViewController (true);
_masterNavigationController = null;
}
from https://github.com/slodge/MvvmCross/blob/vnext/Cirrious/Cirrious.MvvmCross.Touch/Views/Presenters/MvxTouchViewPresenter.cs
If you are not using a standard navigation controller - e.g. if you had a tabbed, modal, popup or split view display then you will need to implement your own presentation logic to handle this.
You can't: 2. RequestRemoveBackStep().
Sadly it proved a bit awkward to implement this at a generic level for iOS - so currently that method is:
public bool RequestRemoveBackStep()
{
#warning What to do with ios back stack?
// not supported on iOS really
return false;
}
from https://github.com/slodge/MvvmCross/blob/vnext/Cirrious/Cirrious.MvvmCross.Touch/Views/MvxTouchViewDispatcher.cs
Sorry! I've raised a bug against this - https://github.com/slodge/MvvmCross/issues/80
3. You can always... Custom ideas
If you need to implement something custom for your iOS app, the best way is to do this through some sort of custom Presenter logic.
There are many ways you could do this.
One example is:
for any View or ViewModel which needs to clear the previous view, you could decorate the View or ViewModel with a [Special] attribute
in Show in your custom Presenter in your app, you could watch for that attribute and do the special behaviour at that time
public override void Show(MvxShowViewModelRequest request)
{
if (request.ViewModelType.GetCustomAttributes(typeof(SpecialAttribute), true).Any())
{
// do custom behaviour here - e.g. pop current view controller
}
base.Show(request);
}
Obviously other mechanisms might be available - it's just C# and UIKit code at this stage
I don't know about mvvm but you can simply Pop the viewcontroller (AC A) without animation and then push the new viewcontoller (AC B) with animation
From within AC A:
NavigationController.PopViewControllerAnimated(false);
NavigationController.PushViewController(new ACb(), true);

Refreshing picture in drawingPanel extends JPanel 2

i apologise for having posted a thread quite similar to this one. but still i am having some problems. thread can be seen here
i am applying a backfround to a jpanel. i need to have a loading gifthat changes later on for a ok or error image.
i load at the beginning a trasparent picture. it get replaced as soon as an action listener starts by the loading one and in the end of the code executed in the listener i change the figure with ok/error. the transparent, the ok and the error one get loaded perfectly but i did not manage to see the loading one.
here is my listener code:
void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {
// load loading icon
Image img = new ImageIcon(iconPath+"loading.gif").getImage();
this.iconPanel.replaceImage(img);
this.iconPanel.updateUI();
this.iconPanel.revalidate();
this.iconPanel.repaint();
// clear table contents
designValue.clear();
deployValue.clear();
// Fill class
diagnosticGenerator diagnostic = new diagnosticGenerator();
Vector<Integer> indexes;
// if modeCombo.getSelectedIndex() == 0 i show only data regarding the current user
if (modeCombo.getSelectedIndex() == 0) {
// receive Design Table
designValue.addAll(diagnostic.getDesignContents());
// receive Deploy Table
deployValue.addAll(diagnostic.getDeployContents());
// receive indexes of out-dated deploy
indexes = new Vector<Integer>(diagnostic.getOutdatedDeployIndexes());
}
// otherwise i show data of all the users
else {
// receive Design Table
designValue.addAll(diagnostic.getDesignContents_allUsers());
// receive Deploy Table
deployValue.addAll(diagnostic.getDeployContents_allUsers());
// receive indexes of out-dated deploy
indexes = new Vector<Integer>(diagnostic.getOutdatedDeployIndexes_allUsers());
}
// set default color to green
deployTable.resetColor(Color.white);
// set red background to the
for (Integer x : indexes)
deployTable.setRowColor(x, Color.red);
deployTable.repaint();
designTable.revalidate();
deployTable.revalidate();
//update refreshLabel with the new date
Date date = new Date();
refreshLabel.setText(date.toString());
//replace icon with different mark depending on the fact if we found an error or not
if(indexes.isEmpty())
img = new ImageIcon(iconPath+"ok.png").getImage();
else
img = new ImageIcon(iconPath+"error.png").getImage();
this.iconPanel.replaceImage(img);
this.iconPanel.repaint();
}
i think it's a matter of asyncronous messages because if i call a wait just after
this.iconPanel.repaint();
i can see the loading gif. but my code gets stuck there.
So i think i shoud find a way to force at that point to execute all the command in queue but i have no idea how to do it.
does anyone had a similar problem with swing?
Use a blocking method such as ImageIO.read(File/URL/InputStream) to get the Image. ImageIO has been introduced into the J2SE 'recently'.