KotlinでFirebaseのRealtimeDatabaseにデータを保存できない
AndroidStudioでKotlinとFirebaseを使ってアプリ開発をしています。Realtimedatabaseにデータを保存したいのですが、公式ドキュメント通りにコードを書いてもデータが保存されず困っています。
発生している問題・エラーメッセージ
onCreateにデータ保存のコードを書いているのですが、エミュレーターを起動してもログが取れておらず、エラーにもなっていません。Firebaseのコンソールを見てもデータが保存されていません。
該当のソースコード
appのgradle
build.gradle
1 2apply plugin: 'com.android.application' 3 4apply plugin: 'kotlin-android' 5 6apply plugin: 'kotlin-android-extensions' 7 8android { 9 compileSdkVersion 29 10 buildToolsVersion "29.0.2" 11 defaultConfig { 12 applicationId "com.example.chatapp" 13 minSdkVersion 16 14 targetSdkVersion 29 15 versionCode 1 16 versionName "1.0" 17 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 18 } 19 buildTypes { 20 release { 21 minifyEnabled false 22 proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 23 } 24 } 25} 26 27dependencies { 28 implementation fileTree(dir: 'libs', include: ['*.jar']) 29 implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 30 implementation 'androidx.appcompat:appcompat:1.1.0' 31 implementation 'androidx.core:core-ktx:1.1.0' 32 implementation 'androidx.constraintlayout:constraintlayout:1.1.3' 33 implementation 'com.google.firebase:firebase-core:17.0.0' 34 implementation 'com.google.firebase:firebase-database:17.0.0' 35 testImplementation 'junit:junit:4.12' 36 androidTestImplementation 'androidx.test.ext:junit:1.1.1' 37 androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' 38} 39 40apply plugin: 'com.google.gms.google-services'
projectのgradle
buildscript { ext.kotlin_version = '1.3.50' repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.5.2' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath 'com.google.gms:google-services:4.3.2' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir }
MainActivity.kt
package com.example.chatapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.DatabaseReference import android.util.Log class MainActivity : AppCompatActivity() { // private lateinit var database: DatabaseReference override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val value = "user2" val database = FirebaseDatabase.getInstance().getReference("users") database.setValue(value) .addOnSuccessListener { Log.d("Main", "success") } .addOnFailureListener { Log.d("Main", "failed") } } }
コンソールの方であらかじめusersという値を追加してあります。
試したこと
検索しても同じ状況の人が見つかりませんでした。
またfirebase-databaseやfirebase-coreのバージョンを変更しても同じ結果でした。
あなたの回答
tips
プレビュー