我正在关注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中运行代码,我可以在控制台中看到它打印&#34; Done&#34;,但是当我检查数据库时(在浏览器上的firebase控制台上)没有任何变化。
答案 0 :(得分:7)
我发现了问题,问题是程序将在连接到Firebase服务器之前终止。您需要做的是通过调用Thread.sleep(20000);
来延迟程序的终止,或者像我做的那样
Scanner scanner = new Scanner(System.in);
while(!scanner.nextLine().equals("Quit")){}
System.exit(0);
答案 1 :(得分:5)
您可以尝试的另一件事是使用Tasks
API明确等待setValue()
任务完成:
Task<Void> task = usersRef.setValue(users);
try {
Tasks.await(task);
} catch (ExecutionException | InterruptedException e) {
// Handle error if necessary
}
答案 2 :(得分:0)
以下代码使用Firebase SDK中的Java异步调用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();
}
}
}
答案 3 :(得分:0)