【问题标题】:Firebase Java Admin SDK don't workFirebase Java Admin SDK 不起作用
【发布时间】:2017-09-27 08:59:33
【问题描述】:

我正在关注 Firebase 网站上关于设置 Java Admin SDK 的文档。于是我在build.gradle中添加了依赖,并添加了如下代码:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.auth.FirebaseCredentials;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class Main {

    public static void main(String[] args) throws FileNotFoundException{
        FileInputStream serviceAccount = new FileInputStream("/Users/idanaviv10/Desktop/mapit-33290-firebase-adminsdk-fdy24-a1d0505493.json");

        FirebaseOptions options = new FirebaseOptions.Builder()
          .setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
          .setDatabaseUrl("https://mapit-33290.firebaseio.com/")
          .build();

        FirebaseApp.initializeApp(options);
        final FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference ref = database.getReference("server/saving-data/fireblog");

        DatabaseReference usersRef = ref.child("users");

        Map<String, User> users = new HashMap<String, User>();
        users.put("alanisawesome", new User("June 23, 1912", "Alan Turing"));
        users.put("gracehop", new User("December 9, 1906", "Grace Hopper"));

        usersRef.setValue(users);
    }
    public static class User {

        public String date_of_birth;
        public String full_name;
        public String nickname;

        public User(String date_of_birth, String full_name) {
            // ...
        }

        public User(String date_of_birth, String full_name, String nickname) {
            // ...
        }

    }
}

问题是当我尝试获取数据(添加侦听器)或尝试保存数据(如示例中)时,什么也没发生。我在 Eclipse 中运行代码,我可以在控制台中看到它打印“完成”,但是当我检查数据库(在浏览器的 firebase 控制台上)时,没有任何变化。

【问题讨论】:

  • 您必须使 HashMap 将值设置到数据库,请参阅保存数据下的 here
  • 感谢您的回复。我尝试从文档中复制确切的示例,但仍然无法正常工作。
  • 控制台中是否有任何数据库错误?检查权限。
  • 控制台没有报错,权限里读写都设置为true。
  • 您的用户孩子下是否有这些字段(date_of_birth、full_name、昵称)?将数据库构建添加到您的问题中

标签: java firebase firebase-realtime-database firebase-admin


【解决方案1】:

我发现了问题,问题是程序将在连接到 Firebase 服务器之前终止。你需要做的是延迟程序的终止,或者调用Thread.sleep(20000);,或者像我一样

Scanner scanner = new Scanner(System.in);
while(!scanner.nextLine().equals("Quit")){}
System.exit(0);  

【讨论】:

  • 当您第一次开始从非 Android Java 访问 Firebase 数据库时,这确实是一个常见问题。我们之前曾多次遇到过这个问题,但很明显,当您搜索它时,这些问题并没有出现。希望其他陷入相同情况的人能找到这个答案。
【解决方案2】:

您可以尝试的另一件事是使用Tasks API 显式等待setValue() 任务完成:

Task<Void> task = usersRef.setValue(users);
try {
    Tasks.await(task);
} catch (ExecutionException | InterruptedException e) {
    // Handle error if necessary
}

【讨论】:

  • 嗨,firebase admin sdk 中有 ref.push().setValueAsync(users)。你看了吗,怎么处理。我面临同样的问题,我添加了儿童听众,但他们没有工作。我什至在主线程中尝试了“while循环”来等待,但监听器回调不起作用。
  • 您必须等待ApiFuture 解决。最简单的方法是在返回的 Future 上调用 get()
  • 我正在做 geton async future 。它正在将数据加载到 firebase,但在 firebase 数据库上添加的回调侦听器未执行。我从 google firebase java sdk 获取了代码。我在下面添加了完整代码的评论
  • Firebase Admin Java SDK 中没有 setValue(users) 这样的方法返回 Task
  • 旧版本 (v5)。这个问题已经有好几年了。
【解决方案3】:

下面的代码使用来自 firebase sdk 的 java async call api 将数据推送到 firebase 数据库,但监听器代码没有执行。我在服务器端后端运行下面​​的代码。

 public enum Firebase {
INSTANCE;

FirebaseApp firebaseApp;


public void initilizeFirebaseApp(ConfigLoader configReader) {

    CountDownLatch done = new CountDownLatch(1);
    final AtomicInteger message1 = new AtomicInteger(0);
    InputStream firebaseSecret = getClass().getClassLoader().getResourceAsStream("ServiceAccount.json");
    final GoogleCredentials credentials;
    try {
        credentials = GoogleCredentials.fromStream(firebaseSecret);
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("Error while reading Firebase config file." + e.toString());
        throw new IllegalStateException(e);
    }

    Map<String, Object> auth = new HashMap<>();
    auth.put("uid", "my_resources");

    FirebaseOptions options = new Builder()
            .setConnectTimeout(1000)
            .setCredentials(credentials)
            .setDatabaseAuthVariableOverride(auth)
            .setDatabaseUrl(configReader.getFirebaseDatabaseURL())
            .setStorageBucket(configReader.getFirebaseStorageBucket())
            .setProjectId(configReader.getFirebseProjectId())
            .build();

    firebaseApp = FirebaseApp.initializeApp(options);


    System.out.println(firebaseApp.getName());
    //System.out.println(firebaseApp.getName());
    // Use the shorthand notation to retrieve the default app's service
    FirebaseAuth defaultAuth = FirebaseAuth.getInstance();
    FirebaseDatabase defaultDatabase = FirebaseDatabase.getInstance();


    // The app only has access as defined in the Security Rules
    DatabaseReference ref = FirebaseDatabase
            .getInstance()
            .getReference("/analyst_profiles");


    DateTime dt = new DateTime(java.util.Date.from(Instant.now()), java.util.TimeZone.getDefault());
    System.out.println(dt.getValue());
    //test data push
    // https://firebase.google.com/docs/database/admin/save-data
    AnalystProfiles analystProfilesObjTemp = new AnalystProfiles("test2", Long.toString(dt.getValue()), "dsds", "ds", "ds",
            "dsa2323", "32ddss232");

    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            AnalystProfiles post = dataSnapshot.getValue(AnalystProfiles.class);
            System.out.println(post);
            //done.countDown();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            System.out.println("The read failed: " + databaseError.getCode());
        }


    });


    CompletableFuture<String> welcomeText = CompletableFuture.supplyAsync(() -> {
        try {
            ref.push().setValueAsync(analystProfilesObjTemp).get();
        } catch (ExecutionException | InterruptedException e) {
            throw new RuntimeException("Error while waiting for future", e);
        }
        return "ok";

    }).thenApply(x -> {
        System.out.println(x);
        System.out.println("Listeners code is not executing");
        return x;
    });


    done.countDown();
    try {
        System.out.println(welcomeText.get());
        done.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }


}


public void testdataLoad() {

    // The app only has access as defined in the Security Rules
    DatabaseReference ref = FirebaseDatabase
            .getInstance()
            .getReference("/analyst_profiles");


    DateTime dt = new DateTime(java.util.Date.from(Instant.now()), java.util.TimeZone.getDefault());
    System.out.println(dt.getValue());
    //test data push
    // https://firebase.google.com/docs/database/admin/save-data
    AnalystProfiles analystProfilesObjTemp = new AnalystProfiles("test2", Long.toString(dt.getValue()), "dsds", "ds", "ashutsh",
            "dsa2323", "32ddss232");

    CompletableFuture<String> welcomeText = CompletableFuture.supplyAsync(() -> {
        try {
            ref.push().setValueAsync(analystProfilesObjTemp).get();
        } catch (ExecutionException | InterruptedException e) {
            throw new RuntimeException("Error while waiting for future", e);
        }
        return "ok";

    }).thenApply(x -> {
        System.out.println(x);
        return x;
    });



    try {
        System.out.println(welcomeText.get());

    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

}

}

【讨论】:

    【解决方案4】:

    添加此代码:

    ApiFuture api=/*your reference to database*/usersRef.setValueAsync(users/*the data*/);
    
    Object o = api.get(/*time out*/8,TimeUnit.SECONDS/*unite for time out her is seconds*/);
    

    最后你可以检查一下

    api.isDone();
    

    【讨论】:

      猜你喜欢
      • 2018-05-02
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 2018-05-02
      • 2018-03-20
      • 2020-01-17
      • 1970-01-01
      • 2018-08-16
      相关资源
      最近更新 更多