# #android #firebase #kotlin #firebase-realtime-database
Вопрос:
Я не вижу, чего мне не хватает. Все, что я хочу, — это ввести текст из 2 полей редактирования, а затем нажать кнопку сохранить, чтобы обновить базу данных. Пожалуйста, смотрите ниже для получения дополнительной информации и большое вам спасибо за любую помощь. База данных очень проста, она называется просто «пользователи», если есть какая-либо другая информация, которую я могу предоставить, пожалуйста, дайте мне знать. Спасибо.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@ id/inputFirstName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:hint="enter your first name"
android:layout_margin="10dp"
/>
<EditText
android:id="@ id/inputLastName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:hint="enter your last name"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@ id/inputFirstName" />
<Button android:id="@ id/saveButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="save"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@id/inputLastName" />
</androidx.constraintlayout.widget.ConstraintLayout>
Основная активность.тыс. т
package com.example.firedemo
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Parcelable
import android.text.TextUtils
import android.widget.Button
import android.widget.EditText
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.IgnoreExtraProperties
import kotlinx.android.synthetic.main.activity_main.*
@IgnoreExtraProperties
data class user(
var firstname: String,
var lastname: String
)
private lateinit var dbReference: DatabaseReference
private lateinit var firebaseDatabase: FirebaseDatabase
private var userId: String = ""
//EditText
@SuppressLint("StaticFieldLeak")
private lateinit var firstNameEt: EditText
@SuppressLint("StaticFieldLeak")
private lateinit var lastNameEt: EditText
//Button
@SuppressLint("StaticFieldLeak")
private lateinit var saveButton: Button
abstract class MainActivity() : AppCompatActivity(), Parcelable {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
firebaseDatabase = FirebaseDatabase.getInstance()
dbReference = firebaseDatabase.getReference("users")
firstNameEt = findViewById(R.id.inputFirstName)
lastNameEt = findViewById(R.id.inputLastName)
userId = dbReference.push().key.toString()
saveButton.setOnClickListener{
val firstname: String = firstNameEt.text.toString()
val lastname: String = lastNameEt.text.toString()
if(TextUtils.isEmpty(userId)){
createUser(firstname, lastname)
} else{
null
}
}
}
private fun createUser(firstname: String, lastname: String){
// Write a message to the database
val user = user(firstname, lastname)
dbReference.child(userId).setValue(user)
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.firedemo">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Firedemo">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
сборка.сортировка
plugins {
id 'com.android.application'
id 'com.google.gms.google-services'
id 'kotlin-android'
id 'kotlin-android-extensions'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.example.firedemo"
minSdkVersion 23
targetSdkVersion 30
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 "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'com.google.firebase:firebase-database:19.7.0'
testImplementation 'junit:junit:4. '
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation platform('com.google.firebase:firebase-bom:26.7.0')
implementation 'com.google.firebase:firebase-analytics-ktx'
}
Комментарии:
1. Что именно во всех этих строках кода работает не так, как вы ожидаете? Пожалуйста, также отредактируйте свой вопрос и добавьте структуру базы данных в виде файла JSON или, по крайней мере, скриншота.
2. Можете ли вы воспроизвести проблему без чтения данных из каких-либо элементов пользовательского интерфейса? Например, с жестко закодированными значениями в
createUser(firstname, lastname)
? Это означало бы, что весь XML не нужен, и вы можете удалить его из своего вопроса. Сосредоточение внимания на таком вопросе-отличный способ повысить вероятность того, что кто-то сможет помочь.3. Если
dbReference.child(userId).setValue(user)
запись в базу данных не выполняется, вам потребуется добавить прослушиватель завершения для ее завершения, чтобы узнать, есть ли какие-либо ошибки. Смотрите здесь пример того, как это сделать: gist.github.com/puf/4a94a01e3c2510298ee46d0a7f90ab75 Если вы не решите эту проблему с помощью этого, покажите обновленный код и его выходные данные в своем вопросе.