Hello, guys!
I ran into the problem of writing/reading data from UserDefault. So the instance of the problem is that when I’m trying to read data with
UserDefault::getInstance()->getStringForKey("key")
an result of the operation is always empty string. But is very strange that it’s prefectly works on Windows. Before reading data, of course, I have writed it with
UserDefault::getInstance()->setStringForKey("key", std::string("str"))
, but before this I used the xxtea encryption. Here is code:
//EncryptEngine.cpp
#include <cstdlib>
#include "cocos2d.h"
#include "EncryptEngine.h"
using std::string;
EncryptEngine* EncryptEngine::getInstance()
{
static EncryptEngine* instance = new EncryptEngine;
return instance;
}
string EncryptEngine::encrypt(int number)
{
string tempStr = patch::to_string(number);
xxtea_long dataLen = tempStr.length();
unsigned char* data = new unsigned char[dataLen];
strcpy((char*) data, tempStr.c_str());
xxtea_long retLen = 0;
unsigned char* result = xxtea_encrypt(data, dataLen, key, keyLen, &retLen);
string retRes = std::string((char*) result);
return retRes;
}
int EncryptEngine::decrypt(string tempStr)
{
xxtea_long dataLen = tempStr.length();
unsigned char* data = new unsigned char[dataLen];
strcpy((char*) data, tempStr.c_str());
xxtea_long retLen = 0;
//temp str is empty
cocos2d::log("key:%s, keyLen:%d, data:%s, dataLen:%d, tempstr:%s", key, keyLen, data, dataLen, tempStr.c_str());
unsigned char* result = xxtea_decrypt(data, dataLen, key, keyLen, &retLen);
cocos2d::log("after");
if (result == 0)
return 0;
int retRes = atoi((char*) result);
return retRes;
}
patch namespace here it’s just template-wrapper around std::to_string() for avoid ndk compilation error.
And here is using the write/read operations:
Write:
UserDefault::getInstance()->setStringForKey("ofvm5x", encrEn->encrypt(23));//garbage
UserDefault::getInstance()->setStringForKey("h84sza", encrEn->encrypt(45));//garbage
UserDefault::getInstance()->setStringForKey("d8m2wt", encrEn->encrypt(0));//money
Read:
p_instance->money = encrEn->decrypt(UserDefault::getInstance()->getStringForKey("d8m2wt"));
Here is just using obfuscated keys for transfer the values.
So I should describe the process:
Just first run through cocos run -p android
is ok and applications works. But when I’m trying to restart application, he is just crashing with error in xxtea_decrypt method because of emptiness of the string value. I have debugging it with cocos2d::log and adb logcat, so I found that UserDefault returns empty string here:
std::string result = UserDefault::getInstance()->getStringForKey("d8m2wt")//money
I’m trying to solve it 3’th day and I’m really asking for help. Maybe @slackmoehrle or @iQD can help me
Thank you very much
Helpful info:
Cocos engine version = cocos2dx-3.13.1
Android NDK = r10e