Java 类com.google.firebase.database.FirebaseDatabase 实例源码

项目:Hyke    文件:HykeLocationManager.java   
@Override
public void onLocationChanged(Location location) {
    FirebaseAuth auth = FirebaseAuth.getInstance();
    String uid = auth.getCurrentUser().getUid();
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users");
    ref.child(uid).child("location").setValue(new Loc(location.getLatitude(), location.getLongitude()));

    SharedPreferences prefs = context.getSharedPreferences("USER_DATA", 0);
    String group_id = prefs.getString("GROUP_ID", "");

    GeoHash geoHash = new GeoHash(location.getLatitude(), location.getLongitude());
    Map<String, Object> updates = new HashMap<String, Object>();
    updates.put("g", geoHash.getGeoHashString());
    updates.put("l", Arrays.asList(location.getLatitude(), location.getLongitude()));

    FirebaseDatabase.getInstance().getReference()
            .child("group_locations")
            .child(group_id)
            .child(uid)
            .setValue(updates);
    EventBus.getDefault().post(location);
}
项目:SVNITChapters    文件:CHRD.java   
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView= inflater.inflate(R.layout.fragment_announcements, container, false);
    recycle=(RecyclerView)rootView.findViewById(R.id.recycle);

    recycle.setLayoutManager(new LinearLayoutManager(getActivity()));

    databaseReference3= FirebaseDatabase.getInstance().getReference().child("CHRD");

    get();


    recycle.setAdapter(firebaseRecyclerAdapter3);
    firebaseRecyclerAdapter3.notifyDataSetChanged();
    databaseReference3.keepSynced(true);
    recycle.invalidate();
    return rootView;
}
项目:drd    文件:Context.java   
/**
 * Vytvoří nový kontext apliakce
 *
 * @param databaseName Název databáze
 */
public Context(String databaseName, ResourceBundle resources) throws FileNotFoundException {
    this.resources = resources;
    this.appDirectory = new File(appDirs
        .getUserDataDir(CREDENTAILS_APP_NAME, CREDENTAILS_APP_VERSION, CREDENTILS_APP_AUTHOR));
    if (!appDirectory.exists()) {
        if (!appDirectory.mkdirs()) {
            logger.error("Nepodařilo se vytvořit složku aplikace, zavírám...");
            Platform.exit();
        }
    }
    logger.info("Používám pracovní adresář: {}", appDirectory.getPath());
    try {
        database = new SQLite(appDirectory.getPath() + SEPARATOR + databaseName);
    } catch (SQLException e) {
        throw new FileNotFoundException();
    }

    initFirebase();
    userManager = new UserManager(FirebaseDatabase.getInstance());
    initManagers();
}
项目:Raffler-Android    文件:AppApplication.java   
@Override
public void onCreate() {
    super.onCreate();

    Realm.init(this);
    RealmConfiguration config = new RealmConfiguration.Builder()
            .deleteRealmIfMigrationNeeded()
            //.schemaVersion(2) // Must be bumped when the schema changes
            //.migration(new RealmContactMigration()) // Migration to run instead of throwing an exception
            .name("default.realm").build();
    Realm.setDefaultConfiguration(config);

    if(database==null) {
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);
        FirebaseDatabase.getInstance().setLogLevel(Logger.Level.DEBUG);
    }

    database = FirebaseDatabase.getInstance();
    References.init(this, database);

    AppManager.getInstance().setContext(getApplicationContext());
    AppManager.getInstance().setCountry(Country.getCountryFromSIM(getApplicationContext()));

    // Initialize image loader
    initImageLoader(this);
}
项目:mobile-app-dev-book    文件:JournalFragment.java   
@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;
}
项目:FantaF1    文件:LoginActivity.java   
private void setContent() {
    setContentView(R.layout.activity_login);
    screen = (RelativeLayout)findViewById(R.id.rl);
    ColorDrawable[] color = {new ColorDrawable(getResources().getColor(R.color.colorAccent)), new ColorDrawable(getResources().getColor(R.color.colorPrimary)) };
    TransitionDrawable trans = new TransitionDrawable(color);
    screen.setBackgroundDrawable(trans);
    trans.startTransition(1800);

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id)).requestEmail().build();
    mGoogleApiClient = new GoogleApiClient.Builder(getBaseContext())
            .enableAutoManage(this, this) .addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();
    mAuth = FirebaseAuth.getInstance();

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    root= database.getReference("room_names");
    loadRooms();
    new CountDownTimer(2500, 1000) {
        public void onTick(long millisUntilDone) { }
        public void onFinish() {
            currentUser = mAuth.getCurrentUser();
            updateUI(currentUser);
        }
    }.start();
}
项目:CSI-KJSCEOfficial    文件:MainActivity.java   
@Override
protected void onResume() {
    super.onResume();

    Query listenNewNotif = FirebaseDatabase
            .getInstance()
            .getReference(getString(R.string.firebase_key_last_notif))
            .child(getString(R.string.firebase_key_notif_id));
    listenNewNotif.keepSynced(true);
    final DatabaseHelper dbHelper = new DatabaseHelper(this);
    listenNewNotif.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            if(dbHelper.getUnreadCount()>0 && notifMenu!=null){
                notifMenu.setIcon(getResources().getDrawable(R.drawable.ic_notification_new));
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.d(TAG,databaseError.getMessage());
        }
    });
}
项目:ReminderPrj    文件:addActivity.java   
public void add(View view) {

        EditText title = (EditText) findViewById(R.id.editTitle);
        EditText description = (EditText) findViewById(R.id.editDescription);
         String titleMessage = title.getText().toString();
        //image64 = String of image
         String descripMessage = description.getText().toString();
        if(titleMessage != null  && imageB64 != null && descripMessage != null ) {
            blogContent chat = new blogContent(titleMessage, imageB64, descripMessage);
            FirebaseDatabase.getInstance().getReference(userUid).push().setValue(chat);
            toMainActivity();
            clearFields();
        }else{
            Toast.makeText(addActivity.this, "Please fill all options", Toast.LENGTH_LONG).show();

        }
    }
项目:CodeWatch    文件:WakatimeDataSyncJob.java   
@SuppressLint("ApplySharedPref")
@Override
public void run() {
    //download all relevant data and sync with firebase
    try {
        FetchWakatimeData fetchWakatimeData = new FetchWakatimeData(getApplicationContext());
        WakatimeDataWrapper wakatimeDataWrapper = fetchWakatimeData.execute();
        Timber.d("Successfully download wakatimeData");
        User user = new TransformUtils(wakatimeDataWrapper, new User()).execute();
        //save to firebase
        Timber.d("Saving to firebase rdb");
        String uid = CacheUtils.getFirebaseUserId(getApplicationContext());
        if (uid != null) {
            FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
            DatabaseReference databaseReference = firebaseDatabase.getReference().child("users");
            databaseReference.child(uid).setValue(user);
        }
    } catch (Exception e) {
        Timber.e(e, "LeaderboardSyncTask failed");
        needsReschedule = true;
    }
    countDownLatch.countDown();
}
项目:firebase-admin-java    文件:FirebaseDatabaseAuthTestIT.java   
@Test
public void testDatabaseAuthVariablesNoAuthorization() throws InterruptedException {
  FirebaseOptions options =
      new FirebaseOptions.Builder(masterApp.getOptions())
          .setDatabaseAuthVariableOverride(null)
          .build();
  FirebaseApp testUidApp =
      FirebaseApp.initializeApp(options, "testServiceAccountDatabaseWithNoAuth");

  FirebaseDatabase masterDb = FirebaseDatabase.getInstance(masterApp);
  FirebaseDatabase testAuthOverridesDb = FirebaseDatabase.getInstance(testUidApp);

  assertWriteSucceeds(masterDb.getReference());

  assertWriteFails(testAuthOverridesDb.getReference("test-uid-only"));
  assertReadFails(testAuthOverridesDb.getReference("test-uid-only"));
  assertWriteFails(testAuthOverridesDb.getReference("test-custom-field-only"));
  assertReadFails(testAuthOverridesDb.getReference("test-custom-field-only"));
  assertWriteSucceeds(testAuthOverridesDb.getReference("test-noauth-only"));    
}
项目:SVNITChapters    文件:GDG.java   
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView= inflater.inflate(R.layout.fragment_announcements, container, false);
    recycle=(RecyclerView)rootView.findViewById(R.id.recycle);

    recycle.setLayoutManager(new LinearLayoutManager(getActivity()));

    databaseReference3= FirebaseDatabase.getInstance().getReference().child("GDG");
    get();
    image2=(ImageView)rootView.findViewById(R.id.image2);



    recycle.setAdapter(firebaseRecyclerAdapter3);
    firebaseRecyclerAdapter3.notifyDataSetChanged();
    databaseReference3.keepSynced(true);
    recycle.invalidate();
    return rootView;
}
项目:firebase-admin-java    文件:DataTestIT.java   
@Test
public void testNameAndRefForSnapshots()
    throws TestFailure, ExecutionException, TimeoutException, InterruptedException {

  DatabaseReference ref = FirebaseDatabase.getInstance(masterApp).getReference();
  // Clear any data there
  new WriteFuture(ref, MapBuilder.of("foo", 10)).timedGet();

  DataSnapshot snap = TestHelpers.getSnap(ref);
  assertNull(snap.getKey());
  assertEquals(ref.toString(), snap.getRef().toString());
  DataSnapshot childSnap = snap.child("a");
  assertEquals("a", childSnap.getKey());
  assertEquals(ref.child("a").toString(), childSnap.getRef().toString());
  childSnap = childSnap.child("b/c");
  assertEquals("c", childSnap.getKey());
  assertEquals(ref.child("a/b/c").toString(), childSnap.getRef().toString());
}
项目:event-me    文件:ParticipantsAdapter.java   
@Override
public void onBindViewHolder(final ParticipantsViewHolder holder, int position) {
    String emailKey = participantEmails.get(position);
    final String userstat = String.valueOf(participantstatus.get(position));
    Log.d("userEmail", emailKey);
    FirebaseDatabase.getInstance().getReference().child(Constants.users).child(emailKey).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            User user = dataSnapshot.getValue(User.class);
            holder.nameView.setText(user.getDisplayName());
            holder.emailView.setText(user.getEmail()+"\n"+userstat);
            Glide.with(context).load(user.getDpUrl()).into(holder.imageView);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
项目:Viajes    文件:AddActivity.java   
private void addItem(HashMap<String, String> images, final Hotel item) {
    DatabaseReference itemsRef = FirebaseDatabase.getInstance().getReferenceFromUrl(Constants.FIREBASE_URL_ITEMS);
    itemsRef.keepSynced(true);
    item.setImagesUrls(images);
    itemsRef = itemsRef.push().getRef();

    itemsRef.setValue(item, new DatabaseReference.CompletionListener() {
        @Override
        public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
            mUploadProgressDialog.dismiss();
            if (databaseError == null) {
                Toast.makeText(AddActivity.this, "Item uploaded Successfully.", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(AddActivity.this, MainActivity.class)
                        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
            } else {
                Toast.makeText(AddActivity.this, "unable to add.", Toast.LENGTH_SHORT).show();

            }
        }
    });
}
项目:chapp-messenger    文件:Contacts.java   
public void GetYourRegistredOnes ( Map<String,String> deineKontakte, Map<String, String> alleDownloads, String uid ) {
    back = new HashMap<String, Object>();       // kontaktnamen werden als boolean ausgelesen
    Set<String> s = new LinkedHashSet<String>(alleDownloads.keySet());        // key - nummer, value - uid
    Set<String> sss = new LinkedHashSet<String>(alleDownloads.values());        // key - nummer, value - uid
    Set<String> ss = new LinkedHashSet<String>(deineKontakte.values());       // key - name, value - nummer
    ss.retainAll(s);
    for (int i = 0; i < ss.size(); i++) {
        String x = ss.toArray()[i].toString();      // geht alle elemente durch, holt bei position i
        String y = "";
        for (int j = 0; j < s.size(); j++) {
            if (s.toArray()[j].toString().equals(x)) {
                y = sss.toArray()[j].toString();
                break;
            }
        }
        back.put(x, y );
    }
    DatabaseReference dbr = FirebaseDatabase.getInstance().getReference().getRoot();
    dbr.child("users").child(uid).child("contacts").setValue(back);
}
项目:Instincts-2k17    文件:ProfileActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);
    ButterKnife.bind(this);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    VCard vCard = new VCard();
    vCard.setName(firebaseUser.getUid());
    qrImageView.setImageBitmap(QRCode.from(vCard.buildString()).bitmap());

    databaseReference = FirebaseDatabase.getInstance().getReference();
    currentUser = FirebaseAuth.getInstance().getCurrentUser();
    sharedPreferences = getSharedPreferences("user", MODE_PRIVATE);

    try {
        populateProfile();
    } catch (Exception e) {
        LogHelper.e(TAG, e.toString());
    }
}
项目:instagram_clone    文件:AccountActivity.java   
private void createUserProfile(String name, String uid, String email) {
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference();
    User user = new User(uid, name, email);
    myRef.child("users").child(uid).setValue(user);

    FirebaseUser currentUser = mAuth.getCurrentUser();
    UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
            .setDisplayName(name).build();
    currentUser.updateProfile(profileUpdates)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                   @Override
                   public void onComplete(@NonNull Task<Void> task) {
                       if(task.isSuccessful()) {
                           Log.d(TAG, "User display_name added");
                       }
                   }
               }
            );
}
项目:FeedFire    文件:MainActivity.java   
private void addLike(final Feed feed){
    flagLike = true;
    final DatabaseReference referenceLike = FirebaseDatabase.getInstance().getReference().child(LIKE_ROOT);
    final FirebaseUser auth = FirebaseAuth.getInstance().getCurrentUser();
    referenceLike.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (flagLike){
                if (dataSnapshot.child( feed.getIdFeed() ).hasChild( auth.getUid())){
                    referenceLike.child(feed.getIdFeed()).child(auth.getUid()).removeValue();
                    flagLike = false;
                }else{
                    referenceLike.child(feed.getIdFeed()).child(auth.getUid()).setValue(true);
                    flagLike = false;
                }
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}
项目:iSPY    文件:TrackerService.java   
/**
 * Loads previously stored statuses from Firebase, and once retrieved,
 * start location tracking.
 */
private void loadPreviousStatuses() {
    String transportId = mPrefs.getString(getString(R.string.transport_id), "");
    FirebaseAnalytics.getInstance(this).setUserProperty("transportID", transportId);
    String path = getString(R.string.firebase_path) + transportId;
    mFirebaseTransportRef = FirebaseDatabase.getInstance().getReference(path);
    mFirebaseTransportRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            if (snapshot != null) {
                for (DataSnapshot transportStatus : snapshot.getChildren()) {
                    mTransportStatuses.add(Integer.parseInt(transportStatus.getKey()),
                            (Map<String, Object>) transportStatus.getValue());
                }
            }
            startLocationTracking();
        }

        @Override
        public void onCancelled(DatabaseError error) {
            // TODO: Handle gracefully
        }
    });
}
项目:SmartHome    文件:Door.java   
public Door(int id){
    state = State.LOCKED;
    this.id = id;

    database = FirebaseDatabase.getInstance();

    doorRef = database.getReference("doors/"+id);
    doorRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            state = (((String) dataSnapshot.getValue()).equals("LOCKED") ? Door.State.LOCKED : Door.State.UNLOCKED);
            setChanged();
            notifyObservers();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.e("dberror", "db error in light.java: ");
            state = Door.State.LOCKED;
            doorRef.setValue(state);
            setChanged();
            notifyObservers();
        }
    });
}
项目:SVNITChapters    文件:Announcements.java   
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
   View rootView= inflater.inflate(R.layout.fragment_announcements, container, false);
    recycle=(RecyclerView)rootView.findViewById(R.id.recycle);

    recycle.setLayoutManager(new LinearLayoutManager(getActivity()));
    firebaseAuth3=FirebaseAuth.getInstance();
    databaseReference3= FirebaseDatabase.getInstance().getReference().child("Announcements");


    get();

    recycle.setAdapter(firebaseRecyclerAdapter3);
    firebaseRecyclerAdapter3.notifyDataSetChanged();
    databaseReference3.keepSynced(true);
    recycle.invalidate();
    return rootView;
}
项目:furry-sniffle    文件:BookmarkActivity.java   
public EntertainmentSpotAdapterViewHolder(View itemView) {
    super(itemView);
    mView = itemView;
    mBookmarkButton = mView.findViewById(R.id.bookmarkButton);
    mLikeButton = mView.findViewById(R.id.likeButton);
    mEntertainmentOwner = mView.findViewById(R.id.ownerTextView); //
    mEntertainmentLikes = mView.findViewById(R.id.likeCounterTextView);
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    mFirebaseAuth = FirebaseAuth.getInstance();
    mLikesDatabaseReference = mFirebaseDatabase.getReference().child("Likes");
    mBookmarksDatabaseReference = mFirebaseDatabase.getReference().child("Bookmarks");
    mLikesDatabaseReference.keepSynced(true);
}
项目:vc    文件:Operation_TypeService.java   
Operation_typeService() {
    try {
        this.test = new FireBase_DataBase();
         FirebaseDatabase database = FirebaseDatabase.getInstance();
         ref = database.getReference("");
         Operation_typeRef = ref.child("Operation_type");
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Operation_typeService.class.getName()).log(Level.SEVERE, null, ex);
    }
}
项目:Howl    文件:ChatActivity.java   
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();
}
项目:mobile-app-dev-book    文件:JournalViewActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_journal_view);
    ButterKnife.bind(this);
    setSupportActionBar(toolbar);
    entries.setLayoutManager(new LinearLayoutManager(this));
    Retrofit retro = new Retrofit.Builder()
            .baseUrl("https://api.darksky.net/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    darkSkyClient = retro.create(DarkSkyServices.class);
    Intent incoming = getIntent();
    if (incoming.hasExtra("TRIP")) {
        Parcelable par = incoming.getParcelableExtra("TRIP");
        Trip t = Parcels.unwrap(par);
        tripKey = t.getKey();
        title.setText(t.getName());
        FirebaseDatabase dbRef = FirebaseDatabase.getInstance();
        FirebaseAuth auth = FirebaseAuth.getInstance();
        FirebaseUser user = auth.getCurrentUser();
        entriesRef = dbRef.getReference(user.getUid())
                .child(tripKey + "/entries").orderByChild("date");
        storage = FirebaseStorage.getInstance();
        adapter = new MyAdapter();
        entries.setAdapter(adapter);
        entries.addItemDecoration(verticalGap);
    }
}
项目:Howl    文件:LoginInteractor.java   
private void updateFirebaseToken(String uid, String token) {
    FirebaseDatabase.getInstance()
            .getReference()
            .child(Constants.ARG_USERS)
            .child(uid)
            .child(Constants.ARG_FIREBASE_TOKEN)
            .setValue(token);
}
项目:vc    文件:PersonService.java   
PersonService() {
    try {
        this.test = new FireBase_DataBase();
         FirebaseDatabase database = FirebaseDatabase.getInstance();
         ref = database.getReference("");
         PersonRef = ref.child("Person");
    } catch (FileNotFoundException ex) {
        Logger.getLogger(PersonService.class.getName()).log(Level.SEVERE, null, ex);
    }
}
项目:Howl    文件:ChatInteractor.java   
@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());
        }
    });
}
项目:chapp-messenger    文件:FirebaseAndroidApp.java   
@Override
public void onCreate() {
    super.onCreate();

    if(!FirebaseApp.getApps(this).isEmpty())
    {
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);
    }

}
项目:cat-is-a-dog    文件:HabitEventDataSourceForHabit.java   
@Override
public void open() {
    mHabitEventArray.clear();
    habitEventQuery = FirebaseDatabase.getInstance().getReference("events/" + userId)
            .orderByChild("habitKey").equalTo(habitKey);

    habitEventQuery.addValueEventListener(this);
}
项目:RestaurantApp    文件:ProductDetailFragment.java   
@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;
}
项目:mobile-app-dev-book    文件:JournalEditActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_journal_edit);
    ButterKnife.bind(this);
    Intent incoming = getIntent();
    imgLoader = new FirebaseImageLoader();
    FirebaseStorage storage = FirebaseStorage.getInstance();
    if (incoming.hasExtra("JRNL_ENTRY")) {
        Parcelable parcel = incoming.getParcelableExtra("JRNL_ENTRY");
        entry = Parcels.unwrap(parcel);
        String url = null;
        if (entry.getType() == 2) {
            url = entry.getUrl();
            fabCover.setVisibility(View.VISIBLE);
        }
        else if (entry.getType() == 3) {
            fabCover.setVisibility(View.GONE);
            imageView.setImageResource(R.drawable.transparent_box);
        }
        else if (entry.getType() == 4) {
            url = entry.getThumbnailUrl();
            fabCover.setVisibility(View.GONE);
        }
        if (url != null) {
            Glide.with(this)
                    .using(imgLoader)
                    .load(storage.getReferenceFromUrl(url))
                    .into(this.imageView);
        }
        caption.setText(entry.getCaption());
        dateTime.setText(entry.getDate());
    }
    if (incoming.hasExtra("DB_REF")) {
        String ref = incoming.getStringExtra("DB_REF");
        parentRef = FirebaseDatabase.getInstance().getReferenceFromUrl(ref);
        String entryKey = incoming.getStringExtra("JRNL_KEY");
        myRef = parentRef.child("entries").child(entryKey);
    }
}
项目:vc    文件:EntrepotService.java   
EntrepotService() {
    try {
        this.test = new FireBase_DataBase();
         FirebaseDatabase database = FirebaseDatabase.getInstance();
         ref = database.getReference("");
         EntrepotRef = ref.child("Entrepot");
    } catch (FileNotFoundException ex) {
        Logger.getLogger(EntrepotService.class.getName()).log(Level.SEVERE, null, ex);
    }
}
项目:firebase-admin-java    文件:InfoTestIT.java   
@Test
public void testGetReferenceToInfoNodes() {
  DatabaseReference root = FirebaseDatabase.getInstance().getReference();
  String dbUrl = FirebaseApp.getInstance().getOptions().getDatabaseUrl();
  assertEquals(dbUrl + "/.info", root.child(".info").toString());
  assertEquals(dbUrl + "/.info/foo", root.child(".info/foo").toString());
}
项目:vc    文件:Operation_StateService.java   
Operation_StateService() {
    try {
        this.test = new FireBase_DataBase();
         FirebaseDatabase database = FirebaseDatabase.getInstance();
         ref = database.getReference("");
         Operation_StateRef = ref.child("Operation_State");
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Operation_StateService.class.getName()).log(Level.SEVERE, null, ex);
    }
}
项目:firebase-admin-java    文件:InfoTestIT.java   
@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);
}
项目:TaipeiTechRefined    文件:FeedbackFragment.java   
private void writeDataBase(String message){
    // Write a message to the database
    FirebaseApp.initializeApp(getActivity());
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    Calendar mCal = Calendar.getInstance();
    CharSequence s = DateFormat.format("yyyy-MM-dd kk:mm:ss", mCal.getTime());
    DatabaseReference myRef = database.getReference((String) s);
    myRef.setValue(message);
}
项目:foodie    文件:Chats.java   
public void addUser(final String buyerUId, final String sellerUId){

        FirebaseDatabase.getInstance().getReference().child("UserList").child(buyerUId).orderByChild("name").equalTo(sellerUId).addListenerForSingleValueEvent(new ValueEventListener() {
            boolean addingUser = false;
            HashMap<String,String> map1 = new HashMap<String, String>();
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                //Toast.makeText(getActivity(),"dataSnapshots exists",Toast.LENGTH_LONG).show();
                HashMap<String,Object> map = (HashMap<String, Object>) dataSnapshot.getValue();

                DatabaseReference node;
                if (dataSnapshot.exists()) {
                    return;
                }

                node = FirebaseDatabase.getInstance().getReference().child("UserList").child(buyerUId).push();
                //map1.put("key",node.getKey());
                map1.put("name", sellerUId);
                node.setValue(map1);
                //FirebaseDatabase.getInstance().getReference().child("UserList").child(buyerUId).setValue(map1);
                //}
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }
项目:firebase-admin-java    文件:RulesTestIT.java   
@Test
public void testStillAuthenticatedAfterReconnect()
    throws InterruptedException, ExecutionException, TestFailure, TimeoutException {
  DatabaseConfig config = TestHelpers.getDatabaseConfig(masterApp);
  DatabaseReference root = FirebaseDatabase.getInstance(masterApp).getReference();
  DatabaseReference ref = root.child(writer.getPath().toString());
  RepoManager.interrupt(config);
  RepoManager.resume(config);
  DatabaseError err = new WriteFuture(ref.child("any_auth"), true).timedGet();
  assertNull(err);
}
项目:CodeWatch    文件:DashboardFragment.java   
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.fragment_dashboard, container, false);
    ButterKnife.bind(this, rootView);
    Icepick.restoreInstanceState(this, savedInstanceState);

    context = getActivity();
    setContext(context);
    setChartColors(chartColors);

    if (savedInstanceState == null) {
        firebaseUid = CacheUtils.getFirebaseUserId(context);
    }
    FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
    statsDatabaseRef = firebaseDatabase.getReference().child("users").child(firebaseUid).child("stats");
    projectsDatabaseRef = firebaseDatabase.getReference().child("users").child(firebaseUid).child("timeSpentOnProjects");

    setUpActivityChart();
    setListeners();
    swipeRefreshLayout.setRefreshing(true);

    AdRequest adRequest = new AdRequest.Builder().build();
    adView.loadAd(adRequest);

    if (scrollPosition != null && scrollView != null) {
        scrollView.post(new Runnable() {
            @Override
            public void run() {
                scrollView.scrollTo(0, scrollPosition);
            }
        });
    }
    return rootView;
}