本文整理汇总了Java中com.google.firebase.database.DatabaseReference.addValueEventListener方法的典型用法代码示例。如果您正苦于以下问题:Java DatabaseReference.addValueEventListener方法的具体用法?Java DatabaseReference.addValueEventListener怎么用?Java DatabaseReference.addValueEventListener使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.google.firebase.database.DatabaseReference
的用法示例。
在下文中一共展示了DatabaseReference.addValueEventListener方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: onCreateView
import com.google.firebase.database.DatabaseReference; //导入方法依赖的package包/类
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_journal_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
FirebaseDatabase dbRef = FirebaseDatabase.getInstance();
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
DatabaseReference userRef = dbRef.getReference(user.getUid());
userRef.addChildEventListener (chEvListener);
userRef.addValueEventListener(valEvListener);
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
adapter = new JournalAdapter(allTrips, mListener);
recyclerView.setAdapter(adapter);
}
return view;
}
示例2: testUnregisterSameCallbackTooManyTimes
import com.google.firebase.database.DatabaseReference; //导入方法依赖的package包/类
@Test
public void testUnregisterSameCallbackTooManyTimes()
throws InterruptedException {
DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ;
ValueEventListener listener =
ref.addValueEventListener(
new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
// no-op
}
@Override
public void onCancelled(DatabaseError error) {
// no-op
}
});
ZombieVerifier.verifyRepoZombies(ref);
ref.removeEventListener(listener);
ref.removeEventListener(listener);
ZombieVerifier.verifyRepoZombies(ref);
}
示例3: testUpdateAfterSetLeafNodeWorks
import com.google.firebase.database.DatabaseReference; //导入方法依赖的package包/类
@Test
public void testUpdateAfterSetLeafNodeWorks() throws InterruptedException {
DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);
final Semaphore semaphore = new Semaphore(0);
final Map<String, Object> expected = new MapBuilder().put("a", 1L).put("b", 2L).build();
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if (DeepEquals.deepEquals(snapshot.getValue(), expected)) {
semaphore.release();
}
}
@Override
public void onCancelled(DatabaseError error) {
}
});
ref.setValueAsync(42);
ref.updateChildrenAsync(expected);
TestHelpers.waitFor(semaphore);
}
示例4: getProfile
import com.google.firebase.database.DatabaseReference; //导入方法依赖的package包/类
public ValueEventListener getProfile(String id, final OnObjectChangedListener<Profile> listener) {
DatabaseReference databaseReference = getDatabaseReference().child("profiles").child(id);
ValueEventListener valueEventListener = databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Profile profile = dataSnapshot.getValue(Profile.class);
listener.onObjectChanged(profile);
}
@Override
public void onCancelled(DatabaseError databaseError) {
LogUtil.logError(TAG, "getProfile(), onCancelled", new Exception(databaseError.getMessage()));
}
});
activeListeners.put(valueEventListener, databaseReference);
return valueEventListener;
}
示例5: readValues
import com.google.firebase.database.DatabaseReference; //导入方法依赖的package包/类
public void readValues(){
DatabaseReference dbRef = fbDatabase.getReference(sample);
dbRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data: dataSnapshot.getChildren()){
SampleModel model = data.getValue(SampleModel.class);
Log.v("FIREBASE", model.getName());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.v("FIREBASE", databaseError.getMessage());
}
});
}
示例6: retrieveData
import com.google.firebase.database.DatabaseReference; //导入方法依赖的package包/类
/**
* Retrieve Data from Firebase
*/
private void retrieveData(){
showProgress(true);
mList = new ArrayList<>();
DatabaseReference feedReference = FirebaseDatabase.getInstance().getReference().child(FEED_ROOT).orderByChild("time").getRef();
feedReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
mList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Feed feed = snapshot.getValue( Feed.class );
mList.add(feed);
}
initRecyclerView(mList);
showProgress(false);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
示例7: getCommentsList
import com.google.firebase.database.DatabaseReference; //导入方法依赖的package包/类
public ValueEventListener getCommentsList(String postId, final OnDataChangedListener<Comment> onDataChangedListener) {
DatabaseReference databaseReference = database.getReference("post-comments").child(postId);
ValueEventListener valueEventListener = databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<Comment> list = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Comment comment = snapshot.getValue(Comment.class);
list.add(comment);
}
Collections.sort(list, new Comparator<Comment>() {
@Override
public int compare(Comment lhs, Comment rhs) {
return ((Long) rhs.getCreatedDate()).compareTo((Long) lhs.getCreatedDate());
}
});
onDataChangedListener.onListChanged(list);
}
@Override
public void onCancelled(DatabaseError databaseError) {
LogUtil.logError(TAG, "getCommentsList(), onCancelled", new Exception(databaseError.getMessage()));
}
});
activeListeners.put(valueEventListener, databaseReference);
return valueEventListener;
}
示例8: initDataBase
import com.google.firebase.database.DatabaseReference; //导入方法依赖的package包/类
private void initDataBase( final ScannerDao scannerDao ) {
Log.i("scan.log", "Initing read database fire-base" );
this.database = FirebaseDatabase.getInstance();
final DatabaseReference scannerConfig = this.database.getReference("app").child("scanner");
scannerConfig.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange( DataSnapshot dataSnapshot ) {
Log.i("scan.log", "O result Database Fire Base" );
Map<String, Object > data = ( Map< String, Object > ) dataSnapshot.getValue();
JsonMapper mapper = new JsonMapper( data );
String type = mapper.string( "type");
String group = mapper.string( "client", "group" );
String name = mapper.string( "client", "name" );
String server = mapper.string( "server", "host" );
int port = mapper.integer( "server", "port" );
SocketConfiguration newConficuration = new SocketConfiguration( type, server, port, group, name );
SocketConfiguration curentConfiguration = scannerDao.loadConfiguration();
if( curentConfiguration == null || ! curentConfiguration.equals( newConficuration ) ) {
Log.i("scan.log", "On new confiuration loaded" );
scannerDao.updateConfiguration( newConficuration );
for( FireBaseCallBack fireBaseCallBack: fireBaseCallBacks ){
fireBaseCallBack.onNewConfiguration( newConficuration );
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
}
示例9: testNodeWithDefaultListener
import com.google.firebase.database.DatabaseReference; //导入方法依赖的package包/类
@Test
public void testNodeWithDefaultListener()
throws TestFailure, ExecutionException, TimeoutException, InterruptedException {
DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);
new WriteFuture(ref, new MapBuilder().put("a", 1).put("b", 2).put("c", 3).put("d", 4)
.put("e", 5).put("f", 6).build()).timedGet();
final AtomicInteger onCalled = new AtomicInteger(0);
final Semaphore semaphore = new Semaphore(0);
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
// Should only be called once
if (onCalled.incrementAndGet() == 1) {
semaphore.release(1);
}
}
@Override
public void onCancelled(DatabaseError error) {
}
});
TestHelpers.waitFor(semaphore);
assertEquals(1, onCalled.get());
DataSnapshot snap = TestHelpers.getSnap(ref.limitToLast(1));
TestHelpers.assertDeepEquals(MapBuilder.of("f", 6L), snap.getValue());
}
示例10: testNodeWithDefaultListenerAndNonCompleteLimit
import com.google.firebase.database.DatabaseReference; //导入方法依赖的package包/类
@Test
public void testNodeWithDefaultListenerAndNonCompleteLimit()
throws TestFailure, ExecutionException, TimeoutException, InterruptedException {
DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);
new WriteFuture(ref, MapBuilder.of("a", 1, "b", 2, "c", 3)).timedGet();
final AtomicInteger onCalled = new AtomicInteger(0);
final Semaphore semaphore = new Semaphore(0);
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
// Should only be called once
if (onCalled.incrementAndGet() == 1) {
semaphore.release(1);
}
}
@Override
public void onCancelled(DatabaseError error) {
}
});
TestHelpers.waitFor(semaphore);
assertEquals(1, onCalled.get());
DataSnapshot snap = TestHelpers.getSnap(ref.limitToLast(5));
TestHelpers.assertDeepEquals(MapBuilder.of("a", 1L, "b", 2L, "c", 3L), snap.getValue());
}
示例11: changeLikeImg
import com.google.firebase.database.DatabaseReference; //导入方法依赖的package包/类
public void changeLikeImg(final String feedKey){
final DatabaseReference referenceLike = FirebaseDatabase.getInstance().getReference().child(MainActivity.LIKE_ROOT);
final FirebaseUser auth = FirebaseAuth.getInstance().getCurrentUser();
referenceLike.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
long totalLike = 0;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
if (snapshot.getKey().equals(feedKey)) {
totalLike = snapshot.getChildrenCount();
break;
}
}
if (dataSnapshot.child(feedKey).hasChild(auth.getUid())){
// ta curtido
ivLike.setImageResource( R.drawable.ic_thumb_up_blue_24dp );
}else{
// nao ta curtido
ivLike.setImageResource( R.drawable.ic_thumb_up_grey600_24dp );
}
tvLike.setText(totalLike+" likes");
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
示例12: getPost
import com.google.firebase.database.DatabaseReference; //导入方法依赖的package包/类
public ValueEventListener getPost(final String id, final OnPostChangedListener listener) {
DatabaseReference databaseReference = getDatabaseReference().child("posts").child(id);
ValueEventListener valueEventListener = databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
if (isPostValid((Map<String, Object>) dataSnapshot.getValue())) {
Post post = dataSnapshot.getValue(Post.class);
if (post != null) {
post.setId(id);
}
listener.onObjectChanged(post);
} else {
listener.onError(String.format(context.getString(R.string.error_general_post), id));
}
} else {
listener.onObjectChanged(null);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
LogUtil.logError(TAG, "getPost(), onCancelled", new Exception(databaseError.getMessage()));
}
});
activeListeners.put(valueEventListener, databaseReference);
return valueEventListener;
}
示例13: getUserInfo
import com.google.firebase.database.DatabaseReference; //导入方法依赖的package包/类
private void getUserInfo(final View view, DatabaseReference userRef){
userRef.addValueEventListener(new ValueEventListener() {
TextView mNameField=(TextView) view.findViewById(R.id.name);
TextView mPhoneField=(TextView) view.findViewById(R.id.phone);
TextView mAddressField=(TextView) view.findViewById(R.id.address);
TextView mEmailField=(TextView) view.findViewById(R.id.email);
TextView mBioField=(TextView) view.findViewById(R.id.bio);
private ImageView mProfileImage = (ImageView) view.findViewById(R.id.profileImage);
//private String userID;
private String mName;
private String mPhone;
private String mAddress;
private String mBio;
private String mEmail;
private String mProfileImageUrl;
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
if(map.get("name") != null){
mName= map.get("name").toString();
mNameField.setText(mName);
}
if(map.get("phone") != null){
mPhone= map.get("phone").toString();
mPhoneField.setText(mPhone);
}
if(map.get("address") != null){
mAddress= map.get("address").toString();
mAddressField.setText(mAddress);
}
if(map.get("email") != null){
mEmail= map.get("email").toString();
mEmailField.setText(mEmail);
}
if(map.get("bio") != null){
mBio= map.get("bio").toString();
mBioField.setText(mBio);
}
if(map.get("profileImageUrl")!= null){
mProfileImageUrl = map.get("profileImageUrl").toString();
Picasso.with(getActivity()).load(mProfileImageUrl)
.error(R.drawable.common_google_signin_btn_icon_dark)
.into(mProfileImage);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
示例14: testRegisterTheSameCallbackMultipleTimes
import com.google.firebase.database.DatabaseReference; //导入方法依赖的package包/类
@Test
public void testRegisterTheSameCallbackMultipleTimes()
throws TestFailure, ExecutionException, TimeoutException, InterruptedException {
DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ;
final AtomicInteger callbackCount = new AtomicInteger(0);
ValueEventListener listener =
new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.getValue() != null) {
callbackCount.incrementAndGet();
}
}
@Override
public void onCancelled(DatabaseError error) {
fail("Should not be cancelled");
}
};
ref.addValueEventListener(listener);
ref.addValueEventListener(listener);
ref.addValueEventListener(listener);
ZombieVerifier.verifyRepoZombies(ref);
new WriteFuture(ref, 42).timedGet();
assertEquals(3, callbackCount.get());
ref.removeEventListener(listener);
new WriteFuture(ref, 84).timedGet();
assertEquals(5, callbackCount.get());
ZombieVerifier.verifyRepoZombies(ref);
ref.removeEventListener(listener);
new WriteFuture(ref, 168).timedGet();
assertEquals(6, callbackCount.get());
ZombieVerifier.verifyRepoZombies(ref);
ref.removeEventListener(listener);
new WriteFuture(ref, 376).timedGet();
assertEquals(6, callbackCount.get());
ZombieVerifier.verifyRepoZombies(ref);
}
示例15: writeNewChanga
import com.google.firebase.database.DatabaseReference; //导入方法依赖的package包/类
private void writeNewChanga() {
AutoCompleteTextView add_title = (AutoCompleteTextView) findViewById(R.id.add_changa_title);
final String title = add_title.getText().toString();
EditText add_description = (EditText) findViewById(R.id.add_changa_description);
final String description = add_description.getText().toString();
EditText add_cost = (EditText) findViewById(R.id.add_changa_costo);
final String price = add_cost.getText().toString();
/*
FirebaseStorage storage = FirebaseStorage.getInstance();
// Create a storage reference from our app
StorageReference storageRef = storage.getReference();
Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
StorageReference riversRef = storageRef.child("images/"+file.getLastPathSegment());
UploadTask uploadTask = riversRef.putFile(file);
// Register observers to listen for when the download is done or if it fails
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Uri downloadUrl = taskSnapshot.getDownloadUrl();
System.out.println("DOWNLOAD;"+downloadUrl);
}
});
ImageButton add_image = (ImageButton)findViewById(R.id.img_changa);
Bitmap image = ((BitmapDrawable)add_image.getDrawable()).getBitmap();
*/
final String key = mDatabase.child("Changas").push().getKey();
final String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
//final UserModel currentUser = (new UserModel()).getUserById(userId);
DatabaseReference database = FirebaseDatabase.getInstance().getReference("users").child(userId);
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserModel userM = dataSnapshot.getValue(UserModel.class);
Changa changa = new Changa(key, userId, userM.name, title, description, price, "", "", mAddCategory.getSelectedItemPosition(), "activa");
Map<String, Object> changaValues = changa.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/changas/" + key, changaValues);
//childUpdates.put("/user-posts/" + userId + "/" + key, postValues);
mDatabase.updateChildren(childUpdates);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
System.out.println("!!!!!!!! Failed to read user:"+ error.toException());
}
};
database.addValueEventListener(eventListener);
}