Search in sources :

Example 6 with FirebaseFirestore

use of com.google.firebase.firestore.FirebaseFirestore in project firebase-android-sdk by firebase.

the class IntegrationTestUtil method testFirestore.

public static FirebaseFirestore testFirestore(String projectId, Logger.Level logLevel, FirebaseFirestoreSettings settings, String persistenceKey) {
    // This unfortunately is a global setting that affects existing Firestore clients.
    Logger.setLogLevel(logLevel);
    Context context = ApplicationProvider.getApplicationContext();
    DatabaseId databaseId = DatabaseId.forDatabase(projectId, DatabaseId.DEFAULT_DATABASE_ID);
    ensureStrictMode();
    AsyncQueue asyncQueue = new AsyncQueue();
    FirebaseFirestore firestore = AccessHelper.newFirebaseFirestore(context, databaseId, persistenceKey, MockCredentialsProvider.instance(), new EmptyAppCheckTokenProvider(), asyncQueue, /*firebaseApp=*/
    null, /*instanceRegistry=*/
    (dbId) -> {
    });
    waitFor(firestore.clearPersistence());
    firestore.setFirestoreSettings(settings);
    firestoreStatus.put(firestore, true);
    return firestore;
}
Also used : Context(android.content.Context) FirebaseFirestore(com.google.firebase.firestore.FirebaseFirestore) DatabaseId(com.google.firebase.firestore.model.DatabaseId) AsyncQueue(com.google.firebase.firestore.util.AsyncQueue)

Example 7 with FirebaseFirestore

use of com.google.firebase.firestore.FirebaseFirestore in project firebase-android-sdk by firebase.

the class FirestoreTest method setShouldFailWithPermissionDenied.

@Test
public void setShouldFailWithPermissionDenied() throws Exception {
    FirebaseAuth auth = FirebaseAuth.getInstance();
    FirebaseFirestore firestore = FirebaseFirestore.getInstance();
    auth.signOut();
    // TODO(allisonbm92): Introduce a better means to reduce flakes.
    Thread.sleep(1000);
    DocumentReference doc = firestore.collection("restaurants").document(TestId.create());
    try {
        HashMap<String, Object> data = new HashMap<>();
        data.put("popularity", 5000L);
        Task<?> setTask = doc.set(new HashMap<>(data));
        Throwable failure = Tasks2.waitForFailure(setTask);
        FirebaseFirestoreException ex = (FirebaseFirestoreException) failure;
        assertThat(ex.getCode()).isEqualTo(FirebaseFirestoreException.Code.PERMISSION_DENIED);
    } finally {
        Tasks2.waitBestEffort(doc.delete());
    }
}
Also used : FirebaseFirestore(com.google.firebase.firestore.FirebaseFirestore) HashMap(java.util.HashMap) FirebaseFirestoreException(com.google.firebase.firestore.FirebaseFirestoreException) DocumentReference(com.google.firebase.firestore.DocumentReference) FirebaseAuth(com.google.firebase.auth.FirebaseAuth) Test(org.junit.Test)

Example 8 with FirebaseFirestore

use of com.google.firebase.firestore.FirebaseFirestore in project firebase-android-sdk by firebase.

the class FirestoreTest method updateShouldTriggerListenerWithUpdatedData.

@Test
public void updateShouldTriggerListenerWithUpdatedData() throws Exception {
    FirebaseAuth auth = FirebaseAuth.getInstance();
    FirebaseFirestore firestore = FirebaseFirestore.getInstance();
    auth.signOut();
    Task<?> signInTask = auth.signInWithEmailAndPassword("test@mailinator.com", "password");
    Tasks2.waitForSuccess(signInTask);
    DocumentReference doc = firestore.collection("restaurants").document(TestId.create());
    try {
        HashMap<String, Object> originalData = new HashMap<>();
        originalData.put("location", "Google NYC");
        Task<?> setTask = doc.set(new HashMap<>(originalData));
        Tasks2.waitForSuccess(setTask);
        SnapshotListener listener = new SnapshotListener(2);
        ListenerRegistration registration = doc.addSnapshotListener(listener);
        try {
            HashMap<String, Object> updateData = new HashMap<>();
            updateData.put("priority", 5L);
            Task<?> updateTask = doc.update(new HashMap<>(updateData));
            Task<DocumentSnapshot> snapshotTask = listener.toTask();
            Tasks2.waitForSuccess(updateTask);
            Tasks2.waitForSuccess(snapshotTask);
            DocumentSnapshot result = snapshotTask.getResult();
            HashMap<String, Object> finalData = new HashMap<>();
            finalData.put("location", "Google NYC");
            finalData.put("priority", 5L);
            assertThat(result.getData()).isEqualTo(finalData);
        } finally {
            registration.remove();
        }
    } finally {
        Tasks2.waitBestEffort(doc.delete());
    }
}
Also used : FirebaseFirestore(com.google.firebase.firestore.FirebaseFirestore) HashMap(java.util.HashMap) ListenerRegistration(com.google.firebase.firestore.ListenerRegistration) DocumentSnapshot(com.google.firebase.firestore.DocumentSnapshot) DocumentReference(com.google.firebase.firestore.DocumentReference) FirebaseAuth(com.google.firebase.auth.FirebaseAuth) Test(org.junit.Test)

Example 9 with FirebaseFirestore

use of com.google.firebase.firestore.FirebaseFirestore in project FIREBASE_TEST_JAVA by essantos8.

the class LoginActivity method firebaseAuthWithGoogle.

private void firebaseAuthWithGoogle(String idToken, GoogleSignInAccount account) {
    AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
    mAuth.signInWithCredential(credential).addOnCompleteListener(this, task -> {
        if (task.isSuccessful()) {
            // Sign in success, update UI with the signed-in user's information
            Log.d("Google Sign In", "signInWithCredential:success");
            FirebaseFirestore db = FirebaseFirestore.getInstance();
            // Check if account is in database
            db.collection("users").whereEqualTo("email", account.getEmail()).get().addOnCompleteListener(task1 -> {
                if (task1.isSuccessful()) {
                    if (task1.getResult().size() > 0) {
                        Log.d("Google Sign In", "Existing account");
                    } else {
                        Log.d("Google Sign In", "New account, adding to Database");
                        User userData = new User(account.getDisplayName(), account.getEmail(), "", mAuth.getCurrentUser().getUid());
                        db.collection("users").document(mAuth.getCurrentUser().getUid()).set(userData);
                    }
                } else {
                    Toast.makeText(this, "Error accessing database!", Toast.LENGTH_SHORT).show();
                }
            });
            startActivity(new Intent(this, MainActivity.class));
        } else {
            // If sign in fails, display a message to the user.
            Log.w("Google Sign In", "signInWithCredential:failure", task.getException());
        }
    });
}
Also used : AuthCredential(com.google.firebase.auth.AuthCredential) FirebaseFirestore(com.google.firebase.firestore.FirebaseFirestore) User(com.example.flashgig.models.User) FirebaseUser(com.google.firebase.auth.FirebaseUser) Intent(android.content.Intent)

Example 10 with FirebaseFirestore

use of com.google.firebase.firestore.FirebaseFirestore in project MDA_APP_RESTAURANTE by karlaogh99.

the class MainActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    // System.out.println("Usuario logeado: " + user.getEmail());
    binding = ActivityMainBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());
    setSupportActionBar(binding.appBarMain.toolbar);
    binding.appBarMain.fab.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show();
        }
    });
    DrawerLayout drawer = binding.drawerLayout;
    NavigationView navigationView = binding.navView;
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    mAppBarConfiguration = new AppBarConfiguration.Builder(R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow).setOpenableLayout(drawer).build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
    NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
    NavigationUI.setupWithNavController(navigationView, navController);
    // Esto es poner en el nav el nombre del usuario
    View headerView = navigationView.getHeaderView(0);
    TextView navUsername = (TextView) headerView.findViewById(R.id.usernameTextView);
    navUsername.setText(user.getEmail());
    // Insertar menu de BD
    recycler_menu = (RecyclerView) findViewById(R.id.menu);
    recycler_menu.setHasFixedSize(true);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    recycler_menu.setLayoutManager(layoutManager);
    System.out.print("f");
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    // Read from the database
    listCategory = new ArrayList<>();
    db.collection("Category").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {
                    Category cat = new Category("", "");
                    cat.setName((String) document.get("Nombre"));
                    cat.setImage((String) document.get("Image"));
                    listCategory.add(cat);
                }
                AdapterCategory adapter = new AdapterCategory(listCategory, new AdapterCategory.OnItemClickListener() {

                    @Override
                    public void onItemClick(Category cat) {
                        moveToDescription(cat);
                    }
                });
                recycler_menu.setAdapter(adapter);
            }
        }
    });
}
Also used : NavigationView(com.google.android.material.navigation.NavigationView) FirebaseFirestore(com.google.firebase.firestore.FirebaseFirestore) Category(com.example.app_restaurante.Model.Category) AdapterCategory(com.example.app_restaurante.Adapter.AdapterCategory) QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) NavController(androidx.navigation.NavController) AdapterCategory(com.example.app_restaurante.Adapter.AdapterCategory) FirebaseUser(com.google.firebase.auth.FirebaseUser) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) NavigationView(com.google.android.material.navigation.NavigationView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) TextView(android.widget.TextView) QuerySnapshot(com.google.firebase.firestore.QuerySnapshot) TextView(android.widget.TextView) DrawerLayout(androidx.drawerlayout.widget.DrawerLayout) AppBarConfiguration(androidx.navigation.ui.AppBarConfiguration)

Aggregations

FirebaseFirestore (com.google.firebase.firestore.FirebaseFirestore)21 FirebaseAuth (com.google.firebase.auth.FirebaseAuth)6 HashMap (java.util.HashMap)6 Intent (android.content.Intent)5 Log (android.util.Log)4 FirebaseUser (com.google.firebase.auth.FirebaseUser)4 View (android.view.View)3 NonNull (androidx.annotation.NonNull)3 DocumentReference (com.google.firebase.firestore.DocumentReference)3 DocumentSnapshot (com.google.firebase.firestore.DocumentSnapshot)3 QuerySnapshot (com.google.firebase.firestore.QuerySnapshot)3 Constant (com.group1.swepproject.user.nochange.data.Constant)3 Test (org.junit.Test)3 Application (android.app.Application)2 Bitmap (android.graphics.Bitmap)2 Location (android.location.Location)2 Bundle (android.os.Bundle)2 MediaStore (android.provider.MediaStore)2 EditText (android.widget.EditText)2 TextView (android.widget.TextView)2