Page 1 of 1

b2dJson::readFromFile() error on Android

Posted: Thu Aug 29, 2013 5:47 pm
by msm1982
I thought I'd post this here in case anyone else encounters the same issue as me.

The cocos2d sample loader uses b2dJson::readFromFile() to load the RUBE json scene. I based my cocos2d-x project off this sample and everything worked fine to begin building/running on linux, but crashes on Android.

When running the app on Android, it was unable to read the file, even though the path was correct and the permissions on the file were world readable. The simple fix is to use cocos2d-x FileUtils to load the data and pass the string to b2dJson:

e.g) instead of

Code: Select all

world = json.readFromFile(fullPath, errMsg);
use this:

Code: Select all

unsigned long fileSize = 0;
unsigned char* fileData = NULL;
fileData = FileUtils::getInstance()->getFileData(fullPath, "r", &fileSize);
std::string jsonContent;
jsonContent.assign(reinterpret_cast<const char*>(fileData), fileSize);
world = json.readFromString(jsonContent, errMsg);

Re: b2dJson::readFromFile() error on Android

Posted: Sun Sep 15, 2013 8:14 am
by iforce2d
That's correct. You have to do that on iPhone too, and the Cocos2d sample does it a few lines earlier in the code, that you might have missed.

To clarify, the relevant lines in the Cocos2d sample are:

Code: Select all

NSString* filename = ...;
NSString* fullpath = [CCFileUtils fullPathFromRelativePath:filename];

b2dJson json;
std::string errMsg;
m_world = json.readFromFile([fullpath UTF8String], errMsg);
Failing to find the file is not in itself a crash causing problem, so that was likely caused subsequently using the world pointer without checking if it was NULL.

Re: b2dJson::readFromFile() error on Android

Posted: Sun Sep 15, 2013 1:28 pm
by msm1982
I dont think I quite follow.

In the cocos2d iphone loader, it only gets the filepath and passes that to the b2dJson method.

What I was trying to say was that on Android, this method never works. The b2dJson readFromFile() method is unable to read the file contents even though I pass it the correct file path.

The cocos2d-x FileUtils method is able to read the contents of the file and I am using that as an intermediary step to pass the contents to b2dJson.readFromString() instead of the iphone readFromFIle() way

Re: b2dJson::readFromFile() error on Android

Posted: Wed Sep 18, 2013 7:59 pm
by iforce2d
I have to apologise for getting ahead of myself. I'm making a cocos2d-x version of the sample loader at the moment and will be using exactly the method you have shown here. Thankyou!!

Re: b2dJson::readFromFile() error on Android

Posted: Thu Sep 19, 2013 12:45 am
by msm1982
no worries, glad it was useful

Re: b2dJson::readFromFile() error on Android

Posted: Fri Aug 15, 2014 12:37 am
by weiweili
It's really helpful to solve my big problem. Thank moderator :D