Android集成MongoDB Realm遇Gradle配置及初始化异常求助
解决Android中Realm安装与初始化错误的步骤
一、修正Project级build.gradle配置
根目录下的build.gradle(非Module层级)需添加Realm插件的classpath:
plugins { id 'com.android.application' version '7.4.2' apply false id 'com.android.library' version '7.4.2' apply false // 添加Realm插件依赖 id 'io.realm.realm-gradle-plugin' version '10.16.1' apply false }
二、修正Module级build.gradle配置
你当前的配置存在插件引用方式错误、依赖添加错误两个核心问题,修改后代码如下:
plugins { id 'com.android.application' // 用新的plugins DSL引入Realm插件,替代旧的apply plugin写法 id 'io.realm.realm-android' } android { namespace 'com.example.ig' compileSdk 33 defaultConfig { applicationId "com.example.ig" minSdk 28 targetSdk 33 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } // 在android块外添加Realm Sync配置 realm { syncEnabled = true } dependencies { implementation 'androidx.appcompat:appcompat:1.6.1' implementation 'com.google.android.material:material:1.9.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.4' testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.1.5' androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' // 移除错误的realm-gradle-plugin依赖,插件会自动引入所需库 }
三、修正Realm初始化代码
确保初始化逻辑在Application类或Activity的onCreate方法中执行,替换你的-Realm-App-ID为实际的App ID:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 初始化Realm Realm.init(this); // 创建Realm App实例 App app = new App(new AppConfiguration.Builder("你的-Realm-App-ID") .build()); }
四、收尾操作
- 点击Android Studio右上角的Sync Now同步Gradle配置
- 执行Build > Clean Project清理旧构建缓存
- 重新运行项目
内容的提问来源于stack exchange,提问作者Droidbane
相关产品推荐
相关产品推荐

