Android,在从Firebase查询数据后无法初始化对象

时间:2018-05-06 17:31:27

标签: android database firebase object google-cloud-firestore

我试图制作像Tanoth / OGame这样简单的旧式浏览器游戏,但是在Android上。我使用Cloud Fire Store数据库,但我遇到了问题。 在登录活动之后,我传入包含用户角色名称的String。有了这个我想通过一个简单的查询从数据库中获取我的PGCharacter对象。在课程开始时我宣布一个PGCharacter变量,但我没有初始化它。

在onCreate方法中,我初始化数据库和存储所有字符的集合。我使用Intent中的ExtraString创建文档引用,因为我的所有文档ID都与播放器用户名相同。之后,我进行查询,如果我找到快照,我想用我的快照结果初始化我的PGCharacter对象。问题是,每次我想打印我的对象的东西它崩溃。我希望我能很好地解释这个问题。 我怎么解决呢?我甚至尝试添加外部功能,但它没有工作。 P.s我的测试我使用现有的播放器

继承我的班级代码:

package com.github.albertocoder97.archadia;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;

public class CharacterActivity extends AppCompatActivity {

private FirebaseFirestore db;
private CollectionReference characterCollection;

private PGCharacter pgCharacter;

private TextView usernameTextView;
private TextView goldTextView;
private TextView gemsTextView;

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

    //Initialize the database
    db = FirebaseFirestore.getInstance();
    //Get characters database
    characterCollection = db.collection("characters");

    Intent intent = getIntent();
    String characterName = intent.getStringExtra("CHARACTER_NAME");

    Log.i("myFilter", "Intent input: " + characterName);

    //Initializing PGCharacter Object
    DocumentReference charDocReference = characterCollection.document(characterName);
    Log.i("myFilter", "ID: " + charDocReference.getId());
    charDocReference.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
        @Override
        public void onSuccess(DocumentSnapshot documentSnapshot) {
            Log.i("myFilter", "Inner Gold DocumentSnapshot: " + documentSnapshot.get("gold").toString());
            setPGCharacter(documentSnapshot);
        }
    });

}




public void setPGCharacter(DocumentSnapshot snapshot){
    PGCharacter temp = snapshot.toObject(PGCharacter.class);
    pgCharacter = temp;
}

}

P.P.s我尝试登录snapshot.getData(),我得到了所有的PGCharacter数据,如果有人问,在我的PGCharacter类中我有一个公共的空构造函数和每个属性的所有获取。

1 个答案:

答案 0 :(得分:1)

删除此行

pgCharacter = temp;