【前言】一般来讲,Android使用的数据库都是自带的SQLite数据库。Web重量级的MySQL、Orcacle、NOSQL等都不适用于Android项目的开发。但是我发现了一个Web上最近几年比较火的一个数据库 ---- MongoDB。查看它的官网发现,它还可以用于Android开发,而且官方文档也给出了一些API说明。于是我决定写下这篇博客分享一下MongoDB在Android上怎么使用。
【说明】:MongoDB也可以在iOS上面使用,我是做安卓开发的,本文只讲解MongoDB在Android上面的使用,iOS的使用情况请上MongoDB官网自行查阅。
创建一个新项目,截图如下:
在module的build.gradle
文件中添加依赖项:
dependencies {
// 添加 MongoDB Mobile SDK
implementation 'org.mongodb:stitch-android-sdk:4.1.0'
}
然后在module的build.gradle
的android
节点里面文件中添加java 1.8支持:
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.lzw.mongodbdemo"
minSdkVersion 25
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
// 编译选项
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
Sync Now
,表示下载MongoDB SDK并自动执行了gradle build命令。编译成功如下图所示:
如下图所示:
下载的mongodb所在本地的路径为:C:\Users\Administrator\.gradle\caches\modules-2\files-2.1\org.mongodb\
,打开该路径之后截图如下所示:
// import com.mongodb.client.MongoCollection;
// 基础 Stitch 包
// MongoDB Mobile 运行必需的组件
// Create the default Stitch Client
final StitchAppClient client =
Stitch.initializeDefaultAppClient("<APP ID>");
// Create a Client for MongoDB Mobile (initializing MongoDB Mobile)
final MongoClient mobileClient =
client.getServiceClient(LocalMongoDbService.clientFactory);
1、com.mongodb.embedded.client.MongoClientEmbeddedException
具体错误如下图所示: