com.google.firebase.database.FirebaseDatabase Java Examples

The following examples show how to use com.google.firebase.database.FirebaseDatabase. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: kute   Author: scorelab   File: LoadPersonRoutesAsyncTask.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected ArrayList<Route> doInBackground(String... params) {
    //Return the retrieved list of person's  routes from firebase
    String id=params[0];
    String route_ref="Routes/"+id;
    DatabaseReference routes_ref= FirebaseDatabase.getInstance().getReference(route_ref);
    routes_ref.keepSynced(true);
    routes_ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot routes:dataSnapshot.getChildren()){
                Route temp=routes.getValue(Route.class);
                Log.i(TAG,temp.getName());
                routes_list.add(temp);
            }
            messenger_to_activity.onTaskCompleted(routes_list);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
    return null;
}
 
Example #2
Source Project: quickstart-android   Author: firebase   File: NewPostActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    binding = ActivityNewPostBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());

    // [START initialize_database_ref]
    mDatabase = FirebaseDatabase.getInstance().getReference();
    // [END initialize_database_ref]

    binding.fabSubmitPost.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            submitPost();
        }
    });
}
 
Example #3
Source Project: UberClone   Author: SimCoderYoutube   File: CustomerMapActivity.java    License: MIT License 6 votes vote down vote up
private void getHasRideEnded(){
    driveHasEndedRef = FirebaseDatabase.getInstance().getReference().child("Users").child("Drivers").child(driverFoundID).child("customerRequest").child("customerRideId");
    driveHasEndedRefListener = driveHasEndedRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(dataSnapshot.exists()){

            }else{
                endRide();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
 
Example #4
Source Project: kute   Author: scorelab   File: SelfRouteDetailActivity.java    License: Apache License 2.0 6 votes vote down vote up
private void setupTrip(){
    Calendar c = Calendar.getInstance();
    int mHour = c.get(Calendar.HOUR_OF_DAY);
    int mMinute = c.get(Calendar.MINUTE);
    String time_string=String.format("%d:%d",mHour,mMinute);
    is_progress_dialog_visible=true;
    progress_dialog.show();
    Trip t = new Trip(source_address, destination_address, source_name_string, destination_name_string, source_cords, destination_cords,time_string , true,Integer.parseInt(no_seats.getText().toString()));
    String self_id=getSharedPreferences("user_credentials", 0).getString("Id", null);
    FirebaseDatabase.getInstance().getReference("Trips").child(self_id).setValue(t).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.d(TAG,"Error Adding trip trip "+e.toString());
        }
    });
    String url=getResources().getString(R.string.server_url)+"matchTrip?personId="+self_id+"&Initiator="+"owner";
    Log.d(TAG,"The url is +"+url);
    requestServer(url);
}
 
Example #5
Source Project: FirebaseUI-Android   Author: firebase   File: FirebaseIndexArrayTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    FirebaseDatabase databaseInstance =
            FirebaseDatabase.getInstance(getAppInstance(InstrumentationRegistry.getContext()));
    mRef = databaseInstance.getReference().child("firebasearray");
    mKeyRef = databaseInstance.getReference().child("firebaseindexarray");

    mArray = new FirebaseIndexArray<>(mKeyRef, mRef, new ClassSnapshotParser<>(Integer.class));
    mRef.removeValue();
    mKeyRef.removeValue();

    mListener = runAndWaitUntil(mArray, new Runnable() {
        @Override
        public void run() {
            for (int i = 1; i <= INITIAL_SIZE; i++) {
                TestUtils.pushValue(mKeyRef, mRef, i, i);
            }
        }
    }, new Callable<Boolean>() {
        @Override
        public Boolean call() {
            return mArray.size() == INITIAL_SIZE;
        }
    });
}
 
Example #6
Source Project: MagicPrint-ECommerce-App-Android   Author: singhkshitij   File: IndividualProduct.java    License: MIT License 6 votes vote down vote up
private void initialize() {
    model = (GenericProductModel) getIntent().getSerializableExtra("product");

    productprice.setText("₹ " + Float.toString(model.getCardprice()));

    productname.setText(model.getCardname());
    productdesc.setText(model.getCarddiscription());
    quantityProductPage.setText("1");
    Picasso.with(IndividualProduct.this).load(model.getCardimage()).into(productimage);

    //SharedPreference for Cart Value
    session = new UserSession(getApplicationContext());

    //validating session
    session.isLoggedIn();
    usermobile = session.getUserDetails().get(UserSession.KEY_MOBiLE);
    useremail = session.getUserDetails().get(UserSession.KEY_EMAIL);

    //setting textwatcher for no of items field
    quantityProductPage.addTextChangedListener(productcount);

    //get firebase instance
    //initializing database reference
    mDatabaseReference = FirebaseDatabase.getInstance().getReference();
}
 
Example #7
Source Project: 1Rramp-Android   Author: hapramp   File: FirebaseNotificationStore.java    License: MIT License 6 votes vote down vote up
public static void markAsRead(String notifId) {
  String rootNode = HapRampMain.getFp();
  String username = HaprampPreferenceManager.getInstance().getCurrentSteemUsername();
  if (username.length() > 0) {
    final DatabaseReference notificationRef = FirebaseDatabase.getInstance()
      .getReference()
      .child(rootNode)
      .child(NODE_NOTIFICATIONS)
      .child(getFormattedUserName(username))
      .child(notifId);

    notificationRef.addListenerForSingleValueEvent(new ValueEventListener() {
      @Override
      public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
          notificationRef.child(NODE_IS_READ).setValue(true);
        }
      }

      @Override
      public void onCancelled(@NonNull DatabaseError databaseError) {

      }
    });
  }
}
 
Example #8
Source Project: TinderClone   Author: SimCoderYoutube   File: MainActivity.java    License: MIT License 6 votes vote down vote up
private void isConnectionMatch(String userId) {
    DatabaseReference currentUserConnectionsDb = usersDb.child(currentUId).child("connections").child("yeps").child(userId);
    currentUserConnectionsDb.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
                Toast.makeText(MainActivity.this, "new Connection", Toast.LENGTH_LONG).show();

                String key = FirebaseDatabase.getInstance().getReference().child("Chat").push().getKey();

                usersDb.child(dataSnapshot.getKey()).child("connections").child("matches").child(currentUId).child("ChatId").setValue(key);
                usersDb.child(currentUId).child("connections").child("matches").child(dataSnapshot.getKey()).child("ChatId").setValue(key);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
 
Example #9
Source Project: firebase-android-sdk   Author: firebase   File: Repo.java    License: Apache License 2.0 6 votes vote down vote up
Repo(RepoInfo repoInfo, Context ctx, FirebaseDatabase database) {
  this.repoInfo = repoInfo;
  this.ctx = ctx;
  this.database = database;

  operationLogger = this.ctx.getLogger("RepoOperation");
  transactionLogger = this.ctx.getLogger("Transaction");
  dataLogger = this.ctx.getLogger("DataOperation");

  this.eventRaiser = new EventRaiser(this.ctx);

  // Kick off any expensive additional initialization
  scheduleNow(
      new Runnable() {
        @Override
        public void run() {
          deferredInitialization();
        }
      });
}
 
Example #10
Source Project: chat21-android-sdk   Author: chat21   File: ChatAuthentication.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
private void deleteInstanceId(String userId) {

        DatabaseReference root;
        if (StringUtils.isValid(ChatManager.Configuration.firebaseUrl)) {
            root = FirebaseDatabase.getInstance().getReferenceFromUrl(ChatManager.Configuration.firebaseUrl);
        } else {
            root = FirebaseDatabase.getInstance().getReference();
        }

        String token = FirebaseInstanceId.getInstance().getToken();
        Log.d(DEBUG_LOGIN, "ChatAuthentication.deleteInstanceId: token ==  " + token);

        // remove the instanceId for the logged user
        DatabaseReference firebaseUsersPath = root
                .child("apps/" + ChatManager.Configuration.appId + "/users/" +
                        userId + "/instances/" + token);
        firebaseUsersPath.removeValue();

        try {
            FirebaseInstanceId.getInstance().deleteInstanceId();
        } catch (IOException e) {
            Log.e(DEBUG_LOGIN, "cannot delete instanceId. " + e.getMessage());
            return;
        }
    }
 
Example #11
Source Project: UberClone   Author: IramML   File: TripHistory.java    License: MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_trip_history);
    initToolbar();
    initRecyclerView();

    mAuth = FirebaseAuth.getInstance();
    database = FirebaseDatabase.getInstance();
    riderHistory = database.getReference(Common.history_driver);
    listData = new ArrayList<>();
    adapter = new historyAdapter(this, listData, new ClickListener() {
        @Override
        public void onClick(View view, int index) {

        }
    });
    rvHistory.setAdapter(adapter);
    getHistory();
}
 
Example #12
Source Project: UberClone   Author: IramML   File: DriverHome.java    License: MIT License 6 votes vote down vote up
private void updateFirebaseToken() {
    FirebaseDatabase db=FirebaseDatabase.getInstance();
    final DatabaseReference tokens=db.getReference(Common.token_tbl);

    final Token token=new Token(FirebaseInstanceId.getInstance().getToken());
    if(FirebaseAuth.getInstance().getUid()!=null) tokens.child(FirebaseAuth.getInstance().getUid()).setValue(token);
    else if(account!=null) tokens.child(account.getId()).setValue(token);
    else{
        GraphRequest request = GraphRequest.newMeRequest(
                accessToken,
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) {
                        String id = object.optString("id");
                        tokens.child(id).setValue(token);
                    }
                });
        request.executeAsync();
    }
}
 
Example #13
Source Project: UberClone   Author: IramML   File: DriverHome.java    License: MIT License 6 votes vote down vote up
private void setUpLocation() {
    if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
        ActivityCompat.requestPermissions(this, new String[]{
                android.Manifest.permission.ACCESS_COARSE_LOCATION,
                android.Manifest.permission.ACCESS_FINE_LOCATION
        }, REQUEST_CODE_PERMISSION);
    }else{
        if (checkPlayServices()){
            buildGoogleApiClient();
            if (locationSwitch.isChecked()){
                drivers= FirebaseDatabase.getInstance().getReference(Common.driver_tbl).child(Common.currentUser.getCarType());
                geoFire=new GeoFire(drivers);
                displayLocation();
            }
        }
    }
}
 
Example #14
Source Project: FirebaseUI-Android   Author: firebase   File: FirebaseArrayOfObjectsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    FirebaseApp app = getAppInstance(InstrumentationRegistry.getContext());
    mRef = FirebaseDatabase.getInstance(app)
            .getReference()
            .child("firebasearray")
            .child("objects");
    mArray = new FirebaseArray<>(mRef, new ClassSnapshotParser<>(Bean.class));
    mRef.removeValue();
    mListener = runAndWaitUntil(mArray, new Runnable() {
        @Override
        public void run() {
            for (int i = 1; i <= INITIAL_SIZE; i++) {
                mRef.push().setValue(new Bean(i, "Text " + i, i % 2 == 0), i);
            }
        }
    }, new Callable<Boolean>() {
        @Override
        public Boolean call() {
            return mArray.size() == INITIAL_SIZE;
        }
    });
}
 
Example #15
Source Project: UberClone   Author: IramML   File: TripHistory.java    License: MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_trip_history);
    initToolbar();
    initRecyclerView();

    mAuth = FirebaseAuth.getInstance();
    database = FirebaseDatabase.getInstance();
    riderHistory = database.getReference(Common.history_rider);
    listData = new ArrayList<>();
    adapter = new historyAdapter(this, (ArrayList<History>) listData, new ClickListener() {
        @Override
        public void onClick(View view, int index) {

        }
    });
    rvHistory.setAdapter(adapter);
    getHistory();
}
 
Example #16
Source Project: UberClone   Author: IramML   File: CallDriver.java    License: MIT License 6 votes vote down vote up
private void loadDriverInfo(String driverID) {
    FirebaseDatabase.getInstance().getReference(Common.user_driver_tbl)
            .child(driverID).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            User user=dataSnapshot.getValue(User.class);

            if(user.getAvatarUrl()!=null &&
                    !TextUtils.isEmpty(user.getAvatarUrl()))
                Picasso.get().load(user.getAvatarUrl()).into(imgAvatar);
            tvName.setText(user.getName());
            tvPhone.setText(user.getPhone());
            tvRate.setText(user.getRates());
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}
 
Example #17
Source Project: LuxVilla   Author: brunomassa   File: firebaseutils.java    License: Apache License 2.0 6 votes vote down vote up
public static void updateuserbio(String userbio, final LinearLayout linearLayout){
    FirebaseAuth auth=FirebaseAuth.getInstance();
    FirebaseUser user=auth.getCurrentUser();
    FirebaseDatabase database = FirebaseDatabase.getInstance();

    if (user !=null) {
        DatabaseReference myRef = database.getReference("users").child(user.getUid()).child("user_bio");

        myRef.setValue(userbio).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {

            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Snackbar.make(linearLayout,"Lamentamos mas ocorreu um erro",Snackbar.LENGTH_LONG).show();
            }
        });
    }
}
 
Example #18
Source Project: RestaurantApp   Author: yusufcakal   File: ProductDetailFragment.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_product_detail, container, false);

    android_id = Secure.getString(getActivity().getContentResolver(), Secure.ANDROID_ID);
    FirebaseApp.initializeApp(getActivity());
    firebaseDatabase = FirebaseDatabase.getInstance();
    databaseReference = firebaseDatabase.getReference("basket").child(android_id);

    btnAddBasket = (FlatButton) view.findViewById(R.id.btnAddBasket);
    btnAddBasket.setOnClickListener(this);

    progressDialog = new ProgressDialog(getActivity());
    progressDialog.setMessage("Ürün Yükleniyor..");
    progressDialog.show();

    sliderLayout = (SliderLayout) view.findViewById(R.id.slider);
    tvPrice = (TextView) view.findViewById(R.id.tvPrice);
    etPiece = (EditText) view.findViewById(R.id.etPiece);
    etPiece.addTextChangedListener(this);

    imageList = new ArrayList<>();
    productIdExstra = getArguments().getInt("id");

    url+=productIdExstra;
    Request request = new Request(getActivity(), url, com.android.volley.Request.Method.GET);
    request.requestVolley(this);

    return  view;
}
 
Example #19
Source Project: FaceT   Author: clementf2b   File: PostActivity.java    License: Mozilla Public License 2.0 5 votes vote down vote up
private void initializeActivity() {

        mAuth = FirebaseAuth.getInstance();
        mStorage = FirebaseStorage.getInstance().getReference();
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Product");

        mCurrentUser = mAuth.getCurrentUser();
        mDatabaseUser = FirebaseDatabase.getInstance().getReference().child("Users").child(mCurrentUser.getUid());

        // Vertical Stepper form vars
        int colorPrimary = ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary);
        int colorPrimaryDark = ContextCompat.getColor(getApplicationContext(), R.color.colorPrimaryDark);
        String[] stepsTitles = getResources().getStringArray(R.array.steps_titles);
        //String[] stepsSubtitles = getResources().getStringArray(R.array.steps_subtitles);

        // Here we find and initialize the form
        verticalStepperForm = (VerticalStepperFormLayout) findViewById(R.id.vertical_stepper_form);
        Typeface fontType = FontManager.getTypeface(getApplicationContext(), FontManager.APP_FONT);
        FontManager.markAsIconContainer(findViewById(R.id.vertical_stepper_form), fontType);
        VerticalStepperFormLayout.Builder.newInstance(verticalStepperForm, stepsTitles, this, this)
                //.stepsSubtitles(stepsSubtitles)
                //.materialDesignInDisabledSteps(true) // false by default
                //.showVerticalLineWhenStepsAreCollapsed(true) // false by default
                .primaryColor(colorPrimary)
                .primaryDarkColor(colorPrimaryDark)
                .displayBottomNavigation(true)
                .showVerticalLineWhenStepsAreCollapsed(true)
                .materialDesignInDisabledSteps(true)
                .init();
    }
 
Example #20
Source Project: android-things-electricity-monitor   Author: riggaroo   File: ElectricityMonitorActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_electricity_monitor);

    firebaseDatabase = FirebaseDatabase.getInstance().getReference();
    final String key = firebaseDatabase.child(FIREBASE_LOGS).push().getKey();

    electricityLog = new ElectricityLog();

    final DatabaseReference onlineRef = firebaseDatabase.child(FIREBASE_INFO_CONNECTED);
    final DatabaseReference currentUserRef = firebaseDatabase.child(FIREBASE_ONLINE_ENDPOINT);
    onlineRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(final DataSnapshot dataSnapshot) {
            Log.d(TAG, "DataSnapshot:" + dataSnapshot);
            if (dataSnapshot.getValue(Boolean.class)) {
                electricityLog.setTimestampOn(ServerValue.TIMESTAMP);
                final DatabaseReference currentLogDbRef = firebaseDatabase.child(FIREBASE_LOGS).child(key);
                currentLogDbRef.setValue(electricityLog);

                currentUserRef.setValue(true);
                currentUserRef.onDisconnect().setValue(false);

                electricityLog.setTimestampOff(ServerValue.TIMESTAMP);
                currentLogDbRef.onDisconnect().setValue(electricityLog);

            }
        }

        @Override
        public void onCancelled(final DatabaseError databaseError) {
            Log.d(TAG, "DatabaseError:" + databaseError);
        }
    });
}
 
Example #21
Source Project: Walk-In-Clinic-Android-App   Author: techwithtim   File: Administrator.java    License: MIT License 5 votes vote down vote up
/**
 * Deletes all bookings from clinic
 * @param id patient id
 * @return bool if succesful
 */
public boolean deletePatientBookings(String id){
    updateBookings();
    for(Booking b: bookings){
        if(b.getPatientId().equals(id)){
            DatabaseReference dR = FirebaseDatabase.getInstance().getReference("bookings").child(b.getId());
            dR.removeValue();
        }
    }

    return true;
}
 
Example #22
Source Project: firebase-admin-java   Author: firebase   File: InfoTestIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInfoNodeChildSetValue() {
  DatabaseReference ref = FirebaseDatabase.getInstance().getReference(".info");
  try {
    ref.child("test").setValueAsync("hi");
    fail("Should not be allowed");
  } catch (DatabaseException expected) {
    // No-op, expected
  }
}
 
Example #23
Source Project: snippets-android   Author: firebase   File: QueryActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_query);

    // Get a reference to the Firebase Database
    databaseReference = FirebaseDatabase.getInstance().getReference();
}
 
Example #24
Source Project: firebase-admin-java   Author: firebase   File: InfoTestIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInfoNodeRemoveValue() {
  DatabaseReference ref = FirebaseDatabase.getInstance().getReference(".info");
  try {
    ref.removeValueAsync();
    fail("Should not be allowed");
  } catch (DatabaseException expected) {
    // No-op, expected
  }
}
 
Example #25
Source Project: firebase-admin-java   Author: firebase   File: DataTestIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNamespaceCaseInsensitive()
    throws TestFailure, ExecutionException, TimeoutException, InterruptedException {

  String child = "" + new Random().nextInt(100000000);
  DatabaseReference ref1 = FirebaseDatabase.getInstance(masterApp).getReference(child);

  String url = "https://" + IntegrationTestUtils.getProjectId().toUpperCase() + ".firebaseio.com/"
      + child;
  DatabaseReference ref2 = FirebaseDatabase.getInstance(masterApp).getReferenceFromUrl(url);

  new WriteFuture(ref1, "testdata").timedGet();
  DataSnapshot snap = TestHelpers.getSnap(ref2);
  assertEquals("testdata", snap.getValue());
}
 
Example #26
Source Project: snippets-android   Author: firebase   File: OfflineActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void fullConnectionExample() {
    // [START rtdb_full_connection_example]
    // Since I can connect from multiple devices, we store each connection instance separately
    // any time that connectionsRef's value is null (i.e. has no children) I am offline
    final FirebaseDatabase database = FirebaseDatabase.getInstance();
    final DatabaseReference myConnectionsRef = database.getReference("users/joe/connections");

    // Stores the timestamp of my last disconnect (the last time I was seen online)
    final DatabaseReference lastOnlineRef = database.getReference("/users/joe/lastOnline");

    final DatabaseReference connectedRef = database.getReference(".info/connected");
    connectedRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            boolean connected = snapshot.getValue(Boolean.class);
            if (connected) {
                DatabaseReference con = myConnectionsRef.push();

                // When this device disconnects, remove it
                con.onDisconnect().removeValue();

                // When I disconnect, update the last time I was seen online
                lastOnlineRef.onDisconnect().setValue(ServerValue.TIMESTAMP);

                // Add this device to my connections list
                // this value could contain info about the device or a timestamp too
                con.setValue(Boolean.TRUE);
            }
        }

        @Override
        public void onCancelled(DatabaseError error) {
            Log.w(TAG, "Listener was cancelled at .info/connected");
        }
    });
    // [END rtdb_full_connection_example]
}
 
Example #27
Source Project: quickstart-java   Author: firebase   File: MyEmailer.java    License: Apache License 2.0 5 votes vote down vote up
public static void sendNotificationEmail(String email, String uid, String postId) {
    // TODO(developer): send email to user notifying them that one of their posts got a new star
    System.out.println("sendNotificationEmail: MOCK IMPLEMENTATION");
    System.out.println("sendNotificationEmail: " + email);

    // Save the date of the last notification sent
    // [START write_fan_out]
    Map<String,Object> update = new HashMap<String,Object>();
    update.put("/posts/" + postId + "/lastNotificationTimestamp", ServerValue.TIMESTAMP);
    update.put("/user-posts/" + uid + "/" + postId + "/lastNotificationTimestamp", ServerValue.TIMESTAMP);

    FirebaseDatabase.getInstance().getReference().updateChildren(update);
    // [END write_fan_out]
}
 
Example #28
Source Project: ChatApp   Author: h01d   File: ProfileActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void onPause()
{
    super.onPause();

    FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserId).child("online").setValue(ServerValue.TIMESTAMP);
}
 
Example #29
Source Project: firebase-admin-java   Author: firebase   File: OrderTestIT.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUpClass() throws TestFailure, TimeoutException, InterruptedException {
  masterApp = IntegrationTestUtils.ensureDefaultApp();
  // Make sure we're connected before any of these tests run
  DatabaseReference ref = FirebaseDatabase.getInstance(masterApp).getReference();
  ReadFuture.untilEquals(ref.child(".info/connected"), true).timedGet();
}
 
Example #30
Source Project: firebase-admin-java   Author: firebase   File: InfoTestIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInfoServerTimeOffset()
    throws TestFailure, TimeoutException, InterruptedException {
  DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
  DataSnapshot snap =
      new ReadFuture(ref.child(".info/serverTimeOffset")).timedGet().get(0).getSnapshot();
  assertTrue(snap.getValue() instanceof Long);
}