我使用的是netbean,这是我的代码。但是当我运行代码时没有错误,并且没有数据保存在firebase中。我已经在google firebsae教程https://firebase.google.com/docs/database/admin/save-data的帮助下完成了这项工作。 那么我的代码有什么问题。或者还有其他好的方法吗
package com.recomm.mavenrec.algorithm.firebaseConnection;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.auth.FirebaseCredentials;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.recomm.mavenrec.Entity.Book;
import com.recomm.mavenrec.Entity.Hospital;
import java.io.FileInputStream;
import java.io.FileNotFoun## Heading ##dException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
public class FirebaseConnection {
public void initiainzeSDK() {
FileInputStream serviceAccount;
try {
serviceAccount = new FileInputStream("myJson.json");
FirebaseOptions options = new FirebaseOptions.Builder() .setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
.setDatabaseUrl("https://adsnavigator-bc363.firebaseio.com/")
.build();
FirebaseApp.initializeApp(options);
} catch (FileNotFoundException foe) {
System.out.println(foe.getMessage());
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
}
public void authrnticate() {
DatabaseReference ref = FirebaseDatabase
.getInstance()
.getReference("restricted_access/secret_document");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Object document = dataSnapshot.getValue();
System.out.println(document);
}
@Override
public void onCancelled(DatabaseError error) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
}
public void writeTOFb() {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("rec");
System.out.println(ref);
DatabaseReference usersRef = ref.child("abc");
System.out.println(usersRef);
Map<String, Hospital> users = new HashMap<>();
users.put("alanisawesome", new Hospital("abc", "sfsf", 1f));
users.put("gracehop", new Hospital("xyz", "rde", 2f));
System.out.println(users);
usersRef.setValue(users);
}}
`
答案 0 :(得分:0)
您可能忘记将数据库写入规则更改为".write": true
,您可以添加此规则并检查其中的错误。
usersRef.setValue(users, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError != null) {
System.out.println("Data could not be saved " + databaseError.getMessage());
} else {
System.out.println("Data saved successfully.");
}
}
});
答案 1 :(得分:0)
这是因为程序在firebase操作完成之前终止。您可以尝试添加计时器任务或线程以在程序中运行,以便应用程序不会被终止。