Не может отображать данные из консоли Firebase в приложении для Android

Я пытаюсь сделать довольно простую викторину, которая отображает вопросы и параметры из сохраненного файла JSON в базе данных Firebase в реальном времени. Но почему-то ничего не отображается и страница остается пустой.

вот мой код перед QuizActivity.java

package com.example.android.scienceapp;

import android.graphics.Color;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class QuizActivity extends AppCompatActivity {
    Button b1, b2, b3, b4;
    TextView t1_question, timerTxt;
    int total = 1;
    int correct = 0;
    int wrong = 0;
    DatabaseReference reference;
    DatabaseReference database;

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_quiz);

    b1 = findViewById(R.id.button2);
    b2 = findViewById(R.id.button3);
    b3 = findViewById(R.id.button4);
    b4 = findViewById(R.id.button5);

    t1_question = findViewById(R.id.questiontxt);
    updateQuestion();

 private void updateQuestion() {

        reference = FirebaseDatabase.getInstance().getReference().child("Questions").child(String.valueOf(total));
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        final Question question = snapshot.getValue(Question.class);


                    String ques = question.getQuestion();
                    String op1 = question.getOption1();
                    String op2 = question.getOption2();
                    String op3 = question.getOption3();
                    String op4 = question.getOption4();

                    t1_question.setText(ques);
                    b1.setText(op1);
                    b2.setText(op2);
                    b3.setText(op3);
                    b4.setText(op4);

                    b1.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            if ((b1.getText().toString().equals(question.getAnswer()))) {
                                b1.setBackgroundColor(Color.GREEN);
                                Handler handler = new Handler();
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        correct++;
                                        b1.setBackgroundColor(Color.parseColor("#DB7093"));

                                        updateQuestion();

                                    }
                                }, 1500);

                            } else {
                                Toast.makeText(QuizActivity.this, "Incorrect", Toast.LENGTH_SHORT).show();
                                wrong = wrong + 1;

                                b1.setBackgroundColor(Color.RED);

                                if (b2.getText().toString().equals(question.getAnswer())) {
                                    b2.setBackgroundColor(Color.GREEN);
                                } else if (b3.getText().toString().equals(question.getAnswer())) {
                                    b3.setBackgroundColor(Color.GREEN);
                                } else if (b4.getText().toString().equals(question.getAnswer())) {
                                    b4.setBackgroundColor(Color.GREEN);
                                }


                                Handler handler = new Handler();
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        b1.setBackgroundColor(Color.parseColor("#DB7093"));
                                        b2.setBackgroundColor(Color.parseColor("#DB7093"));
                                        b3.setBackgroundColor(Color.parseColor("#DB7093"));
                                        b4.setBackgroundColor(Color.parseColor("#DB7093"));
                                        updateQuestion();
                                    }

                                }, 1500);

                            }
                        }

                    });

                    b2.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            if ((b2.getText().toString().equals(question.getAnswer()))) {
                                b2.setBackgroundColor(Color.GREEN);
                                Handler handler = new Handler();
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        correct++;
                                        b2.setBackgroundColor(Color.parseColor("#DB7093"));

                                        updateQuestion();

                                    }
                                }, 1500);

                            } else {
                                Toast.makeText(QuizActivity.this, "Incorrect", Toast.LENGTH_SHORT).show();
                                wrong = wrong + 1;

                                b2.setBackgroundColor(Color.RED);

                                if (b1.getText().toString().equals(question.getAnswer())) {
                                    b1.setBackgroundColor(Color.GREEN);
                                } else if (b3.getText().toString().equals(question.getAnswer())) {
                                    b3.setBackgroundColor(Color.GREEN);
                                } else if (b4.getText().toString().equals(question.getAnswer())) {
                                    b4.setBackgroundColor(Color.GREEN);
                                }


                                Handler handler = new Handler();
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        b1.setBackgroundColor(Color.parseColor("#DB7093"));
                                        b2.setBackgroundColor(Color.parseColor("#DB7093"));
                                        b3.setBackgroundColor(Color.parseColor("#DB7093"));
                                        b4.setBackgroundColor(Color.parseColor("#DB7093"));
                                        updateQuestion();
                                    }

                                }, 1500);

                            }
                        }

                    });

                    b3.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            if ((b3.getText().toString().equals(question.getAnswer()))) {
                                b3.setBackgroundColor(Color.GREEN);
                                Handler handler = new Handler();
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        correct++;
                                        b3.setBackgroundColor(Color.parseColor("#DB7093"));

                                        updateQuestion();

                                    }
                                }, 1500);

                            } else {
                                Toast.makeText(QuizActivity.this, "Incorrect", Toast.LENGTH_SHORT).show();
                                wrong = wrong + 1;

                                b3.setBackgroundColor(Color.RED);

                                if (b2.getText().toString().equals(question.getAnswer())) {
                                    b2.setBackgroundColor(Color.GREEN);
                                } else if (b1.getText().toString().equals(question.getAnswer())) {
                                    b1.setBackgroundColor(Color.GREEN);
                                } else if (b4.getText().toString().equals(question.getAnswer())) {
                                    b4.setBackgroundColor(Color.GREEN);
                                }


                                Handler handler = new Handler();
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        b1.setBackgroundColor(Color.parseColor("#DB7093"));
                                        b2.setBackgroundColor(Color.parseColor("#DB7093"));
                                        b3.setBackgroundColor(Color.parseColor("#DB7093"));
                                        b4.setBackgroundColor(Color.parseColor("#DB7093"));
                                        updateQuestion();
                                    }

                                }, 1500);

                            }
                        }

                    });

                    b4.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            if ((b4.getText().toString().equals(question.getAnswer()))) {
                                b4.setBackgroundColor(Color.GREEN);
                                Handler handler = new Handler();
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        correct++;
                                        b4.setBackgroundColor(Color.parseColor("#DB7093"));

                                        updateQuestion();

                                    }
                                }, 1500);

                            } else {
                                Toast.makeText(QuizActivity.this, "Incorrect", Toast.LENGTH_SHORT).show();
                                wrong = wrong + 1;

                                b4.setBackgroundColor(Color.RED);

                                if (b2.getText().toString().equals(question.getAnswer())) {
                                    b2.setBackgroundColor(Color.GREEN);
                                } else if (b3.getText().toString().equals(question.getAnswer())) {
                                    b3.setBackgroundColor(Color.GREEN);
                                } else if (b1.getText().toString().equals(question.getAnswer())) {
                                    b1.setBackgroundColor(Color.GREEN);
                                }


                                Handler handler = new Handler();
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        b1.setBackgroundColor(Color.parseColor("#DB7093"));
                                        b2.setBackgroundColor(Color.parseColor("#DB7093"));
                                        b3.setBackgroundColor(Color.parseColor("#DB7093"));
                                        b4.setBackgroundColor(Color.parseColor("#DB7093"));
                                        updateQuestion();
                                    }

                                }, 1500);
                                updateQuestion();

                            }
                        }


                    });


                }

 }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    }
}

XML-активность выглядит следующим образом:

 <?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout 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 = ".QuizActivity">

    <TextView
        android:id = "@+id/questiontxt"
        android:layout_width = "352dp"
        android:layout_height = "131dp"
        android:layout_alignParentEnd = "true"
        android:layout_alignParentTop = "true"
        android:layout_marginEnd = "14dp"
        android:layout_marginTop = "14dp"
        android:textSize = "28sp"
        android:textAlignment = "center"
        />

    <Button
        android:id = "@+id/button2"
        android:layout_width = "150dp"
        android:layout_height = "119dp"
        android:layout_alignParentStart = "true"
        android:layout_alignParentTop = "true"
        android:layout_marginStart = "27dp"
        android:layout_marginTop = "173dp"
        android:background = "#DB7093"
        android:padding = "8dp" />

    <Button
        android:id = "@+id/button3"
        android:layout_width = "146dp"
        android:layout_height = "119dp"
        android:layout_alignStart = "@+id/button5"
        android:layout_alignTop = "@+id/button2"
        android:background = "#DB7093"
        android:padding = "8dp" />

    <Button
        android:id = "@+id/button4"
        android:layout_width = "150dp"
        android:layout_height = "119dp"
        android:layout_alignStart = "@+id/button2"
        android:layout_alignTop = "@+id/button5"
        android:background = "#DB7093"
        android:padding = "8dp" />

    <Button
        android:id = "@+id/button5"
        android:layout_width = "148dp"
        android:layout_height = "119dp"
        android:layout_alignParentBottom = "true"
        android:layout_alignParentEnd = "true"
        android:layout_marginBottom = "84dp"
        android:layout_marginEnd = "27dp"
        android:background = "#DB7093"
        android:padding = "8dp" />


    </RelativeLayout>

И файл JSON в базе данных выглядит так:

Не может отображать данные из консоли Firebase в приложении для Android

А build.gradle(app) выглядит так:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.android.scienceapp"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner 
  "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 
'proguard-rules.pro'
        }
    }
}

 dependencies {
      implementation fileTree(dir: 'libs', include: ['*.jar'])
      //noinspection GradleCompatible
      implementation 'com.android.support:design:27.1.1'
      implementation 'com.android.support:appcompat-v7:27.1.1'
      implementation 'com.android.support.constraint:constraintlayout:1.1.0-beta4'
        implementation 'com.google.firebase:firebase-database:16.0.1'
        implementation 'com.google.firebase:firebase-auth:16.0.1'
        implementation 'com.google.firebase:firebase-core:16.0.1'
        implementation 'com.firebase:firebase-client-android:2.3.1'
        implementation 'com.google.firebase:firebase-storage:16.0.1'


    implementation 'com.google.android.gms:play-services-auth:16.0.1'


    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso- 
core:3.0.2'
   }apply plugin: 'com.google.gms.google-services'

ТАКЖЕ я хотел бы упомянуть, что я пытался установить данные в консоли firebase, используя это действие, используя метод setText(), и это работает. Единственная проблема, кажется, поиск данных.

Я был бы очень признателен за помощь и любой другой ресурс, чтобы сделать вопрос более понятным. БЛАГОДАРНОСТЬ!!!

Обновлено: это ошибка, которую я получаю сейчас на своем телефоне, когда запускаю приложение:

Не может отображать данные из консоли Firebase в приложении для Android

Поставь свой logcat тоже

Swati 24.02.2019 08:07

Я разместил это .. Можете ли вы помочь ?? :)

user9799719 24.02.2019 11:35
0
2
167
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Прежде всего, я предполагаю, что 1, 2 дочерние узлы ниже Questions узла последовательно увеличиваются.

1) Когда вы инициализировали ссылку на базу данных, как это

reference = FirebaseDatabase.getInstance().getReference().child("Questions").child(String.valueOf(total));

Вы уже находитесь в узле 1 (поскольку изначально общее количество = 1;). Следовательно,

for (DataSnapshot snapshot : dataSnapshot.getChildren()){

не будет работать. Вероятно, вы получите исключение. Поэтому предлагаю следующие изменения:

private void updateQuestion() {

    reference = FirebaseDatabase.getInstance().getReference().child("Questions").child(String.valueOf(total));
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            //for (DataSnapshot snapshot : dataSnapshot.getChildren()){
            if (dataSnapshot.exists()) {
                DataSnapshot snapshot = dataSnapshot;
                /*final Question question = snapshot.getValue(Question.class);

                String ques = question.getQuestion();
                String op1 = question.getOption1();
                String op2 = question.getOption2();
                String op3 = question.getOption3();
                String op4 = question.getOption4();*/

                String ques = snapshot.child("question").getValue().toString();
                String op1 = snapshot.child("option1").getValue().toString();
                String op2 = snapshot.child("option2").getValue().toString();
                String op3 = snapshot.child("option3").getValue().toString();
                String op4 = snapshot.child("option4").getValue().toString();

                //### ADD THIS ALSO ###
                final String answer = snapshot.child("answer").getValue().toString();
                .......

2) Затем замените каждую проверку кнопки на эту.

//if ((b1.getText().toString().equals(question.getAnswer()))) {
if ((b1.getText().toString().equals(answer))) {

сделайте это также для b2, b3 и b4.

3) Наконец, поскольку вы находитесь на узле 1, так как общее значение равно 1. Поэтому увеличивайте общее количество перед вызовом updateQuestion();. Делайте везде, где вы вызывали updateQuestion для прослушивателей кликов по кнопкам.

total++;    //<< Add this statement to jump to next node of firebase database
updateQuestion();

Надеюсь это поможет.

поскольку, согласно вашему вопросу, важно было получить только данные Firebase, но для завершения функциональности приложения в целом я добавил шаги 2 и 3 для справки. Надеюсь, это помогло, но вы можете сделать это по-другому, как вам нужно. Добро пожаловать!

Ujjwal Jung Thapa 24.02.2019 12:14

Другие вопросы по теме