cocos2d-x c++ -> java for android - cocos2d-x

Currently I'am developing a game using cocos2d-x.
Of course, for multi-platform use.
basically I use a xcode for coding and development.
I want to attach IAP(In app purchases) separately to each coding for iPhone and Android
Problem to try to call a function of a certain class in Android that did not work.
Sources include the following:
cpp side
MyClass::invoke_init()
{
JavaVM* jvm = JniHelper::getJavaVM();
JNIEnv* env;
jvm->GetEnv((void **) &env, JNI_VERSION_1_2);
jclass cls;
jmethodID method;
cls = env->FindClass("com/joycestudios/game/SampleActivity");
method = env->GetMethodID(cls, "initFunc", "()V");
env->CallVoidMethod(cls, method);
}
java side
public class SampleActivity extends Cocos2dxActivity
{
public void initFunc()
{
Log.v("LOG_INFO", "initFunc()");
}
}
The first test as follows: I'm in progress.
build from xcode and build from build_natvie.sh and last build from eclipse.
But after run on eclipse, Just black screen and shuts down.
How to call a function of a java class?
What I looked at several samples, including also analyze the problem, I do not see any problems?

Can you tell if you find any error log?
First check if your game is working fine on android..
Den we can have a look how to call the function.
Generally for calling native method I use MessageJni class available in Cocos2d-x library.
I create my methods in MessageJni class which calls for native methods.
Its easy and convenient way of calling native methods.
Just google using MessageJni class. It will ease your work.
:)

Related

Call platform specific code from core project

I just Implemented ads for Android in my game using this guide.
It works fine, I have an interface in my core project that the Android Activity implements.
However my problem is that you need to send this implemented interface to the core project, and then pass it as a parameter to your first Screen, where you can use it, ex:
public MyGdxGame(PlatformSpecific ps) //Android class that handle fb-login and ads
{
this.ps = ps;
}
#Override
public void create ()
{
setScreen(new LoginScreen(this, ps);
}
This was fine for when I needed fb-login since I'm using that in the LoginScreen, but I want to be able to create my ads in other Screens (after a game is finished) by calling createAd-method in interface.
Do I have to keep passing ps between all the Screens just so I can use it in a Screen that only gets used quite rarely, or is there some way to get to this interface from my Screen without passing it to the constructor? Kind of like when you initiate an object, ex:
private PlatformSpecific ps = new PlatformSpecific();
Or does LibGdx have some library to support this scenario maybe? Worst case I could just pass ps between all constructors but feels like a pretty ugly solution.
Solution 1:
Store PlatformSpecific in a global static variable. That allows you to access anywhere in your code without passing it in every constructor.
Soluatio 2:
Have MyPlatformContext class which provides access to PlatformSpecific. Then pass this MyPlatformContext object to your screen constructors. If you extend your platform specific code later you do not have to change the screen constructors. Just edit MyPlatformContextMyPlatformContext class.
Pseudo code:
class MyPlatformContext {
private FacbookPlatform fb;
private AdmobPlatform admob
FacbookPlatform getFacebook() {
return fb;
}
...
}

Static function in base class not wanting to call member functions on subclasses if using Flash Builder 4.7, instead of 4.6

Since yesterday, I've been trying to port an ActionScript Mobile project from Flash Builder 4.6 to Flash Builder 4.7, and I've run into a little bit of a problem that's probably a compiler bug. In FB 4.6, this works:
Temp.as:
package
{
import flash.display.Sprite;
public class Temp extends Sprite
{
public function Temp()
{
new StartMenu();
}
}
}
Screen1.as:
package
{
import flash.display.*;
internal class Screen1 extends Sprite
{
private static var m_vScreens:Vector.<Screen1> = new Vector.<Screen1>();
public function Screen1()
{
m_vScreens.push(this);
onScreenSizeDetermined();return;
var strFunction:String = "useSmallPortraitLayout";
for each (var screen:Screen1 in m_vScreens)
{
trace(1)
screen[strFunction]();
}
}
protected function useSmallPortraitLayout():void
{
}
private static function onScreenSizeDetermined():void
{
var strFunction:String = "useSmallPortraitLayout";
for each (var screen:Screen1 in m_vScreens)
{
trace(2)
screen[strFunction](); // Error thrown here in 4.7.
}
}
}
}
StartMenu.as:
package
{
public final class StartMenu extends Screen1
{
override protected function useSmallPortraitLayout():void
{
}
}
}
But in 4.7, it doesn't work. The error I get back is this:
ReferenceError: Error #1069: Property useSmallPortraitLayout not found on StartMenu and
there is no default value.
Now that being said, this can be fixed in one of at least two ways:
Use Flash Builder 4.6
Comment out onScreenSizeDetermined();return;, thereby using a member function to call useSmallPortraitLayout(), instead of a static function. This doesn't require using the constructor; it works just fine, as long as Screen1 is calling useSmallPortraitLayout() from pretty much any non-static method.
Unfortunately the static method will fail, even when it's called from outside the constructor and/or from a timed delay. One thing I don't specifically remember in 4.6, but I am seeing it in at least 4.7, is that using an unrelated class to call a static method directly through an instance won't compile - it has to be done in a staticky way in unrelated classes. Not that I do things like that in real code, but it does make me wonder if the relationship between static and non-static has intentionally changed.
This is probably just some trivial compiler bug specific to FB 4.7, and I would just go right back to 4.6, but pure ActionScript library projects are directly supported only in 4.7. (This is a mobile project, but I was going to add a library project to the solution.)
One thing to note is the code will not compile in FB 4.7 if the static function calls useSmallPortraitLayout this way:
screen.useSmallPortraitLayout();
It has to call it dynamically for it to even compile.
Is there an easy-enough fix for this? Has there been a little bit of syntactical weirdness that 4.6 has simply been overlooking this whole time? What's wrong, and what's a good solution/work-around?
UPDATE
If worst comes to worst, it does seem to work to partially replace the Vector.<Screen1> with a Vector.<Function>, and then just make calls to the members of the function vector, instead of to functions of the members of the Screen1 vector. (This is simplified from production code.) But that's just a fallback.
Also, something I wasn't paying a lot of attention to previously (specifically as far as this one problem goes), but BotMaster kind of brought it to my attention, is that in the process of going from FB 4.6 to FB 4.7, I also went from AIR 3.1 to AIR 3.4.
This is more a scope issue imo. Protected method can only be called within the instance scope and not within a static scope. Of course changing the modifier to public fixes the issue here. PO might argue that protected is wanted here but in reality if there is intention of directly calling a method on an instance outside the scope of that instance then logically that method needs to be public.
Btw FB 4.6 compiler is provided by the used AIR/FLEX SDK and so cannot behave differently from FB 4.7 using the same SDK.
Flash Builder 4.7 uses ASC 2.0 to compile ActionScript projects. From the release notes, emphasis added:
ASC 2.0 is a new compiler for ActionScript® 3.0 (AS3). It has stricter
adherence to the AS3 language specification, includes compilation
performance improvements, is more stable under memory pressure, and
contains some demonstration optimizations that can be optionally
enabled (in-lining, dead code elimination).
I suspect that the compiler sees useSmallPortraitLayout() is not referenced in your original code, and is eliminated from the ABC output.

Accessing REST api from Windows CE

I have one Windows Handheld device application which has the requirement of accessing a REST API. The REST API gives me JSON output which I am going to handle via Newton.JSON. Now to achieve modular structure I want to have the communication to the REST API be handled via a different module altogether something like a Class Library. But unfortunately it seems that it is not possible to do so via a class library(or maybe possible). So my question is what is the best alternative to do so?
Please note that I don't want to include those connectivity operations in my front end application project. And I am using .Net framework 3.5 & Windows Mobile SDK 6.0
Thanks in advance
Pseudo class library code:
public function void startQuery() //starts a thread that does the JSON query
//inside thread on query result use OnDone() delegate
private delegate void OnDone(string dateTimeString);
//In main GUI code add a reference to the class lib and init a new object then add an event handler to the OnDone delegate of the class lib
JSONClassLib myJson=new JSONClassLib();
...
myJson.OnDone+=new EventHandler(myEventHandler);
void myEventHandler(sender this, objext o){
//will be called when query is done
}
//you need to use Control.Invoke if you want to update the GUI from myEventHandler
//to start a query use something like this from your class lib
myJson.doQuery(string);
If you add your existing code we may help with creating a class lib and async code
Now I got my answer. Sorry I did a mistake while selecting the project type. I selected "Windows Form Class Library" project instead of "Smart Device Class Library" project. Now that I have selected the right one it is working fine for me.
BTW thanks for those responses.
Cheers

How to implement MVVM in Windows Phone 8.1 app (xaml)?

Could anyone give an example of implementation? Is it done with ViewModel implementing INotifyPropertyChanged (and raising events, as it's done in Silverlight) or some other way? How is ViewModel bound to the view?
All examples I've found so far are incomplete or outdated (refer to Silverlight apps, not Xaml ones).
In the case of Windows RT I would advise to look towards PRISM. It provides really good modern development practices. You will get suitable navigation service, app lifecycle management, great MVVM support and very flexible view and ViewModels resolution mechanism.
You can easily add it to your project via NuGet.
It has pretty good documentation, so if you have any questions you can find an answer on MSDN or even download free book Prism for the Windows Runtime. Our team has successful experience in building projects using PRISM.
I currently use the following approach in my own Universal/W8.1/WP8.1 apps. This approach uses the RArcher WinRT Toolkit, which is an experimental toolkit based on the MVVM pattern.
It provides a way to maintain app state and you can use the ViewModelBase to implement INPC.
It also uses the Unity dependency injection container.
I'd start with making the ViewModelLocator an application-wide resource, so my Views can access it easily.
<Application.Resources>
<vm:ViewModelLocator x:Key="ViewModelLocator" />
</Application.Resources>
The view can use it like so:
<Page.DataContext>
<Binding Source="{StaticResource ViewModelLocator}" Path="MainViewModel" />
</Page.DataContext>
The ViewModelLocator looks like this:
public sealed class ViewModelLocator
{
public ViewModelLocator()
{
RegisterIoCBindings();
}
public IMainViewModel MainViewModel
{
get { return IocContainer.Get<IMainViewModel>(); }
}
private void RegisterIoCBindings()
{
IocContainer.Container.RegisterType(typeof(IMainViewModel), typeof(MainViewModel),
null, new ContainerControlledLifetimeManager());
}
}
The MainViewModel has the ViewModelBase as baseclass and implements the IMainViewModel:
public sealed class MainViewModel : ViewModelBase, IMainViewModel
{
private string myText;
[AutoState]
public string MyText
{
get { return myText; }
set
{
myText = value;
OnPropertyChanged();
}
}
public MainViewModel() // You can use constructor injection here
{
}
}
That is the basic setup. And as the others have stated, MVVM is a pattern and there a many ways to use it. I would say, use what feels good ;-)
If you like to know more about this approach, check out the toolkit and unity DI.
There is no difference, it's the same. Because MVVM is a pattern. You can implement it to your windows phone app easily. I'm using MVVM Light for my wp apps and EventToCommand behavior to raise events. I have an app open sourced on GitHub, you can check it out if you want.

swing uncaughtexceptionhandler

I am trying to build a general exception handler for a swing application as described here: http://www.javaspecialists.eu/archive/Issue081.html
I work in jython (python syntax getting compiled to java and executed). My code looks roughly like this (updated):
def launcher(func):
class launcherThread(Runnable):
def __init__(self):
super(launcherThread, self).__init__()
def run(self):
func()
#trying to get the name which can be used to instantiate this in java
cls = ExceptionGroup().getClass()
fullName = cls.__module__ + '.' + cls.__name__
System.setProperty("sun.awt.exception.handler", fullName)
Thread(ExceptionGroup(), launcherThread(), 'Cross ExceptionHandlerThread').start()
class ExceptionGroup(ThreadGroup):
def __init__(self):
super(ExceptionGroup, self).__init__("HardenedGroup")
def uncaughtException(self, thread, exception):
#make a fancy dialog displaying str(exception)
If I test it it works fine however in the production enviornment it failes.
For testing I launch my program in Eclipse (PyDev), the production enviornment is a third party application written in Java, that has a Jython console build in. The application supports adding of custom menu entries, and putting jython scripts on these.
The main difference I see between testing and production enviornment is that in the production enviornment the swing threads are allready started (the third party application utilitizes swing). Does this cause my ThreadGroup setting to fail, or is there another reason why this is not working?
How can I get the Involved threads (exceptions ar thrown as a result of buttonActions) to check their defaultException handlers? If (as I am afraid) it should turn out that the third party installed its own handler (all exceptions are written to a log file) how can I make a new swing worker thread? (I don't want to catch the exceptions created by the host application after all)
Question recap:
1. How can I check which threads are started for the function func passed into the launcher function and see thier uncaught exception handler?
2. Can I enforce a seperate swing dispatcher for my gui part and the main applications gui part? (If I exitOnClos on a frame of my add in, the third party application closes)?
Update:
Considering the anwser from lbalazscs I am trying to use the sun.awt.exception.handler property, but it has no effect, the exceptions still end up in the log file (applications dfeault behaviour). Am I using it right? (p.s.: I am on Java 1.6)
If you have Java 5 or higher, you can also use Thread.setDefaultUncaughtExceptionHandler(), which is also described in a newer "Java Specialists' Newsletter":
http://www.javaspecialists.eu/archive/Issue089.html
And here is the newest Java 7 version:
http://www.javaspecialists.eu/archive/Issue196.html
Also see this:
Why bother with setting the "sun.awt.exception.handler" property?
EDIT: This is how I use Thread.setDefaultUncaughtExceptionHandler (in Java...):
public static void setupGlobalExceptionHandling() {
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread t, Throwable e) {
handleException(e);
}
});
}