无法在Android应用上显示Firebase控制台中的数据

时间:2019-02-24 05:47:48

标签: android firebase firebase-realtime-database

我正在尝试进行一个非常基本的测验活动,以显示Firebase实时数据库中存储的JSON文件中的问题和选项。但是由于某种原因,什么也没有显示,并且该页面留为空白。

这是我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文件如下所示:

JSON file in the database

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'

我还想提到我已经使用setText()方法使用此活动在firebase控制台中尝试并设置了数据,并且它可以工作。唯一的问题似乎是数据检索。

我非常感谢您的帮助和任何其他资源,以使问题更易于理解。谢谢!!!

编辑:这是我运行应用程序时在手机上收到的错误:

enter image description here

1 个答案:

答案 0 :(得分:0)

首先,我猜测1, 2节点下面的Questions个子节点是按顺序递增的。

1)像这样初始化数据库引用时

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

您已经在1节点中(因为最初 int total = 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节点上,因为total的值为1。因此,在调用updateQuestion();之前增加total。无处不在,在按钮单击侦听器上调用updateQuestion的地方。

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

希望这会有所帮助。