Android EventListener未触发

时间:2017-05-09 18:04:15

标签: android firebase firebase-realtime-database

我现在正在尝试做的是尝试获取已经在我的firebase数据库中的位置对象,例如:Artic base并将其存储在我创建的localeobj中,但出于某种原因,当我运行程序时,它一直说localeobj是我正确地做我的听众吗?

package com.example.spy;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import java.util.ArrayList;
import java.util.Random;

import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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 GameJoin extends AppCompatActivity implements View.OnClickListener {
    private FirebaseDatabase database;
    private DatabaseReference myRef;
    private FirebaseUser user;

    private TextView location;
    private TextView role;
    private TextView desc;

    private Button back;

    private Intent extra;
    private Bundle data;

    private String spy;

    private Location localeObj;

    private String game_code;

    private Random rand;

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

        rand = new Random();

        //Firebase stuff
        user = FirebaseAuth.getInstance().getCurrentUser();
        database = FirebaseDatabase.getInstance();
        myRef = database.getReference();

        //Views
        role = (TextView) findViewById(R.id.label_role);
        location = (TextView) findViewById(R.id.label_location);
        desc = (TextView) findViewById(R.id.descriptionText);

        //Buttons
        back = (Button) findViewById(R.id.button3);

        //Attach a listener to the button
        findViewById(R.id.button3).setOnClickListener(this);

        //Retrieve data from previous activity
        extra = getIntent();
        data = extra.getBundleExtra("game_data");
        game_code = data.getString("game_code");

        //TODO: Pull location object from Firebase
        myRef.child("lobby").child(game_code).child("location").addValueEventListener( new ValueEventListener() {

            @Override
            public void onCancelled(DatabaseError error) {
            System.out.println("************************IN CANCELLED*************************************");
            }

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                System.out.println("************************OUTSIDE IF*************************************");
                for (DataSnapshot data : dataSnapshot.getChildren()) {
                    localeObj = dataSnapshot.getValue(Location.class);
                    System.out.println("************************IN IF*************************************");
                }
            }
        });

        myRef.child("lobby").child(game_code).child("spy").addValueEventListener( new ValueEventListener() {

            @Override
            public void onCancelled(DatabaseError error) {

            }

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot data : dataSnapshot.getChildren()) {
                    spy = (String) dataSnapshot.getValue(String.class);
                }
            }
        });

        //Display a special UI if the user is a spy
        if (user.getEmail().equals(spy)) {
            role.setText("You are the spy. Don't get caught!");
            location.setText("Mystery Location");
            desc.setText("Welcome to Spy Fall. Keep your identity hidden for the length of the game, or figure out what the location is to win the game.");
        } else {
            role.setText(localeObj.getRole(rand.nextInt(3)));
            location.setText(localeObj.getLocationName());
            desc.setText("Welcome to Spy Fall. Infer who is the spy before time runs out in order to win the game.");
        }

    }


    @Override
    public void onClick(View v) {
        //Stuff happens when buttons are clicked
        int id = v.getId();
        if (id == R.id.button3) {
            //Clean up old game lobby information
            myRef = database.getReference("lobby");
            myRef.child(game_code).child("players").child(user.getUid()).removeValue(); //Remove all data associated with the current game

            //Return to the main lobby
            Intent main_lobby = new Intent(GameJoin.this, MainActivity.class);
            startActivity(main_lobby);
        }
    }
}

这是我得到的tomcat消息

                                                             --------- beginning of crash
05-09 11:01:42.718 3083-3083/com.example.spy E/AndroidRuntime: FATAL EXCEPTION: main
                                                               Process: com.example.spy, PID: 3083
                                                               java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.spy/com.example.spy.GameJoin}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.spy.Location.getRole(java.lang.Integer)' on a null object reference
                                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                   at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                   at android.os.Looper.loop(Looper.java:154)
                                                                   at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.spy.Location.getRole(java.lang.Integer)' on a null object reference
                                                                   at com.example.spy.GameJoin.onCreate(GameJoin.java:112)
                                                                   at android.app.Activity.performCreate(Activity.java:6679)
                                                                   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
                                                                   at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
                                                                   at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                   at android.os.Looper.loop(Looper.java:154) 
                                                                   at android.app.ActivityThread.main(ActivityThread.java:6119) 
                                                                   at java.lang.reflect.Method.invoke(Native Method) 
                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

https://gyazo.com/2b0c1ee92f365f06b1737c99793c96b3 香港专业教育学院发布了我的数据库结构的样子

1 个答案:

答案 0 :(得分:1)

如果您想获得locationName,请使用以下代码:

myRef.child("lobby").child(game_code).child("location").addValueEventListener( new ValueEventListener() {

    @Override
    public void onCancelled(DatabaseError error) {
        System.out.println("************************IN CANCELLED*************************************");
    }

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        System.out.println("************************OUTSIDE IF*************************************");
        String locationName = (String) dataSnapshot.child("locationName").getValue();
    }
})

希望它有所帮助。