Java Code Examples for com.google.firebase.database.FirebaseDatabase#getReference()

The following examples show how to use com.google.firebase.database.FirebaseDatabase#getReference() . 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 File: firebaseMessaging.java    From UberClone with MIT License 6 votes vote down vote up
@Override
public void onNewToken(@NonNull String s) {
    super.onNewToken(s);
    FirebaseDatabase db=FirebaseDatabase.getInstance();
    DatabaseReference tokens=db.getReference(Common.token_tbl);

    Token token=new Token(s);
    if (FirebaseAuth.getInstance().getCurrentUser()!=null)tokens.child(FirebaseAuth.getInstance().getUid())
            .setValue(token);
}
 
Example 2
Source File: PopularFragment.java    From YTPlayer with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    show();
    if (writeData!=null) {
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference reference = database.getReference(ref);
        reference.child("timeString").setValue(YTutils.getTodayDate_nogaps());
        reference.child("data").setValue(writeData);
        Toast.makeText(activity, "Updated server list!", Toast.LENGTH_SHORT).show();
    }
    if (models.size()>0) {
        mOplayfab.setOnClickListener(view -> {
            String[] yturls = new String[models.size()];
            MusicService.nPlayModels.clear();
            for (int i=0;i<models.size();i++) {
                MetaModel metaModel = new MetaModel(
                        YTutils.getVideoID(models.get(i).getYtUrl()),
                        models.get(i).getTitle(),
                        models.get(i).getAuthor(),
                        models.get(i).getImgUrl()
                );
                NPlayModel model = new NPlayModel(models.get(i).getYtUrl(),new YTMeta(metaModel),false);

                MusicService.nPlayModels.add(model);
                yturls[i] = models.get(i).getYtUrl();
            }
            MainActivity.PlayVideo(yturls);
        });
        adapter = new SongAdapter(models,activity);
        mRecyclerview.setAdapter(adapter);
    }else
        Toast.makeText(activity, "Unable to retrieve data!", Toast.LENGTH_SHORT).show();
    Log.e(TAG, "onPostExecute: Process ended" );
}
 
Example 3
Source File: AttendeesFragment.java    From white-label-event-app with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LOGGER.fine("onCreate");

    final Bundle args = getArguments();
    title = args.getString(ARG_TITLE);

    final FirebaseDatabase fdb = FirebaseDatabase.getInstance();
    attendeesRef = fdb.getReference("/sections/attendees");
}
 
Example 4
Source File: CompanyDetailFragment.java    From white-label-event-app with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LOGGER.fine("onCreate");

    final Bundle args = getArguments();
    final String companyId = args.getString(ARG_COMPANY_ID);
    if (Strings.isNullOrEmpty(companyId)) {
        throw new IllegalArgumentException(ARG_COMPANY_ID + " can't be null or empty");
    }

    final FirebaseDatabase fdb = FirebaseDatabase.getInstance();
    companyRef = fdb.getReference("/sections/companies/items/" + companyId);
}
 
Example 5
Source File: firebaseMessagning.java    From UberClone with MIT License 5 votes vote down vote up
@Override
public void onNewToken(@NonNull String s) {
    super.onNewToken(s);
    FirebaseDatabase db=FirebaseDatabase.getInstance();
    DatabaseReference tokens=db.getReference(Common.token_tbl);

    Token token=new Token(s);
    if (FirebaseAuth.getInstance().getCurrentUser()!=null)tokens.child(FirebaseAuth.getInstance().getUid())
            .setValue(token);
}
 
Example 6
Source File: verifyPatient2.java    From Doctorave with MIT License 5 votes vote down vote up
private  void putInformationInFb(final Context context) {

        // TODO: Send messages on click
        FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
        final DatabaseReference mDatabaseReference = mFirebaseDatabase.getReference();
        Query hekkQuery = mDatabaseReference;

        hekkQuery.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                boolean alreadyHas = false;
                for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
                    if (snapshot.getKey().equals(phone)){
                        alreadyHas = true;
                        saveUserInSP(context);
                    }
                }
                if(!alreadyHas){
                    mDatabaseReference.child(phone).setValue("").addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            saveUserInSP(context);
                        }
                    })
                            .addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception e) {

                                }
                            });
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });

    }
 
Example 7
Source File: MapsFragment.java    From white-label-event-app with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LOGGER.fine("onCreate");

    final Bundle args = getArguments();
    title = args.getString(ARG_TITLE);

    final FirebaseDatabase fdb = FirebaseDatabase.getInstance();
    mapsRef = fdb.getReference("/sections/maps");
}
 
Example 8
Source File: FirebaseDatabaseTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetValue() throws InterruptedException, ExecutionException, TimeoutException,
    TestFailure {
  FirebaseDatabase db = FirebaseDatabase.getInstance(masterApp);
  DatabaseReference ref = db.getReference("testSetValue");
  ref.setValueAsync("foo").get(TestUtils.TEST_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
  ReadFuture readFuture = ReadFuture.untilEquals(ref, "foo");
  readFuture.timedWait();
}
 
Example 9
Source File: AttendeeDetailFragment.java    From white-label-event-app with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LOGGER.fine("onCreate");

    final Bundle args = getArguments();
    final String attendeeId = args.getString(ARG_ATTENDEE_ID);
    if (Strings.isNullOrEmpty(attendeeId)) {
        throw new IllegalArgumentException(ARG_ATTENDEE_ID + " can't be null or empty");
    }

    final FirebaseDatabase fdb = FirebaseDatabase.getInstance();
    eventRef = fdb.getReference("/event");
    attendeeRef = fdb.getReference("/sections/attendees/items/" + attendeeId);
}
 
Example 10
Source File: OfflineActivity.java    From snippets-android with 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 11
Source File: MainActivity.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void basicReadWrite() {
    // [START write_message]
    // Write a message to the database
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference("message");

    myRef.setValue("Hello, World!");
    // [END write_message]

    // [START read_message]
    // Read from the database
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // This method is called once with the initial value and again
            // whenever data at this location is updated.
            String value = dataSnapshot.getValue(String.class);
            Log.d(TAG, "Value is: " + value);
        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.w(TAG, "Failed to read value.", error.toException());
        }
    });
    // [END read_message]
}
 
Example 12
Source File: AppClass.java    From intra42 with Apache License 2.0 5 votes vote down vote up
void initFirebase() {
    try {
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        firebaseRefClusterMapContribute = database.getReference("cluster_map");
    } catch (IllegalStateException | NullPointerException e) {
        e.printStackTrace();
        FirebaseCrashlytics.getInstance().recordException(e);
    }
}
 
Example 13
Source File: BaseActivity.java    From stockita-point-of-sale with MIT License 5 votes vote down vote up
/**
 * This helper method is to check and listen for the user connection, and also
 * log time stamp when the user disconnect.
 */
private void presenceFunction() {

    // Initialize the .info/connected
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    mUserPresenceRef = database.getReference(".info/connected");

    // Get an instance reference to the location of the user's /usersLog/<uid>/lastOnline
    final DatabaseReference lastOnlineRef = database.getReference()
            .child(Constants.FIREBASE_USER_LOG_LOCATION)
            .child(mUserUid)
            .child(Constants.FIREBASE_PROPERTY_LAST_ONLINE);


    // Initialize the listeners
    mUserPresenceListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            // Get the boolean value of the connection status
            boolean connected = dataSnapshot.getValue(Boolean.class);

            if (connected) {

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

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            // Nothing
        }
    };

    // Add the listeners instance to the database database instance
    mUserPresenceRef.addValueEventListener(mUserPresenceListener);

}
 
Example 14
Source File: ShutdownExample.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
  final Semaphore shutdownLatch = new Semaphore(0);

  FirebaseApp app =
      FirebaseApp.initializeApp(
          InstrumentationRegistry.getInstrumentation().getTargetContext(),
          new FirebaseOptions.Builder()
              .setDatabaseUrl("http://gsoltis.fblocal.com:9000")
              .build());

  FirebaseDatabase db = FirebaseDatabase.getInstance(app);
  db.setLogLevel(Level.DEBUG);
  DatabaseReference ref = db.getReference();

  ValueEventListener listener =
      ref.child("shutdown")
          .addValueEventListener(
              new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot snapshot) {
                  Boolean shouldShutdown = snapshot.getValue(Boolean.class);
                  if (shouldShutdown != null && shouldShutdown) {
                    System.out.println("Should shut down");
                    shutdownLatch.release(1);
                  } else {
                    System.out.println("Not shutting down: " + shouldShutdown);
                  }
                }

                @Override
                public void onCancelled(DatabaseError error) {
                  System.err.println("Shouldn't happen");
                }
              });

  try {
    // Keeps us running until we receive the notification to shut down
    shutdownLatch.acquire(1);
    ref.child("shutdown").removeEventListener(listener);
    db.goOffline();
    System.out.println("Done, should exit");
  } catch (InterruptedException e) {
    throw new RuntimeException(e);
  }
}
 
Example 15
Source File: FirebaseProgressBar.java    From TwrpBuilder with GNU General Public License v3.0 4 votes vote down vote up
private void start(final ProgressBar progressBar, @NonNull final TextView textView, @NonNull FirebaseRecyclerAdapter adapter, @NonNull final String refId, final boolean filter, @NonNull String from, String equalto) {
    FirebaseDatabase mFirebaseInstance = FirebaseDatabase.getInstance();


    progressBar.setVisibility(View.VISIBLE);
    Query query;
    if (filter) {
        query = mFirebaseInstance.getReference(refId).orderByChild(from).equalTo(equalto);
    } else {
        query = mFirebaseInstance.getReference(refId);
    }
    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            progressBar.setVisibility(View.GONE);
            if (!dataSnapshot.exists()) {

                if (filter) {
                    textView.setText(R.string.no_builds_found);
                } else {
                    switch (refId) {
                        case "RunningBuild":
                            textView.setText(R.string.no_running_builds);
                            break;
                        case "Builds":
                            textView.setText(R.string.no_builds_found);
                            break;
                        case "Rejected":
                            textView.setText(R.string.no_rejected);
                            break;
                    }
                }
                textView.setVisibility(View.VISIBLE);
            } else {
                textView.setVisibility(View.GONE);
            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError firebaseError) {
            progressBar.setVisibility(View.GONE);

        }
    });
    adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
            progressBar.setVisibility(View.GONE);
        }
    });


}
 
Example 16
Source File: RepoDatabase.java    From TvAppRepo with Apache License 2.0 4 votes vote down vote up
public static void getLeanbackShortcut(String packageName, final LeanbackShortcutCallback callback) {
    final FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference reference = database.getReference("leanbackShortcuts");
    DatabaseReference shortcutReference = reference.child(packageName.replaceAll("[.]", "_"));
    if (DEBUG) {
        Log.d(TAG, "Looking at shortcut reference " + shortcutReference.toString());
        Log.d(TAG, "Looking for package " + packageName);
    }

    shortcutReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (DEBUG) {
                Log.d(TAG, "Got value back " + dataSnapshot.toString());
            }
            try {
                LeanbackShortcut leanbackShortcut =
                        dataSnapshot.getValue(LeanbackShortcut.class);
                if (leanbackShortcut == null) {
                    if (DEBUG) {
                        Log.i(TAG, "No leanback shortcut");
                    }
                    callback.onNoLeanbackShortcut();
                    return;
                }
                if (DEBUG) {
                    Log.i(TAG, "This is a leanback shortcut");
                }
                callback.onLeanbackShortcut(leanbackShortcut);
            } catch (Exception e) {
                if (DEBUG) {
                    Log.i(TAG, "No leanback shortcut");
                    Log.e(TAG, e.getMessage());
                }
                callback.onNoLeanbackShortcut();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            if (DEBUG) {
                Log.e(TAG, databaseError.toString());
            }
            callback.onDatabaseError(databaseError);
        }
    });
}
 
Example 17
Source File: RepoDatabase.java    From TvAppRepo with Apache License 2.0 4 votes vote down vote up
public static RepoDatabase getInstance(String type) {
    if (apps == null) {
        apps = new HashMap<>();
    }
    // Read from the database
    if (mRepoDatabase == null) {
        mRepoDatabase = new RepoDatabase();
        final FirebaseDatabase database = FirebaseDatabase.getInstance();
        databaseReference = database.getReference(type);
        Log.d(TAG, "Create new instance of RepoDatabase");
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // This method is called once with the initial value and again
                // whenever data at this location is updated.
                Log.d(TAG, "Got new snapshot " + dataSnapshot.toString());
                for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                    try {
                        Log.d(TAG, dataSnapshot1.toString());
                        Apk value = dataSnapshot1.getValue(Apk.class);
                        value.setKey(dataSnapshot1.getKey());
                        Log.d(TAG, "Value is: " + value);
                        if (apps.containsKey(value.getPackageName()) &&
                                apps.get(value.getPackageName()).getVersionCode() < value.getVersionCode() ||
                                !apps.containsKey(value.getPackageName())) {
                            for (Listener listener : listenerList) {
                                listener.onApkAdded(value, apps.size());
                            }
                            apps.put(value.getPackageName(), value);
                        }
                    } catch (RuntimeException e) {
                        // Something weird happened. Debug it.
                        throw new FirebaseIsBeingWeirdException("Something weird happens to Firebase here: " +
                                dataSnapshot1.toString() + " in " + dataSnapshot.toString());
                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.w(TAG, "Failed to read value.", error.toException());
            }
        });
    }
    return mRepoDatabase;
}
 
Example 18
Source File: ShutdownExample.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
  final Semaphore shutdownLatch = new Semaphore(0);

  FirebaseApp app =
      FirebaseApp.initializeApp(
          new FirebaseOptions.Builder()
              .setDatabaseUrl("https://admin-java-sdk.firebaseio.com")
              .build());

  FirebaseDatabase db = FirebaseDatabase.getInstance(app);
  DatabaseReference ref = db.getReference();

  ValueEventListener listener =
      ref.child("shutdown")
          .addValueEventListener(
              new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot snapshot) {
                  Boolean shouldShutdown = snapshot.getValue(Boolean.class);
                  if (shouldShutdown != null && shouldShutdown) {
                    System.out.println("Should shut down");
                    shutdownLatch.release(1);
                  } else {
                    System.out.println("Not shutting down: " + shouldShutdown);
                  }
                }

                @Override
                public void onCancelled(DatabaseError error) {
                  System.err.println("Shouldn't happen");
                }
              });

  try {
    // Keeps us running until we receive the notification to shut down
    shutdownLatch.acquire(1);
    ref.child("shutdown").removeEventListener(listener);
    db.goOffline();
    System.out.println("Done, should exit");
  } catch (InterruptedException e) {
    throw new RuntimeException(e);
  }
}
 
Example 19
Source File: FirebaseDataManager.java    From Android-MVP-vs-MVVM-Samples with Apache License 2.0 3 votes vote down vote up
public FirebaseDataManager() {
    super();
    final FirebaseDatabase database = FirebaseDatabase.getInstance();
    database.setLogLevel(BuildConfig.DEBUG ? Logger.Level.DEBUG : Logger.Level.NONE);
    database.setPersistenceEnabled(false);

    mDatabase = database.getReference();

    mDatabaseCheckIn = mDatabase.child(TABLE_CHECK_IN);


}
 
Example 20
Source File: ViewReports.java    From Crimson with Apache License 2.0 3 votes vote down vote up
private void getReports() {

        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference reportsReference = database.getReference("reports");

        allReports = new ArrayList<>();

        reportsReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {

                AllReports reports;

                for (DataSnapshot postSnapshot: snapshot.getChildren()) {

                     String value = String.valueOf(postSnapshot.getValue());
                     reports = new AllReports();

                     reports.setUrl(value);
                     allReports.add(reports);

                }

                showImages(allReports);


            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.e("The read failed: " ,databaseError.getMessage());
            }
        });

    }