在Firebase数据库中检索数据重复时遇到麻烦-Unity C#

时间:2018-10-07 20:03:10

标签: c# firebase unity3d firebase-realtime-database

您好,我正在尝试使用Unity创建一个简单的消息传递应用程序,但是这样做很麻烦。

所以目前,我正试图通过创建按钮来填充最新消息的列表(实时),我首先运行LoadRecentMessages()以在您的“ users_chat_info” 中获取您的聊天ID。从Firebase数据库中运行,然后运行GetRecentMsgs(),它会获取您聊天中的最新消息,该消息是从Firebase数据库路径“ chat”>“ chat_room”>“(SomeGeneratedKey)”>“ m_recent” ,然后创建包含该信息的按钮。如下所示,这是我正在使用的数据树,因此您可以了解其工作原理 (DataTree)

现在我遇到的问题是由于某种原因两次创建了按钮。我运行了一个调试日志,当运行GetRecentMsgs()时,chatIds的计数为2而不是1,这很奇怪。这是下面的Debug.Log。

Received values for ChatIds.
Chat Room Id's : -LOEgQUGcG4P2jMRmO22

CHATLIST COUNT(ChatidRetreive) : 1
Received values for RecenttMessages.
CHATLIST COUNT(ChatidRetreive) : 2
Received values for RecenttMessages.
CHATLIST COUNT(ChatidRetreive) : 2
Created Recent Message : hello
CHATLIST COUNT(AfterCreatedRMbutton) : 2
Created Recent Message : CfXVOi8XFib4q4X1q02pAnoNsek2
CHATLIST COUNT(AfterCreatedRMbutton) : 2

代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Firebase;
using Firebase.Database;
using Firebase.Unity.Editor;

public class MessagingHandler : MonoBehaviour {

private string currentID;
private string chatingWithID;
private string chatID;
public FirebaseMethods fh;
public GameObject Button_Template;
public GameObject RecentMsg_Template;
List<string> chatIds = new List<string>();
ArrayList recentMsgs = new ArrayList();
ArrayList messages = new ArrayList();

private GameObject[] recent_msgs;
private GameObject[] msgs;
DependencyStatus dependencyStatus = DependencyStatus.UnavailableOther;

public void InitializeMsgHandler()
{
    currentID = fh.userID;
    chatIds.Clear();
    chatIds.Add("Firebase");
    messages.Clear();
    messages.Add("Firebase");
    msgs = new GameObject[1];


    FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task => {
        dependencyStatus = task.Result;
        if (dependencyStatus == DependencyStatus.Available)
        {
            InitializeFirebase();
        }
        else
        {
            Debug.LogError(
              "Could not resolve all Firebase dependencies: " + dependencyStatus);
        }
    });
}

// Initialize the Firebase database:
protected virtual void InitializeFirebase()
{
    FirebaseApp app = FirebaseApp.DefaultInstance;
    // NOTE: You'll need to replace this url with your Firebase App's database
    // path in order for the database connection to work correctly in editor.
    app.SetEditorDatabaseUrl(FirebaseGlobals.dbUrl);
    if (app.Options.DatabaseUrl != null)
        app.SetEditorDatabaseUrl(app.Options.DatabaseUrl);
    StartListener();
}

protected void StartListener()
{
    LoadRecentMessages();
}

private void LoadRecentMessages()
{
      FirebaseDatabase.DefaultInstance
      .GetReference("chat")
      .Child("users_chat_info")
      .Child(currentID)
      .ValueChanged += (object sender2, ValueChangedEventArgs e2) => {
          if (e2.DatabaseError != null)
          {
              Debug.LogError(e2.DatabaseError.Message);
              return;
          }
          Debug.Log("Received values for ChatIds.");
          string title = chatIds[0].ToString();
          chatIds.Clear();
          chatIds.Add(title);
          //Debug.Log(recentMsgs.ToString());
          if (e2.Snapshot != null && e2.Snapshot.ChildrenCount > 0)
          {
              foreach (var childSnapshot in e2.Snapshot.Children)
              {
                  if (childSnapshot == null || childSnapshot.Value == null)
                  {
                      Debug.LogError("Bad data in sample.  Did you forget to call SetEditorDatabaseUrl with your project id?");
                      break;
                  }
                  else
                  {

                      Debug.Log("Chat Room Id's : " + childSnapshot.Child("chat_id").Value.ToString());
                      Debug.Log("CHATLIST COUNT(ChatidRetreive) : " + chatIds.Count);
                      //chatIds.Insert(1, childSnapshot.Child("chat_id").Value.ToString());
                      chatIds.Add(childSnapshot.Child("chat_id").Value.ToString());
                  }
              }
          }
          GetRecentMsgs();
      };
}
private void GetRecentMsgs()
{
    for (int i = 0; i < chatIds.Count; i++)
    {
        FirebaseDatabase.DefaultInstance
      .GetReference("chat")
      .Child("chat_rooms")
      .Child(chatIds[i])
      .Child("m_recent")
      .ValueChanged += (object sender2, ValueChangedEventArgs e2) =>
      {
          if (e2.DatabaseError != null)
          {
              Debug.LogError(e2.DatabaseError.Message);
              return;
          }
          Debug.Log("Received values for RecenttMessages.");
          Debug.Log("CHATLIST COUNT(ChatidRetreive) : " + chatIds.Count);
          if (e2.Snapshot != null && e2.Snapshot.ChildrenCount > 0)
          {
              foreach (var childSnapshot in e2.Snapshot.Children)
              {
                  if (childSnapshot == null || childSnapshot.Value == null)
                  {
                      Debug.LogError("Bad data in sample.  Did you forget to call SetEditorDatabaseUrl with your project id?");
                      break;
                  }
                  else
                  {
                      Debug.Log("Created Recent Message : " + childSnapshot.Value.ToString());
                      GameObject go = Instantiate(RecentMsg_Template) as GameObject;
                      go.SetActive(true);
                      Msg TB = go.GetComponent<Msg>();
                      go.transform.SetParent(RecentMsg_Template.transform.parent);

                      Debug.Log("CHATLIST COUNT(AfterCreatedRMbutton) : " + chatIds.Count);
                  }
              }
          }
      };
    }
}

}

0 个答案:

没有答案