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 File: FirebaseNotificationStore.java    From 1Rramp-Android with 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 #2
Source File: ChatAuthentication.java    From chat21-android-sdk with 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 #3
Source File: FirebaseIndexArrayTest.java    From FirebaseUI-Android with 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 #4
Source File: TripHistory.java    From UberClone with 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 #5
Source File: Repo.java    From firebase-android-sdk with 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 #6
Source File: DriverHome.java    From UberClone with 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 #7
Source File: SelfRouteDetailActivity.java    From kute with 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 #8
Source File: CustomerMapActivity.java    From UberClone with 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 #9
Source File: DriverHome.java    From UberClone with 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 #10
Source File: FirebaseArrayOfObjectsTest.java    From FirebaseUI-Android with 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 #11
Source File: TripHistory.java    From UberClone with 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 #12
Source File: MainActivity.java    From TinderClone with 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 #13
Source File: IndividualProduct.java    From MagicPrint-ECommerce-App-Android with 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 #14
Source File: NewPostActivity.java    From quickstart-android with 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 #15
Source File: CallDriver.java    From UberClone with 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 #16
Source File: firebaseutils.java    From LuxVilla with 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 #17
Source File: LoadPersonRoutesAsyncTask.java    From kute with 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 #18
Source File: Utility.java    From stockita-point-of-sale with MIT License 5 votes vote down vote up
/**
 * Create new user profile into Firebase location users
 *
 * @param userName  The user name
 * @param userUID   The user UID from Firebase Auth
 * @param userEmail The user encoded email
 */
public static void createUser(Context context, String userName, String userUID, String userEmail, String userPhoto) {

    // Encoded the email that the user just signed in with
    String encodedUserEmail = Utility.encodeEmail(userEmail);

    // This is the Firebase server value time stamp HashMap
    HashMap<String, Object> timestampCreated = new HashMap<>();

    // Pack the ServerValue.TIMESTAMP into a HashMap
    timestampCreated.put(Constants.FIREBASE_PROPERTY_TIMESTAMP, ServerValue.TIMESTAMP);

    /**
     * Pass those data into java object
     */
    UserModel userModel = new UserModel(userName, userUID, userEmail, userPhoto, timestampCreated);

    /**
     * Initialize the DatabaseReference
     */
    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();

    /**
     * Get reference into the users location
     */
    DatabaseReference usersLocation = databaseReference.child(Constants.FIREBASE_USER_LOCATION);


    /**
     * Add the user object into the users location in Firebase database
     */
    usersLocation.child(userUID).setValue(userModel);

}
 
Example #19
Source File: DoorbellActivity.java    From doorbell with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "Doorbell Activity created.");

    // We need permission to access the camera
    if (checkSelfPermission(Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {
        // A problem occurred auto-granting the permission
        Log.e(TAG, "No permission");
        return;
    }

    mDatabase = FirebaseDatabase.getInstance();
    mStorage = FirebaseStorage.getInstance();

    // Creates new handlers and associated threads for camera and networking operations.
    mCameraThread = new HandlerThread("CameraBackground");
    mCameraThread.start();
    mCameraHandler = new Handler(mCameraThread.getLooper());

    mCloudThread = new HandlerThread("CloudThread");
    mCloudThread.start();
    mCloudHandler = new Handler(mCloudThread.getLooper());

    // Initialize the doorbell button driver
    initPIO();

    // Camera code is complicated, so we've shoved it all in this closet class for you.
    mCamera = DoorbellCamera.getInstance();
    mCamera.initializeCamera(this, mCameraHandler, mOnImageAvailableListener);
}
 
Example #20
Source File: ChatActivity.java    From FirebaseMessagingApp with GNU General Public License v3.0 5 votes vote down vote up
private void init() {
    // set the toolbar
    setSupportActionBar(mToolbar);

    // set toolbar title
    mToolbar.setTitle(getIntent().getExtras().getString(Constants.ARG_RECEIVER));



  //
    FirebaseDatabase.getInstance().getReference().child("users")
            .child(getIntent().getExtras().get(Constants.ARG_RECEIVER_UID).toString())
            .child("status").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            try{
            mToolbar.setSubtitle(dataSnapshot.getValue().toString());}catch (Exception e){
            //no status
        }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });





    // set the register screen fragment
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.frame_layout_content_chat,
            ChatFragment.newInstance(getIntent().getExtras().getString(Constants.ARG_RECEIVER),
                    getIntent().getExtras().getString(Constants.ARG_RECEIVER_UID),
                    getIntent().getExtras().getString(Constants.ARG_FIREBASE_TOKEN)),
            ChatFragment.class.getSimpleName());
    fragmentTransaction.commit();
}
 
Example #21
Source File: ChatInteractor.java    From FirebaseMessagingApp with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void sendMessageToFirebaseUser(final Context context, final Chat chat, final String receiverFirebaseToken) {
    final String room_type_1 = chat.senderUid + "_" + chat.receiverUid;
    final String room_type_2 = chat.receiverUid + "_" + chat.senderUid;

    final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();

    databaseReference.child(Constants.ARG_CHAT_ROOMS).getRef().addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.hasChild(room_type_1)) {
                Log.e(TAG, "sendMessageToFirebaseUser: " + room_type_1 + " exists");
                databaseReference.child(Constants.ARG_CHAT_ROOMS).child(room_type_1).child(String.valueOf(chat.timestamp)).setValue(chat);
            } else if (dataSnapshot.hasChild(room_type_2)) {
                Log.e(TAG, "sendMessageToFirebaseUser: " + room_type_2 + " exists");
                databaseReference.child(Constants.ARG_CHAT_ROOMS).child(room_type_2).child(String.valueOf(chat.timestamp)).setValue(chat);
            } else {
                Log.e(TAG, "sendMessageToFirebaseUser: success");
                databaseReference.child(Constants.ARG_CHAT_ROOMS).child(room_type_1).child(String.valueOf(chat.timestamp)).setValue(chat);
                getMessageFromFirebaseUser(chat.senderUid, chat.receiverUid);
            }
            // send push notification to the receiver
            sendPushNotificationToReceiver(chat.sender,
                    chat.message,
                    chat.senderUid,
                    new SharedPrefUtil(context).getString(Constants.ARG_FIREBASE_TOKEN),
                    receiverFirebaseToken);
            mOnSendMessageListener.onSendMessageSuccess();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            mOnSendMessageListener.onSendMessageFailure("Unable to send message: " + databaseError.getMessage());
        }
    });
}
 
Example #22
Source File: SignInUI.java    From stockita-point-of-sale with MIT License 5 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {

        case RC_SIGN_IN:

            if (resultCode == RESULT_OK) {
                // user is signed in!

                /**
                 * Get a reference for the current signed in user, and get the
                 * email and the UID
                 */
                FirebaseUser userProfile = FirebaseAuth.getInstance().getCurrentUser();

                if (userProfile != null) {


                    // Get the photo Url
                    Uri photoUri = userProfile.getPhotoUrl();
                    final String photoUrl = photoUri != null ? photoUri.getPath() : null;

                    // Get the user name and store them in SharedPreferences for later use.
                    final String profileName = userProfile.getDisplayName();

                    // Get the user email and store them in SharedPreferences for later use.
                    final String profileEmail = userProfile.getEmail();

                    // Get the user UID and sore them in SharedPreferences for later use.
                    final String profileUid = userProfile.getUid();

                    // Encoded the email that the user just signed in with
                    String encodedUserEmail = Utility.encodeEmail(profileEmail);

                    // Register the current sign in data in SharedPreferences for later use
                    Utility.registerTheCurrentLogin(getBaseContext(), profileName, profileUid, encodedUserEmail, photoUrl);

                    // Initialize the Firebase reference to the /users/<userUid> location
                    final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference()
                            .child(Constants.FIREBASE_USER_LOCATION)
                            .child(profileUid);

                    // Listener for a single value event, only one time this listener will be triggered
                    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                            // Check if hasChildren means already exists
                            if (!dataSnapshot.hasChildren()) {

                                /**
                                 * Create this new user into /users/ node in Firebase
                                 */
                                Utility.createUser(getBaseContext(), profileName, profileUid, profileEmail, photoUrl);
                            }

                        }

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

                            // Get the message in to the logcat
                            Log.e("check if users exist", databaseError.getMessage());
                        }
                    });
                }

                // When signed in then start the main activity
                startActivity(new Intent(this, MainActivity.class));
                finish();

            } else {
                // user is not signed in. Maybe just wait for the user to press
                // "sign in" again, or show a message
                Log.e(TAG_LOG, "not failed to sign in");
            }
    }
}
 
Example #23
Source File: DriverHome.java    From UberClone with MIT License 5 votes vote down vote up
private void loadDriverInformation(){
    FirebaseDatabase.getInstance().getReference(Common.user_driver_tbl)
            .child(Common.userID)
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    Common.currentUser = dataSnapshot.getValue(User.class);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
}
 
Example #24
Source File: firebaseutils.java    From LuxVilla with Apache License 2.0 5 votes vote down vote up
public static void setlike(String id){
    String uid="";
    FirebaseAuth auth=FirebaseAuth.getInstance();
    FirebaseUser user=auth.getCurrentUser();
    if (user != null){
        uid=user.getUid();
    }
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference("users").child(uid).child("likes");
    myRef.child("heart"+id).child("liked").setValue("true");
}
 
Example #25
Source File: MyFirebaseInstanceIDService.java    From firebase-chat with MIT License 5 votes vote down vote up
/**
 * Persist token to third-party servers.
 * <p>
 * Modify this method to associate the user's FCM InstanceID token with any server-side account
 * maintained by your application.
 *
 * @param token The new token.
 */
private void sendRegistrationToServer(final String token) {
    new SharedPrefUtil(getApplicationContext()).saveString(Constants.ARG_FIREBASE_TOKEN, token);

    if (FirebaseAuth.getInstance().getCurrentUser() != null) {
        FirebaseDatabase.getInstance()
                .getReference()
                .child(Constants.ARG_USERS)
                .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                .child(Constants.ARG_FIREBASE_TOKEN)
                .setValue(token);
    }
}
 
Example #26
Source File: Context.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
public ConnectionContext getConnectionContext() {
  return new ConnectionContext(
      wrapAuthTokenProvider(this.getAuthTokenProvider()),
      this.getExecutorService(),
      this.isPersistenceEnabled(),
      FirebaseDatabase.getSdkVersion(),
      this.getUserAgent(),
      ImplFirebaseTrampolines.getThreadFactory(firebaseApp));
}
 
Example #27
Source File: DatabaseTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void setValueShouldTriggerListenerWithNewlySetData() throws Exception {
  FirebaseAuth auth = FirebaseAuth.getInstance();
  FirebaseDatabase database = FirebaseDatabase.getInstance();

  auth.signOut();
  Task<?> signInTask = auth.signInWithEmailAndPassword("[email protected]", "password");
  Tasks2.waitForSuccess(signInTask);

  DatabaseReference doc = database.getReference("restaurants").child(TestId.create());
  SnapshotListener listener = new SnapshotListener();
  doc.addListenerForSingleValueEvent(listener);

  HashMap<String, Object> data = new HashMap<>();
  data.put("location", "Google NYC");

  try {
    Task<?> setTask = doc.setValue(new HashMap<>(data));
    Task<DataSnapshot> snapshotTask = listener.toTask();
    Tasks2.waitForSuccess(setTask);
    Tasks2.waitForSuccess(snapshotTask);

    DataSnapshot result = snapshotTask.getResult();
    assertThat(result.getValue()).isEqualTo(data);
  } finally {
    Tasks2.waitBestEffort(doc.removeValue());
  }
}
 
Example #28
Source File: DatabaseTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void updateChildrenShouldTriggerListenerWithUpdatedData() throws Exception {
  FirebaseAuth auth = FirebaseAuth.getInstance();
  FirebaseDatabase database = FirebaseDatabase.getInstance();

  auth.signOut();
  Task<?> signInTask = auth.signInWithEmailAndPassword("[email protected]", "password");
  Tasks2.waitForSuccess(signInTask);

  DatabaseReference doc = database.getReference("restaurants").child(TestId.create());
  HashMap<String, Object> originalData = new HashMap<>();
  originalData.put("location", "Google NYC");

  try {
    Task<?> setTask = doc.setValue(new HashMap<>(originalData));
    Tasks2.waitForSuccess(setTask);
    SnapshotListener listener = new SnapshotListener();
    doc.addListenerForSingleValueEvent(listener);

    HashMap<String, Object> updateData = new HashMap<>();
    updateData.put("count", 412L);

    Task<?> updateTask = doc.updateChildren(new HashMap<>(updateData));
    Task<DataSnapshot> snapshotTask = listener.toTask();
    Tasks2.waitForSuccess(updateTask);
    Tasks2.waitForSuccess(snapshotTask);

    DataSnapshot result = snapshotTask.getResult();
    HashMap<String, Object> finalData = new HashMap<>();
    finalData.put("location", "Google NYC");
    finalData.put("count", 412L);
    assertThat(result.getValue()).isEqualTo(finalData);
  } finally {
    Tasks2.waitBestEffort(doc.removeValue());
  }
}
 
Example #29
Source File: MainActivity.java    From CourierApplication with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void onPause() {
    super.onPause();
    if(FirebaseDatabase.getInstance()!=null)
    {
        FirebaseDatabase.getInstance().goOffline();
    }
}
 
Example #30
Source File: ChatActivity.java    From TinderClone with MIT License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chat);

    matchId = getIntent().getExtras().getString("matchId");

    currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();

    mDatabaseUser = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID).child("connections").child("matches").child(matchId).child("ChatId");
    mDatabaseChat = FirebaseDatabase.getInstance().getReference().child("Chat");

    getChatId();

    mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    mRecyclerView.setNestedScrollingEnabled(false);
    mRecyclerView.setHasFixedSize(false);
    mChatLayoutManager = new LinearLayoutManager(ChatActivity.this);
    mRecyclerView.setLayoutManager(mChatLayoutManager);
    mChatAdapter = new ChatAdapter(getDataSetChat(), ChatActivity.this);
    mRecyclerView.setAdapter(mChatAdapter);

    mSendEditText = findViewById(R.id.message);
    mSendButton = findViewById(R.id.send);

    mSendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            sendMessage();
        }
    });
}