简体   繁体   English

我想通过以下代码从 android 工作室在实时数据库中添加数据,但它不应该工作

[英]I want to add data in Realtime database from android studio from the following code but it should not worked

Code for registration注册码

//Code used for inserting the data of students I am not adding import parts because this question is not submitted at that time. //用于插入学生数据的代码我没有添加导入部分,因为当时没有提交这个问题。

public class StudentregisterActivity extends AppCompatActivity {

    EditText stname;
    EditText stphone;
    EditText stemail;
    EditText stpassword;
    Button stbtn;


    DatabaseReference studentref;
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.studentregister);

        stname=findViewById(R.id.editTextTextPersonName);
        stemail=findViewById(R.id.editTextTextEmailAddress);
        stphone=findViewById(R.id.editTextPhone);
        stpassword=findViewById(R.id.editTextTextPassword);
        stbtn=findViewById(R.id.button7);

        studentref=FirebaseDatabase.getInstance().getReference().child("Students");

        stbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                
                InsertStudentData();

            }
        });
    }
    private void InsertStudentData(){

        String name=stname.getText().toString();
        String email=stemail.getText().toString();
        String phone=stphone.getText().toString();
        String password=stpassword.getText().toString();

        Students students=new Students(name,email,phone,password);

        studentref.push().setValue(students);
        Toast.makeText(StudentregisterActivity.this,"Register Successfully",Toast.LENGTH_SHORT).show();

    }
}

Students学生

package com.example.pariksha;

public class Students {

    String name;
    String email;
    String phone;
    String password;

    public Students(String name, String email, String phone, String password) {
        this.name = name;
        this.email = email;
        this.phone = phone;
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

setting-gradle设置等级

//Gradle setting of the project //项目的Gradle设置

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)
    repositories {
        google()
        mavenCentral()
        jcenter()
        maven { url "https://maven.xyz.com" }
    }
}
rootProject.name = "Pariksha"
include ':app'

gradle-properties等级属性

//Gradle properties of the project //项目的Gradle属性

# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
android.useAndroidX=true
android.enableJetifier=true

gradle-build app gradle 构建应用程序

//Gradle properties of app //应用程序的Gradle属性

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

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.pariksha"
        minSdk 19
        targetSdk 31
        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
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    //noinspection GradleCompatible
    implementation 'androidx.appcompat:appcompat:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.firebase:firebase-auth:19.2.0'
    implementation 'com.google.firebase:firebase-database:19.2.1'
    implementation 'com.google.firebase:firebase-database:20.0.3'
    implementation platform('com.google.firebase:firebase-bom:29.0.3')
    implementation 'com.google.firebase:firebase-analytics'
    implementation 'com.google.firebase:firebase-analytics:20.0.2'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

}

build gradle project构建 gradle 项目

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.4"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.0"
        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
    }
}

allprojects {

    repositories {
        // Check that you have the following line (if not, add it):
        google()  // Google's Maven repository
        mavenCentral()


    }
}

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

First of all please have a look at rules defined for Firebase Realtime Database.首先,请查看为 Firebase 实时数据库定义的规则。 If you're not using Firebase Auth, You can Update rules like this.如果你没有使用 Firebase Auth,你可以像这样更新规则。

Goto Realtime Database then change tab to Rules and update rules.转到实时数据库,然后将选项卡更改为规则并更新规则。

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

Then you can write data.然后就可以写入数据了。

private void InsertStudentData(){

    String name=stname.getText().toString();
    String email=stemail.getText().toString();
    String phone=stphone.getText().toString();
    String password=stpassword.getText().toString();

    Students students=new Students(name,email,phone,password);

    studentref.setValue(students).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
             Toast.makeText(StudentregisterActivity.this,"Register Successfully",Toast.LENGTH_SHORT).show();
        }
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Toast.makeText(StudentregisterActivity.this,"Register failed",Toast.LENGTH_SHORT).show();

        }
    });

}

Make sure following things确保以下事项

  1. Internet permission in Manifest.清单中的 Internet 权限。
  2. Set Firebase Realtime database Rules to Public/Authenticate user for private rules.将 Firebase 实时数据库规则设置为公共/验证用户以获取私有规则。
  3. Internet Availability on testing device to push data into database.测试设备上的 Internet 可用性,可将数据推送到数据库中。

To set Internet Permission设置 Internet 权限

<uses-permission android:name="android.permission.INTERNET" />

To set rules to public将规则设置为公开

  1. Goto Firebase console转到 Firebase 控制台
  2. Realtime database rules实时数据库规则
  3. Paste this code in rules将此代码粘贴到规则中

** **

{
 “rules”: {
 “.read”: true,
 “.write”: true
 }
}

** **

At the end try uploading data using the code below最后尝试使用下面的代码上传数据

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference tasksRef = rootRef.child("Students").push();
Students students=new Students(name,email,phone,password);
tasksRef.setValue(student);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从Firebase实时数据库,Android Studio,Java获取数据 - Getting Data from Firebase realtime database, Android Studio, Java 从 Android Studio 中的实时 firebase 数据库中检索数据 - Retrieve data from realtime firebase database in Android Studio Android Studio 未从 Firebase 实时数据库读取检索到的数据 - Android Studio is not reading the retreived data from Firebase realtime database 我想使用android studio中的实时数据库将以前的数据和新数据存储在同一个孩子中 - I want to store previous data and the new data in the same child using realtime database in android studio 我希望这段代码从android studio循环 - I want this code to loop from android studio Java, Android studio, Firebase 数据库如何将数据添加到实时数据库 - Java, Android studio, Firebase database how to add data to realtime database 我想从 Cloud Firestore 数据库中获取纬度和经度以在 map Android Studio 上添加标记 - I want to get latitude and longitude from Cloud Firestore database to add markers on map Android Studio 将数据从 Firestore 数据库(不是实时数据库)移动到 Android Studio 中的新集合 - Move data from Firestore Database (not Realtime Database) to new collection in Android Studio 我想将数据从PC传输到我正在使用以下代码的Android手机,但我无法获得工作目录 - i want to transfer data from pc to android phone for which i am using the following code, i am not able to get working directory 我如何在需要时而不只是在 DataChange 时从 firebase 实时数据库中读取数据 - how can i read data from firebase realtime database when i want and not just when DataChange
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM