2017-10-13 104 views
3

我正在嘗試爲Android遊戲創建一個簡單的Stats活動。我正在使用新的Firestore數據庫。我已經能夠將文檔保存到我的Firestore數據庫,總分數,最近的分數,平均分數,總遊戲數和高分數,但是當我嘗試從數據庫中讀取數據時,它會返回空值。保存並讀取整數Firestore Android

public void readFromDB(){ 
    statsDoc.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { 
     @Override 
     public void onSuccess(DocumentSnapshot documentSnapshot) { 
      if(documentSnapshot.exists()){ 
       UserData userdata = documentSnapshot.toObject(UserData.class); 
      } 
     } 

我使用用戶數據類:

/* Copyright statement */ 

package com.squidstudios.android.balloonpopper.utils; 

import com.google.firebase.database.IgnoreExtraProperties; 

/** 
* UserData.java 
* 
* This class represents a single user's data including username, email, number of points earned, 
* a saved state of their progress towards earning a single point, and their password. 
*/ 
@IgnoreExtraProperties 
public class UserData { 
    public String email; 
    public int total_points; 

public int avg_score; 
public int high_score; 
public int total_games; 
public int prev_score; 

public UserData() { 
    // Default constructor required for calls to DataSnapshot.getValue(UserData.class) 
} 


public int getTotal_games() { 
    return total_games; 
} 

public void setTotal_games(int total_games) { 
    this.total_games = total_games; 
} 

public int getTotal_points() { 
    return total_points; 
} 

public void setTotal_points(int total_points) { 
    this.total_points = total_points; 
} 

public int getAvg_score() { 
    return avg_score; 
} 

public void setAvg_score(int avg_score) { 
    this.avg_score = avg_score; 
} 

public int getHigh_score() { 
    return high_score; 
} 

public void setHigh_score(int high_score) { 
    this.high_score = high_score; 
} 


public String getEmail() { 
    return email; 
} 

public void setEmail(String email) { 
    this.email = email; 
} 

public int getPrev_score() { 
    return prev_score; 
} 

public void setPrev_score(int prev_score) { 
    this.prev_score = prev_score; 
} 

} 

,當我測試它與字符串,但由於某種原因整數工作不正常工作。提前致謝!

回答

4

在做了一些測試之後,我得到了最後的結論,我們必須將Longs轉換爲Integers,因爲這是我們從Firestore獲取「Number」所得到的結果。 這裏是我的數據是什麼樣子:


使用該做的鑄造:
1]

確保您通過點擊「編輯」圖標,在該領域的最終存儲在「數」: Safely casting long to int in Java

我的代碼如下所示:

int money = snapshot.getLong("money").intValue(); 


隨意問了進一步的解釋!

+0

對我很好。如果沒有提供字段,我會建議先進行NOT NULL檢查。 – Jozef