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

The following examples show how to use com.google.firebase.database.FirebaseDatabase#getInstance() . 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: FirebaseSaveObject.java    From Examples with MIT License 6 votes vote down vote up
/**
 * initialize firebase.
 */
private void initFirebase() {
    try {
        // .setDatabaseUrl("https://fir-66f50.firebaseio.com") - Firebase project url.
        // .setServiceAccount(new FileInputStream(new File("filepath"))) - Firebase private key file path.
        FirebaseOptions firebaseOptions = new FirebaseOptions.Builder()
                .setDatabaseUrl("https://fir-66f50.firebaseio.com")
                .setServiceAccount(new FileInputStream(new File("C:\\Users\\Vicky\\Documents\\NetBeansProjects\\Examples\\src\\com\\javaquery\\google\\firebase\\Firebase-30f95674f4d5.json")))
                .build();

        FirebaseApp.initializeApp(firebaseOptions);
        firebaseDatabase = FirebaseDatabase.getInstance();
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    }
}
 
Example 2
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 3
Source File: Home.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 4
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 5
Source File: DriverTracking.java    From UberClone with MIT License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_driver_tracking);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    if(getIntent()!=null){
        riderLat=getIntent().getDoubleExtra("lat",-1.0);
        riderLng=getIntent().getDoubleExtra("lng",-1.0);
        riderID = getIntent().getStringExtra("riderID");
        riderToken=getIntent().getStringExtra("token");
    }
    database = FirebaseDatabase.getInstance();
    historyDriver = database.getReference(Common.history_driver).child(Common.userID);
    historyRider = database.getReference(Common.history_rider).child(riderID);
    riderInformation=database.getReference(Common.user_rider_tbl);
    tokens=database.getReference(Common.token_tbl);
    drivers= FirebaseDatabase.getInstance().getReference(Common.driver_tbl).child(Common.currentUser.getCarType());
    geoFire=new GeoFire(drivers);
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    verifyGoogleAccount();


    mService = Common.getGoogleAPI();
    mFCMService=Common.getFCMService();
    location=new Location(this, new locationListener() {
        @Override
        public void locationResponse(LocationResult response) {
            // refresh current location
            Common.currentLat=response.getLastLocation().getLatitude();
            Common.currentLng=response.getLastLocation().getLongitude();
            displayLocation();

        }
    });
    btnStartTrip=(Button)findViewById(R.id.btnStartTrip);
    btnStartTrip.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(btnStartTrip.getText().equals("START TRIP")){
                pickupLocation=new LatLng(Common.currentLat, Common.currentLng);
                btnStartTrip.setText("DROP OFF HERE");
            }else if(btnStartTrip.getText().equals("DROP OFF HERE")){
                calculateCashFree(pickupLocation, new LatLng(Common.currentLat, Common.currentLng));
            }
        }
    });
    getRiderData();
}
 
Example 6
Source File: DetailPrıductFragment.java    From RestaurantApp with 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_detail_product, container, false);

    android_id = Settings.Secure.getString(getActivity().getContentResolver(), Settings.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();
    progressDialog.hide();

    //OnSuucese kaydet

    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");

    urlDetail+=productIdExstra;

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

    return view;
}
 
Example 7
Source File: AppUpdateChecker.java    From 1Rramp-Android with MIT License 5 votes vote down vote up
public static void checkAppUpdatesNode(final Context context, final AppUpdateAvailableListener appUpdateAvailableListener) {
  String rootNode = HapRampMain.getFp();
  FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
  firebaseDatabase.getReference()
    .child(rootNode)
    .child("app_updates")
    .child("latest_version")
    .addListenerForSingleValueEvent(new ValueEventListener() {
      @Override
      public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
          String version = (String) dataSnapshot.getValue();
          try {
            int lv = Integer.valueOf(version);
            PackageInfo pInfo = context.getPackageManager().getPackageInfo("com.hapramp", 0);
            int myVersion = pInfo.versionCode;
            if (myVersion < lv) {
              if (appUpdateAvailableListener != null) {
                appUpdateAvailableListener.onAppUpdateAvailable();
              }
            }
          }
          catch (Exception e) {
            Log.d("AppUpdater", e.toString());
          }
        }
      }

      @Override
      public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d("AppUpdater", databaseError.getMessage());
      }
    });
  ;
}
 
Example 8
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 9
Source File: ManageAccountActivity.java    From wmn-safety with MIT License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_account);

    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    setTitle("Update Account");

    mNameInputEditText = findViewById(R.id.account_update_full_name);
    mEmailInputEditText = findViewById(R.id.account_update_email);
    mPhoneInputEditText = findViewById(R.id.account_update_phone);

    mFirebaseAuth = FirebaseAuth.getInstance();
    mFirebaseUser = mFirebaseAuth.getCurrentUser();
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    mDatabaseReference = mFirebaseDatabase.getReference().child("users");

    mDatabaseReference.child(mFirebaseUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            UserData userData = dataSnapshot.getValue(UserData.class);
            if(userData != null)  {
                mNameInputEditText.setText(userData.getName());
                mEmailInputEditText.setText(userData.getEmail());
                mPhoneInputEditText.setText(userData.getNumber());
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
 
Example 10
Source File: FirebaseDatabaseTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testDatabaseUrlWithPathInOptions() {
  FirebaseApp app = appWithDbUrl(IntegrationTestUtils.getDatabaseUrl() 
      + "/paths/are/not/allowed", "dbUrlWithPathInOptions");
  try {      
    FirebaseDatabase.getInstance(app);
    fail("no error thrown for DB URL with path");
  } catch (DatabaseException expected) { // ignore
  }
}
 
Example 11
Source File: FirebaseDatabaseApiTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void getDifferentInstanceForAppWithUrl() {
  FirebaseApp app = appForDatabaseUrl(TEST_NAMESPACE, "getDifferentInstanceForAppWithUrl");
  FirebaseDatabase unspecified = FirebaseDatabase.getInstance(app);
  FirebaseDatabase original = FirebaseDatabase.getInstance(app, TEST_NAMESPACE);
  FirebaseDatabase alternate = FirebaseDatabase.getInstance(app, TEST_ALT_NAMESPACE);

  assertEquals(TEST_NAMESPACE, unspecified.getReference().toString());
  assertEquals(TEST_NAMESPACE, original.getReference().toString());
  assertEquals(TEST_ALT_NAMESPACE, alternate.getReference().toString());
}
 
Example 12
Source File: AgendaFragment.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");
    restoreState(savedInstanceState);

    final Bundle args = getArguments();
    title = args.getString(ARG_TITLE);
    startAtTime = args.getLong(ARG_START_AT_TIME, 0);

    favSessionButtonManager = new FavSessionButtonManager(
        FirebaseDatabase.getInstance(), FirebaseAuth.getInstance(), new MyAuthRequiredListener());
}
 
Example 13
Source File: FirebaseHelper.java    From UberClone with MIT License 5 votes vote down vote up
public FirebaseHelper(AppCompatActivity activity){
    this.activity=activity;
    root=activity.findViewById(R.id.root);
    firebaseAuth=FirebaseAuth.getInstance();
    firebaseDatabase=FirebaseDatabase.getInstance();
    users=firebaseDatabase.getReference(Common.user_driver_tbl);
    if(firebaseAuth.getUid()!=null)loginSuccess();
}
 
Example 14
Source File: DatabaseHelper.java    From social-app-android with Apache License 2.0 5 votes vote down vote up
public void init() {
        database = FirebaseDatabase.getInstance();
        database.setPersistenceEnabled(true);
        storage = FirebaseStorage.getInstance();

//        Sets the maximum time to retry upload operations if a failure occurs.
        storage.setMaxUploadRetryTimeMillis(Constants.Database.MAX_UPLOAD_RETRY_MILLIS);
    }
 
Example 15
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 16
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 17
Source File: InitContentProvider.java    From white-label-event-app with Apache License 2.0 4 votes vote down vote up
private void initFirebase() {
    final FirebaseDatabase fdb = FirebaseDatabase.getInstance();
    fdb.setPersistenceEnabled(true);
    FirebaseCache.getInstance();
    context.registerActivityLifecycleCallbacks(new GoOfflineWhenInvisible(fdb));
}
 
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: 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 20
Source File: FireSignin.java    From Learning-Resources with MIT License 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    LayoutInflaterCompat.setFactory(getLayoutInflater(), new IconicsLayoutInflater(getDelegate()));
    FacebookSdk.sdkInitialize(getApplicationContext());
    mCallbackManager = CallbackManager.Factory.create();
    super.onCreate(savedInstanceState);
    setContentView(R.layout.lo_fire_signin);

    mCrdntrlyot = (CoordinatorLayout) findViewById(R.id.cordntrlyot_fireauth);
    mTxtinptlyotEmail = (TextInputLayout) findViewById(R.id.txtinputlyot_fireauth_email);
    mTxtinptlyotPaswrd = (TextInputLayout) findViewById(R.id.txtinputlyot_fireauth_password);
    mTxtinptEtEmail = (TextInputEditText) findViewById(R.id.txtinptet_fireauth_email);
    mTxtinptEtPaswrd = (TextInputEditText) findViewById(R.id.txtinptet_fireauth_password);
    mAppcmptbtnSignup = (AppCompatButton) findViewById(R.id.appcmptbtn_fireauth_signin);
    mTvFrgtPaswrd = (TextView) findViewById(R.id.tv_fireauth_frgtpaswrd);
    mImgvwFirebase = (ImageView) findViewById(R.id.imgvw_fireauth_firebase);
    mImgvwGp = (ImageView) findViewById(R.id.imgvw_fireauth_social_gp);
    mImgvwFb = (ImageView) findViewById(R.id.imgvw_fireauth_social_fb);
    mPrgrsbrMain = (ProgressBar) findViewById(R.id.prgrsbr_fireauth);

    mFireAuth = FirebaseAuth.getInstance();
    mFireDB = FirebaseDatabase.getInstance();

    FirebaseAuth.getInstance().signOut();

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

    mAppcmptbtnSignup.setOnClickListener(this);
    mTvFrgtPaswrd.setOnClickListener(this);
    mImgvwFirebase.setOnClickListener(this);
    mImgvwGp.setOnClickListener(this);
    mImgvwFb.setOnClickListener(this);
}