1

this is my build.gradel project file // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        compose_version = '1.0.1'
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.1"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.30"
        classpath 'com.google.gms:google-services:4.3.10'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

this is build.gradel module code

    plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'com.google.gms.google-services'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.ehika.grp.myapplication1"
        minSdk 23
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary true
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
        useIR = true
    }
    buildFeatures {
        compose true
        viewBinding true
    }
    composeOptions {
        kotlinCompilerExtensionVersion = "1.1.0-alpha03"
        kotlinCompilerVersion '1.5.21'
    }
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }
}

dependencies {

    apply plugin : "kotlin-android"
    apply plugin : "kotlin-android-extensions"

    implementation 'androidx.core:core-ktx:1.6.0'
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation "androidx.compose.ui:ui:$compose_version"
    implementation "androidx.compose.material:material:$compose_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
    implementation 'androidx.activity:activity-compose:1.3.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
    debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"

    //Firebase
    implementation platform('com.google.firebase:firebase-bom:28.4.0')
    implementation 'com.google.firebase:firebase-analytics-ktx'
    implementation 'com.google.android.gms:play-services-auth:19.2.0'
    implementation 'com.google.firebase:firebase-auth-ktx:20.0.4'
    implementation 'com.google.firebase:firebase-database-ktx'
}

this is my code to write data in realtime database

   val  currentUserID = FirebaseAuth.getInstance().currentUser!!.uid
    val usersRef: DatabaseReference = FirebaseDatabase.getInstance().reference.child("Users")

    val userMap = HashMap<String, Any>()
    userMap["uid"] = currentUserID

    usersRef.child(currentUserID).setValue(userMap)
        .addOnCompleteListener{ task ->
            if (task.isSuccessful){
                Toast.makeText(baseContext, "Data stored successful.",
                    Toast.LENGTH_SHORT).show()
                val intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
                finish()
            } else {
                Toast.makeText(baseContext, "data not stored.",
                    Toast.LENGTH_SHORT).show()
            }
        }

i have tried changing from classpath 'com.google.gms:google-services:4.3.10' to classpath 'com.google.gms:google-services:4.3.8' but it didn't workout for me.

these are my realtime database rules

{
  "rules": {
    "users": {
      ".read": true,
      ".write": true
    }
  }
}
Prasad
  • 13
  • 4

1 Answers1

2

In order to write some data into the Firebase Realtime Database, you need to use DatabaseReference#setValue(Object value). In code should look like this:

val database = Firebase.database
val myRef = database.getReference("message")
myRef.setValue("Hello, World!")

You might also attach a complete listener to see the result of the write operation.

Edit:

In order to use the following reference:

val usersRef: DatabaseReference = FirebaseDatabase.getInstance().reference.child("Users")

You need to create rules to allow access. Since you are using "users" instead of "Users":

{
  "rules": {
    "users": {
      ".read": true,
      ".write": true
    }
  }
}

Firebase servers will reject the write. So please use the following rules:

{
  "rules": {
    "Users": {  //Use capital letter U
      ".read": true,
      ".write": true
    }
  }
}

Edit2:

Final change. Adding the URL location of the database fixed the problem.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • thanks for answering my question but by mistake I wrote wrong code. I was trying random methods to solve it. I copied earlier code from firebase documentation. Now this is my real code which I am using in my project.I have edited the question. Can you please help me. – Prasad Sep 10 '21 at 08:34
  • Please check my updated answer and tell me if it works. – Alex Mamo Sep 10 '21 at 08:37
  • I have put toast on random positions they are working. The problem is in firebase code. – Prasad Sep 10 '21 at 08:39
  • Without having the right rules, your write operation will be rejected. Have you tried the rules in my edited answer? – Alex Mamo Sep 10 '21 at 08:40
  • I am able to get user id but only not able to write it. – Prasad Sep 10 '21 at 08:44
  • "not working" doesn't provide enough information so I can further help. What exactly doesn't work? Do you get any errors? – Alex Mamo Sep 10 '21 at 08:44
  • Good to hear that you can get the ID but is your `Toast.makeText(baseContext, "data not stored.", Toast.LENGTH_SHORT).show()` displaying something? – Alex Mamo Sep 10 '21 at 08:45
  • the code is inside button.setOnClickListener........when I click on button it shows nothing. No error. No crash. – Prasad Sep 10 '21 at 08:47
  • What is the location of y ou Firebase Database, US? – Alex Mamo Sep 10 '21 at 08:48
  • Singapore (asia-southeast1) – Prasad Sep 10 '21 at 08:49
  • In that case, [this is indeed the problem](https://stackoverflow.com/questions/67795058/save-android-user-credentials-to-firebase-database-kotlin/), right? – Alex Mamo Sep 10 '21 at 08:50