2

我正在关注 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 控制台上)时,没有任何变化。 在此处输入图像描述

4

4 回答 4

9

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

Scanner scanner = new Scanner(System.in);
while(!scanner.nextLine().equals("Quit")){}
System.exit(0);  
于 2017-04-29T10:21:31.090 回答
5

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

Task<Void> task = usersRef.setValue(users);
try {
    Tasks.await(task);
} catch (ExecutionException | InterruptedException e) {
    // Handle error if necessary
}
于 2017-04-29T20:05:16.960 回答
0

添加此代码:

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();

截屏

于 2019-12-06T20:59:37.703 回答
0

下面的代码使用来自 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();
    }

}

}

于 2019-01-30T08:32:45.067 回答