當前位置: 首頁>>代碼示例>>Java>>正文


Java DatabaseReference.addValueEventListener方法代碼示例

本文整理匯總了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;
}
 
開發者ID:gvsucis,項目名稱:mobile-app-dev-book,代碼行數:26,代碼來源:JournalFragment.java

示例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);
}
 
開發者ID:firebase,項目名稱:firebase-admin-java,代碼行數:26,代碼來源:EventTestIT.java

示例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);
}
 
開發者ID:firebase,項目名稱:firebase-admin-java,代碼行數:24,代碼來源:DataTestIT.java

示例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;
}
 
開發者ID:rozdoum,項目名稱:social-app-android,代碼行數:18,代碼來源:DatabaseHelper.java

示例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());
        }
    });
}
 
開發者ID:marckregio,項目名稱:maklib,代碼行數:18,代碼來源:FirebaseDatabaseActivity.java

示例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) {

        }
    });
}
 
開發者ID:AleBarreto,項目名稱:FeedFire,代碼行數:26,代碼來源:MainActivity.java

示例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;
}
 
開發者ID:rozdoum,項目名稱:social-app-android,代碼行數:32,代碼來源:DatabaseHelper.java

示例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) {}
    });
}
 
開發者ID:tec-ustp,項目名稱:SIIEScanner,代碼行數:34,代碼來源:FirebaseScanner.java

示例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());
}
 
開發者ID:firebase,項目名稱:firebase-admin-java,代碼行數:31,代碼來源:QueryTestIT.java

示例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());
}
 
開發者ID:firebase,項目名稱:firebase-admin-java,代碼行數:30,代碼來源:QueryTestIT.java

示例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) {

        }
    });
}
 
開發者ID:AleBarreto,項目名稱:FeedFire,代碼行數:31,代碼來源:AdapterListFeed.java

示例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;
}
 
開發者ID:rozdoum,項目名稱:social-app-android,代碼行數:30,代碼來源:DatabaseHelper.java

示例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) {

        }
    });
}
 
開發者ID:thandomy,項目名稱:foodie,代碼行數:65,代碼來源:profileTab.java

示例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);
}
 
開發者ID:firebase,項目名稱:firebase-admin-java,代碼行數:45,代碼來源:EventTestIT.java

示例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);


}
 
開發者ID:sloiza,項目名稱:changApp,代碼行數:68,代碼來源:AddChanga.java


注:本文中的com.google.firebase.database.DatabaseReference.addValueEventListener方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。