Почему моя база данных не работает, я использую способы в официальной документации? - PullRequest
1 голос
/ 20 февраля 2020

У меня проблема: База данных Firebase не работает, и я не могу понять, почему это произошло (невозможно отправить данные на сервер, когда я нажимаю кнопку для отправки данных - ничего не происходит, данные не сохраняются на сервере ).

Посмотрите мой код:

private var db = FirebaseDatabase.getInstance()                                               
private lateinit var dbReference: DatabaseReference                                           

override fun onCreate(savedInstanceState: Bundle?) {                                          
 super.onCreate(savedInstanceState)                                                        
 setContentView(R.layout.activity_main)                                                    
 setSupportActionBar(toolbar)                                                              

 dbReference = db.reference.child("member")                                                

 add_item_to_db_button.setOnClickListener {                                                 
     dbReference.push()                                                                    
         .setValue(Member(item_name.text.toString(), item_description.text.toString()))    

 }                                                                                         
}  

Мой класс конструктора для отправки данных в базу данных:

 class Member {
 lateinit var itemName: String
 lateinit var itemDescription: String

constructor()
constructor(itemName: String, itemDescription: String) {
    this.itemName = itemName
    this.itemDescription = itemDescription
  }

} 

Мои зависимости (google() и jcenter() Включено на верхнем уровне Gradle):

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'


// Firebase
implementation 'com.google.firebase:firebase-analytics:17.2.2'
implementation 'com.google.firebase:firebase-database:19.2.1'
implementation 'com.google.firebase:firebase-auth:19.2.0'
implementation 'com.google.firebase:firebase-core:17.2.2'
implementation 'com.firebaseui:firebase-ui:0.6.2'
implementation 'com.google.android.gms:play-services-gcm:17.0.0'
implementation 'com.google.android.gms:play-services-auth:17.0.0'
implementation 'com.firebaseui:firebase-ui-auth:4.3.1'

}

apply plugin: 'com.google.gms.google-services'   

Мой XML файл:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:padding="40dp"
 android:orientation="vertical"
 android:gravity="center"
 android:layout_height="match_parent">

 <ImageView
    android:layout_width="200dp"
    android:src="@color/cardview_dark_background"
    android:layout_marginBottom="30dp"
    android:layout_height="200dp"/>

 <EditText
    android:layout_width="match_parent"
    android:id="@+id/item_name"
    android:text="Description"
    android:layout_height="wrap_content"/>

 <EditText
    android:text="Name of product"
    android:layout_width="match_parent"
    android:id="@+id/item_description"
    android:layout_height="wrap_content"/>

 <Button
    android:id="@+id/add_item_to_db_button"
    android:layout_width="match_parent"
    android:text="Add"
    android:layout_height="wrap_content"/>

</LinearLayout>

И, наконец, правила базы данных:

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

Я не понимаю, почему БД не работает. Пробовал несколько способов, выложил в StackOverflow - не помогает.

Ответы [ 3 ]

1 голос
/ 21 февраля 2020

Ну, все люди, которые пытались мне помочь - большое спасибо;) В моем случае все способы мне не помогли, поэтому я попытался подключить Firebase DB к другому Google account, а затем подключить Firebase Database, результат - все работает хорошо.

0 голосов
/ 20 февраля 2020

Измените свой класс на класс данных:

data class Member(val itemName : String, val itemDescription : String) {
constructor() : this("", "")
}
0 голосов
/ 20 февраля 2020

Вам нужна действующая сеть и это разрешение в ваших файлах манифеста. Перепроверьте в вашем файле манифеста.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...