Xcode build working BUT Android Studio build not working as expected

(I am new to Cocos2dx)
(Xcode with macOS, Android studio with Galaxy Note5)
macOS = Version 10.15.6
Xcode = Version 11.6
Android Studio = Version 4.0.1
Phone (Galaxy Note5) = samsung sm-n920k

I am making a stopwatch similar to https://cstimer.net.
The stopwatch is a cocos2d::Label* stopWatchLabel;
I am using the void update(float dt); function to update the stopwatch(Label) using the setString(); function.
It seems to work on Xcode. (Image below) (It is running)

But it doesn’t seem to work on Android Studio. As soon as I start the stopwatch, the program crashes. I think it’s because of the setString(); function. But I am not sure, and I can’t fix it.
How can I fix this code to make the stopwatch on Android?

HelloWorldscene.cpp

#include "HelloWorldScene.h"
#include "ui/CocosGUI.h"

#include <iostream>

USING_NS_CC;

Scene* HelloWorld::createScene()
{
    auto scene = HelloWorld::create();
    auto layer = Layer::create();
    scene->addChild(layer);
    
    return scene;
}

// Print useful error message instead of segfaulting when files are not there.
static void problemLoading(const char* filename)
{
    printf("Error while loading: %s\n", filename);
    printf("Depending on how you compiled you might have to add 'Resources/' in front of filenames in HelloWorldScene.cpp\n");
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Scene::init() )
    {
        return false;
    }

    auto visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    /////////////////////////////
    // 3. add your codes below...
    
    // colors for stopWatchLabel
    WHITE_4B = Color4B(255, 255, 255, 255);
    PINK_4B = Color4B(255, 0, 126, 255);
    GREEN_4B = Color4B(0, 255, 126, 255);
    
    stopWatchLabel = Label::createWithTTF("0.0->", "fonts/FiraCode-Regular.ttf", 96);
    stopWatchLabel->setPosition(Vec2(visibleSize.width/2+origin.x, visibleSize.height/2-100+origin.y));
    this->addChild(stopWatchLabel, 1);
    
    stopWatchBase = 0;
    this->scheduleUpdate();
    stopWatchCheck = 0; // 0: stopped, 1: started, 2: anti ovelap int usage, 3: stop with color
    touchDurationCheck = 0; // 0, 1->
    touchDurationBase = 0.0;
    holdStopWatch = 0.55;
    
    listener1 = EventListenerTouchOneByOne::create();

    listener1->onTouchBegan = [=](Touch* touch, Event* event){
        if (stopWatchCheck == 0)
        {
            stopWatchBase = 0;
            stopWatchLabel->setTextColor(PINK_4B);
            
            touchDurationCheck = 1;
        }
        else if (stopWatchCheck == 1)
        {
            stopWatchLabel->setTextColor(PINK_4B);
            stopWatchCheck = 0;
        }
        return true;
    };
    listener1->onTouchMoved = [=](Touch* touch, Event* event){
    };
    listener1->onTouchEnded = [=](Touch* touch, Event* event){
        if (stopWatchCheck == 2)
        {
            stopWatchCheck = 1;
        }
        stopWatchLabel->setTextColor(WHITE_4B);
        
        touchDurationCheck = 0;
        touchDurationBase = 0;
    };
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, this);
    return true;
}
void HelloWorld::update(float dt)
{
    // stopWatchCheck to these
    if (stopWatchCheck == 1)
    {
        stopWatchBase += dt;
        stopWatchLabel->setString(std::to_string(stopWatchBase));
    }
    // touchDurationCheck
    if (touchDurationCheck == 1)
    {
        touchDurationBase += dt;
    }
    if (touchDurationBase > holdStopWatch && listener1->onTouchBegan)
    {
        stopWatchLabel->setString(std::to_string(stopWatchBase)); // if thing
        stopWatchLabel->setTextColor(GREEN_4B); // if thing
        stopWatchCheck = 2; // if thing
    }
}

HelloWorldScene.h

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"

class HelloWorld : public cocos2d::Scene
{
public:
    static cocos2d::Scene* createScene();

    virtual bool init();
    
    // a selector callback
    void menuCloseCallback(cocos2d::Ref* pSender);
    
    // implement the "static create()" method manually
    CREATE_FUNC(HelloWorld);
    
    void update(float dt); // update function
    float stopWatchBase; // stopwatch base number thing
    cocos2d::Label* stopWatchLabel; // label to represent
    int stopWatchCheck;
    cocos2d::EventListenerTouchOneByOne* listener1; // touch listener
    int touchDurationCheck;
    float touchDurationBase; // touch duration
    float holdStopWatch; // hold to start
    
    cocos2d::Color4B WHITE_4B;
    cocos2d::Color4B PINK_4B;
    cocos2d::Color4B GREEN_4B;
};

#endif // __HELLOWORLD_SCENE_H__

Why doesn’t it work?

What does the console say when it crashes?

Did you step through using the debugger?

1 Like

This happens when I run it.
When the touch ended.
It’s ok until I run the stopwatch.

From debugging, I think setString(); in the update function is causing this. setString(); has to execute every frame, so it crashes.
But I’m not sure. And if that is the cause of the error, how do I fix it? How do I make setString(); executing every frame not crash? SCREEN RECORDING OF THE PROGRAM CRASHING

One more strange thing.
This, [timer label]->setString(std::to_string([stopwatch])); executes every frame. In theory, it has to update the [timer label] every frame. But it crashes.

It’s funny because when i replace the [stopwatch] value with something else, for example) [timer label]->setString("this is a test"); This code should update the [timer label] to “this is a test” every frame right? Instead, the label just disappears.

I press the debug button in android studio. (I don’t know how to use this, so I will show you a screen recording, and outputs.)
It shows a screen with some functions, but I have no idea about them. SCREEN RECORDING ABOUT DEBUGGING

Starting LLDB server using code injection
Debugger attached to process 16852
Signal: SIGSEGV (signal SIGSEGV: address access protected (fault address: 0x7ef8dd2690))
failed to send the k packet

Process finished with exit code 6
Executing commands in '/Applications/Android Studio.app/Contents/bin/lldb/shared/stl_printers/load_script'.
(lldb) script import sys
(lldb) script import os
(lldb) script gala_available = os.environ.get('AS_GALA_PATH') is not None
(lldb) script exec("if gala_available: sys.path.append(os.environ['AS_GALA_PATH'])")
(lldb) script exec("if gala_available: import gdb")
(lldb) script exec("if gala_available: import gdb.printing")
(lldb) script libstdcxx_printers_available = gala_available and (os.environ.get('AS_LIBSTDCXX_PRINTER_PATH') is not None)
(lldb) script exec("if libstdcxx_printers_available: sys.path.append(os.environ['AS_LIBSTDCXX_PRINTER_PATH'])")
(lldb) script exec("if libstdcxx_printers_available: import printers")
(lldb) script exec("if libstdcxx_printers_available: printers.register_libstdcxx_printers(None)")
(lldb) script exec("if lldb.debugger.GetCategory('libstdc++-v6').IsValid(): lldb.debugger.GetCategory('gnu-libstdc++').SetEnabled(False)")
08/30 19:51:05: Launching 'test' on samsung SM-N920K.
$ adb shell am start -n "com.cshift.test/org.cocos2dx.cpp.AppActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 10340 on device 'samsung-sm_n920k-0715f7fb24ce2c05'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
D/main: cocos_android_app_init
D/Cocos2dxHelper: isSupportLowLatency:false
D/Cocos2dxHelper: sampleRate: 48000, framesPerBuffer: 240
D/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp: nativeSetAudioDeviceInfo: sampleRate: 48000, bufferSizeInFrames: 240
D/Cocos2dxActivity: onResume()
D/ViewRootImpl@6cbb4f0[AppActivity]: ThreadedRenderer.create() translucent=false
D/InputTransport: Input channel constructed: fd=58
D/ViewRootImpl@6cbb4f0[AppActivity]: setView = DecorView@77d5a69[AppActivity] touchMode=true
D/ViewRootImpl@6cbb4f0[AppActivity]: dispatchAttachedToWindow
D/ViewRootImpl@6cbb4f0[AppActivity]: Relayout returned: oldFrame=[0,0][0,0] newFrame=[0,0][1920,1080] result=0x7 surface={isValid=true 545865963520} surfaceGenerationChanged=true
    mHardwareRenderer.initialize() mSurface={isValid=true 545865963520} hwInitialized=true
D/libEGL: loaded /vendor/lib64/egl/libGLES_mali.so
D/SurfaceView: Relayout returned: oldFrame=[0,0][0,0] newFrame=[0,0][1920,1080] result=0x7 surface={Surface(name=null)/@0x64cd84c isValid=true 545865967104}
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
D/mali_winsys: EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000,  [1920x1080]-format:1
D/mali_winsys: EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000,  [1920x1080]-format:1
D/cocos2d-x debug info: {
    	cocos2d.x.version: cocos2d-x-4.0
    	vendor: ARM
    	cocos2d.x.compiled_with_profiler: false
    	max_texture_units: 96
    	cocos2d.x.build_type: DEBUG
    	renderer: Mali-T760
    	cocos2d.x.compiled_with_gl_state_cache: true
    	max_samples_allowed: 0
    	supports_OES_depth24: true
    	version: OpenGL ES 3.2 v1.r15p0-00rel0.5dff6779e3b10548dc5cd2b2f4972566
    	max_vertex_attributes: 16
    	supports_NPOT: true
    	supports_vertex_array_object: true
    	max_texture_size: 8192
    	supports_S3TC: false
    	supports_discard_framebuffer: true
    	supports_ETC1: true
    	supports_OES_map_buffer: true
    	supports_PVRTC: false
    	supports_BGRA8888: false
    	supports_ATITC: false
    	supports_OES_packed_depth_stencil: true
    }
D/cocos2d-x debug info: OpenGL error 0x0501 in ../../../../../../cocos2d/cocos/renderer/backend/opengl/TextureGL.cpp updateData 207
D/cocos2d-x debug info: cocos2d: QuadCommand: resizing index size from [-1] to [2560]
D/ViewRootImpl@6cbb4f0[AppActivity]: Relayout returned: oldFrame=[0,0][1920,1080] newFrame=[0,0][1920,1080] result=0x1 surface={isValid=true 545865963520} surfaceGenerationChanged=false
D/SurfaceView: Relayout returned: oldFrame=[0,0][1920,1080] newFrame=[0,0][1920,1080] result=0x1 surface={Surface(name=null)/@0x64cd84c isValid=true 545865974272}
D/ViewRootImpl@6cbb4f0[AppActivity]: MSG_RESIZED_REPORT: ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=2
    MSG_WINDOW_FOCUS_CHANGED 1
D/ViewRootImpl@6cbb4f0[AppActivity]: mHardwareRenderer.initializeIfNeeded()#2 mSurface={isValid=true 545865963520}
D/Cocos2dxActivity: onWindowFocusChanged() hasFocus=true
D/SEM_CLIP_SemClipboardManager: isCocktailBarDisplayed : false
V/InputMethodManager: Starting input: tba=android.view.inputmethod.EditorInfo@69b8111 nm : com.cshift.test ic=null
I/InputMethodManager: [IMM] startInputInner - mService.startInputOrWindowGainedFocus
D/InputTransport: Input channel constructed: fd=76
V/InputMethodManager: Starting input: tba=android.view.inputmethod.EditorInfo@5af5276 nm : com.cshift.test ic=null
D/ViewRootImpl@6cbb4f0[AppActivity]: ViewPostImeInputStage processPointer 0
W/System: ClassLoader referenced unknown path: /system/framework/QPerformance.jar
E/BoostFramework: BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't find class "com.qualcomm.qti.Performance" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib64, /vendor/lib64]]
V/BoostFramework: BoostFramework() : mPerf = null
D/ViewRootImpl@6cbb4f0[AppActivity]: ViewPostImeInputStage processPointer 1
D/cocos2d-x debug info: Assert failed: reference count should be greater than 0
E/cocos2d-x assert: ../../../../../../cocos2d/cocos/base/CCRef.cpp function:release line:99
D/cocos2d-x debug info: Assert failed: reference count should be greater than 0
E/cocos2d-x assert: ../../../../../../cocos2d/cocos/base/CCRef.cpp function:release line:99
D/cocos2d-x debug info: Assert failed: reference count should be greater than 0
E/cocos2d-x assert: ../../../../../../cocos2d/cocos/base/CCRef.cpp function:release line:99
D/cocos2d-x debug info: Assert failed: reference count should be greater than 0
E/cocos2d-x assert: ../../../../../../cocos2d/cocos/base/CCRef.cpp function:release line:99
A/libc: Fatal signal 11 (SIGSEGV), code 2, fault addr 0x7ef9180690 in tid 10406 (GLThread 6245)

These are the outputs.
How can I fix this?

THESE ARE THE SCREEN RECORDINGS, (capitalized for readability)

SCREEN RECORDING OF THE PROGRAM CRASHING:

SCREEN RECORDING ABOUT DEBUGGING:

Yep, seems like debugging was the only solution.

SOLUTION
So, it seems like stopWatchLabel = Label::createWithTTF("0.0->", "fonts/FiraCode-Regular.ttf", 96); was the problem.
I changed the font size, 96, to 20 or smaller and it worked. I don’t know why though. Debugging was the solution.

slackmoehrle said:
Did you step through using the debugger?

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Not all fonts are created equal. Perhaps a different TTF would allow a larger font size or it’s possible characters are missing. It’s always safe to debug with Arial.

1 Like