cocos2d-x在Android真機上使用Sqlite數據庫

暫未驗證。

首先,我是使用sqlite3.c來操作sqlite的,這個庫的下載和使用,很多教程上都有介紹。

在win32和MacOS上,這個庫的使用沒啥特別,但是在Android上,卻無法直接讀取。

這裏要說明,Android不能讀取的原因,是因爲對數據庫的操作必須有root權限,也就是說,我們的應用程序只能對系統提供的特定目錄中的數據庫文件進行操作。

這個目錄,cocos2.1.3可以通過CCFileUtils::sharedFileUtils()->getWritablePath()來獲得。

也就是說,我們需要把資源目錄下的sliqte庫文件,複製到CCFileUtils::sharedFileUtils()->getWritablePath()中,纔可以對其進行操作。

對於這種情況,我的解決方案是,在AppDelegate.cpp中,做如下實現

bool isFileExist(const char* pFileName)
{
if(!pFileName)return false;
std::string filePath = CCFileUtils::sharedFileUtils()->getWritablePath();
filePath+=pFileName;
FILE *pFp = fopen(filePath.c_str(),"r");
CCLog(filePath.c_str());
if(pFp)
{
fclose(pFp);
return true;
}
return false;
}
void copyData(const char* pFileName)
{
std::string strPath = CCFileUtils::sharedFileUtils()->fullPathForFilename(pFileName);
unsigned long len=0;
unsigned char* data =NULL;
data = CCFileUtils::sharedFileUtils()->getFileData(strPath.c_str(),"r",&len);


std::string destPath = CCFileUtils::sharedFileUtils()->getWritablePath();
destPath+= pFileName;


FILE *pFp=fopen(destPath.c_str(),"w+");
fwrite(data,sizeof(char),len,pFp);
fclose(pFp);
delete []data;
data=NULL;
}

bool AppDelegate::applicationDidFinishLaunching()
{
#if (CC_TARGET_PLATFORM !=CC_TARGET_WIN32)//Android下需要複製數據文件
//檢查數據庫文件是否已經提取
if(isFileExist("dbd_user_save.db")==false)
{
copyData("dbd_user_save.db");//要使用的sqlite庫文件
}
#endif
//下略



在程序啓動時,檢查sqlite是否存在,不存在,則複製一份

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章