Constant Abrh
Constant Abrh

Reputation: 23

setValue() not saving data to my realtime database

I'm trying to save data to my realtime database using the setValue() methods but it's not saving my object.

I tried with a simple String and still didn't worked.

My code :

    FirebaseDatabase db = FirebaseDatabase.getInstance();
        DatabaseReference ref = db.getReference();
        ref.setValue("user");
Toast.makeText(RegisterApp.this, "Passe tranquille #1! Ref = " + ref.toString() + " | Db = " + db.toString(), Toast.LENGTH_LONG).show();

The makeText is called and show me good information which (should) show that it's connected to the database?

But still my realtime db shown null instead of string "user".

build.graddle

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = '1.4.32'
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.2.1'
        classpath 'com.google.gms:google-services:4.3.8'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
    }
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

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

app/build.graddle with version set by myself

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"
    defaultConfig {
        applicationId "com.example.projetl3"
        minSdkVersion 26
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    configurations {
        compile.exclude group: "guava", module: "guava"
        implementation.exclude module:'proto-google-common-protos'
        implementation.exclude module:'protolite-well-known-types'
        implementation.exclude module:'guava'
        implementation.exclude module:'protobuf-lite'

    }


    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    packagingOptions {
        exclude 'META-INF/INDEX.LIST'
        exclude 'META-INF/DEPENDENCIES'
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.2'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'com.google.firebase:firebase-database:20.0.0'

    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
// CameraX core library using camera2 implementation
    implementation "androidx.camera:camera-camera2:1.1.0-alpha04"
// CameraX Lifecycle Library
    implementation "androidx.camera:camera-lifecycle:1.1.0-alpha04"
// CameraX View class
    implementation "androidx.camera:camera-view:1.0.0-alpha24"


    implementation 'com.google.android.gms:play-services-vision:20.1.3'
    implementation platform('com.google.cloud:libraries-bom:20.2.0')
    implementation 'com.google.cloud:google-cloud-vision'

    implementation 'com.google.api-client:google-api-client-android:1.22.0'
    implementation 'com.google.apis:google-api-services-vision:v1-rev357-1.22.0'
    implementation 'com.google.code.findbugs:jsr305:3.0.2'

    // Import the Firebase BoM
    implementation platform('com.google.firebase:firebase-bom:28.0.1')

    // Add the dependency for the Firebase SDK for Google Analytics
    // When using the BoM, don't specify versions in Firebase dependencies
    implementation 'com.google.firebase:firebase-analytics'
    implementation 'com.google.firebase:firebase-database:20.0.0'
}

app/build.graddle with bom version :

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"
    defaultConfig {
        applicationId "com.example.projetl3"
        minSdkVersion 26
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    configurations {
        compile.exclude group: "guava", module: "guava"
        implementation.exclude module:'proto-google-common-protos'
        implementation.exclude module:'protolite-well-known-types'
        implementation.exclude module:'guava'
        implementation.exclude module:'protobuf-lite'

    }


    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    packagingOptions {
        exclude 'META-INF/INDEX.LIST'
        exclude 'META-INF/DEPENDENCIES'
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.2'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'

    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
// CameraX core library using camera2 implementation
    implementation "androidx.camera:camera-camera2:1.1.0-alpha04"
// CameraX Lifecycle Library
    implementation "androidx.camera:camera-lifecycle:1.1.0-alpha04"
// CameraX View class
    implementation "androidx.camera:camera-view:1.0.0-alpha24"


    implementation 'com.google.android.gms:play-services-vision:20.1.3'
    implementation platform('com.google.cloud:libraries-bom:20.2.0')
    implementation 'com.google.cloud:google-cloud-vision'

    implementation 'com.google.api-client:google-api-client-android:1.22.0'
    implementation 'com.google.apis:google-api-services-vision:v1-rev357-1.22.0'
    implementation 'com.google.code.findbugs:jsr305:3.0.2'

    // Import the Firebase BoM
    implementation platform('com.google.firebase:firebase-bom:28.0.1')

    // Add the dependency for the Firebase SDK for Google Analytics
    // When using the BoM, don't specify versions in Firebase dependencies
    implementation 'com.google.firebase:firebase-analytics'
    implementation 'com.google.firebase:firebase-database'
}

My rules : ( I even tried to put them to true, or even "true")

{
  "rules": {
    ".read": "now < 1623794400000",  // 2021-6-16
    ".write": "now < 1623794400000",  // 2021-6-16
  }
}

Upvotes: 2

Views: 1236

Answers (4)

Ravi.Dudi
Ravi.Dudi

Reputation: 1364

If your database is in a non-default region, make sure you add the database link in the getInstance code.

FirebaseDatabase.getInstance("database URL here")

In my case this was the reason, so make sure you aren't making the same mistake.

Upvotes: 1

Alex Mamo
Alex Mamo

Reputation: 139029

You can use a Map for adding data to the database, as @ahmad bajwa suggested in his answer, or you can use a model class. Seeing that you want to write some user data, at a minimum, the declaration of the class should look like this:

class User {
    public String userName;
}

Now to write the data to the Realtime Database, please use the following lines of code:

User user = new User("Constant Abrh");
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
usersRef.child("firstUser").setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull Task<Void> task) {
        if (task.isSuccessful()) {
            Log.d("TAG", "User added successfully.");
        } else {
            Log.d"(TAG", task.getException().getMessage()); //Don't ignore potential errors!
        }
    }
});

Always consider attaching a listener to see the result, because there are cases in which the write operation might not succeed, Firebase servers might reject the write operation, for example. In the end, you database structure should look like this:

Firebase-root
  |
  --- users
       |
       --- firstUser
             |
             --- name: "Constant Abrh"

If you want, you can also consider implementing Firebase Authentication, so you can write later Security Rules.

Upvotes: 2

ahmad bajwa
ahmad bajwa

Reputation: 1068

You need to use Map to add values in firebase Realtime database. As firebase Realtime database work just like json.

   DatabaseReference ref = db.getReference();
    Map<String, Object> users = new HashMap<>();
    users.put("user",   "Alan Turing");
    ref.setValueAsync(users);

For more details you at this: https://firebase.google.com/docs/database/admin/save-data

Upvotes: 2

ntippa
ntippa

Reputation: 31

Check this article on medium where there is explanation for why setValue would fail. https://medium.com/@valokafor/firebase-realtime-database-by-example-with-android-1e597819e24b . You might want to check Firebase rules

Upvotes: 3

Related Questions