cocos2d-x在Android真机上使用Sqlite

首先,我是使用sqlite3.c来操作sqlite的,这个库的下载和使用,很多教程上都有介绍。

在win32和MacOS上,这个库的使用没啥特别,但是在Android上,却无法直接读取。

这里要说明,Android不能读取的原因,是因为对数据库的操作必须有root权限,也就是说,我们的应用程序只能对系统提供的特定目录中的数据库文件进行操作。

这个目录,cocos3.4可以通过

FileUtils::getInstance()->getWritablePath()
来获得。

也就是说,我们需要把资源目录下的sliqte库文件,复制到FileUtils::getInstance()->getWritablePath()中,才可以对其进行操作。

对于这种情况,我的解决方案是,在AppDelegate.cpp中,做如下实现

bool AppDelegate::isFileExist(const char* pFileName)
{
	if(!pFileName)return false;
	std::string filePath = FileUtils::getInstance()->getWritablePath();
	
	filePath+=pFileName;
	FILE *pFp = fopen(filePath.c_str(),"r");

	if(pFp)
	{
		fclose(pFp);
		return true;
	}
	return false;
}
//将db资源复制到FileUtils::getInstance()->getWritablePath()
void AppDelegate::copyData(const char* pFileName)
{
	std::string strPath = FileUtils::getInstance()->fullPathForFilename(pFileName);
	//unsigned long len=0;
	ssize_t len = 0;
	unsigned char* data =NULL;
	data = FileUtils::getInstance()->getFileData(strPath.c_str(),"r",&len);


	std::string destPath = FileUtils::getInstance()->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_PLATFORM_ANDROID)//Android下需要复制数据文件
//检查数据库文件是否已经提取
if(isFileExist(DBNAME)==false)
{
copyData(DBNAME);//要使用的sqlite库文件
}

#endif

//下略


在程序启动时,检查sqlite是否存在,不存在,则复制一份。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值