从Firebase实时数据库(Qt c ++)获得价值

时间:2020-01-17 03:02:43

标签: android c++ firebase qt firebase-realtime-database

我正在使用Qt开发适用于Android的应用程序,此刻,我试图从Firebase实时数据库中获取一个值,但我一直得到 0 false )为firebase::kFutureStatusPending。我可以通过在数据库上使用SetValue()来设置值,并且已经将urldbref.Child(user->uid()).Child("Nickname").url()进行了检查,这是正确的。这是我与此部分相关的代码,最后我还包括了JSON结构:

firebase::database::Database *database=firebase::database::Database::GetInstance(_app);
dbref = database->GetReferenceFromUrl("https://***/");

firebase::Future<firebase::database::DataSnapshot> result =
    dbref.Child(user->uid()).Child("Nickname").GetValue();


if (result.status() != firebase::kFutureStatusPending) {
  if (result.status() != firebase::kFutureStatusComplete) {
    qDebug() <<"ERROR: GetValue() returned an invalid result.";

  } else if (result.error() != firebase::database::kErrorNone) {
    qDebug() << result.error_message();

  } else {
    firebase::database::DataSnapshot snapshot = *result.result();
    qDebug() << "snapshot available" ;
  }
}

else {
    qDebug() << "results are still pending";
}

如何在我的Nickname中获得Raad子(在这种情况下为Qt Android app)的值?

这是JSON文件的内容:

{
  "YQEa5KquWgOiPHfD7SLSgU92mTH2" : {
    "Email Address" : "shariatraad@gmail.com",
    "Nickname" : "Raad"
  }
}

2 个答案:

答案 0 :(得分:1)

documentation复制代码时,您似乎错过了以下注释:

// In the game loop that polls for the result...

if (result.status() != firebase::kFutureStatusPending) {
  if (result.status() != firebase::kFutureStatusComplete) {

由于数据是异步加载的,因此result.status()并不正确。因此,您需要在游戏循环中或在其他重复运行的地方进行检查。

或者,您也可以使用Future.onCompletion,如here所示:

// Or, set an OnCompletion callback, which accepts a C++11 lambda or
// function pointer. You can pass your own user data to the callback. In
// most cases, the callback will be running in a different thread, so take
// care to make sure your code is thread-safe.
future.OnCompletion([](const Future< SampleResultType >& completed_future,
                       void* user_data) {
  // We are probably in a different thread right now.
  if (completed_future.error() == 0) {
    DoSomethingWithResultData(completed_future.result());
  }
  else {
    LogMessage("Error %d: %s",
               completed_future.error(),
               completed_future.error_message());
  }
}, user_data);

但是在这种情况下,同样重要的是确保在检索数据之前,程序(的main)不会退出,否则您将永远看不到它。

答案 1 :(得分:0)

我通过将其添加到代码中解决了该问题:

result.OnCompletion([](const firebase::Future<firebase::database::DataSnapshot>& completed_future){
    if (completed_future.error() == 0)
    {
       //Do what you need to do with your value here
    }
}
);