Search in sources :

Example 66 with QueryDocumentSnapshot

use of com.google.firebase.firestore.QueryDocumentSnapshot in project SE_TermProject by IMDongH.

the class UserMainActivity method onMapReady.

@Override
public void onMapReady(final GoogleMap googleMap) {
    mMap = googleMap;
    // setDefaultLocation();
    // int hasFineLocationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
    // int hasCoarseLocationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
    // 
    // if (hasFineLocationPermission == PackageManager.PERMISSION_GRANTED && hasCoarseLocationPermission == PackageManager.PERMISSION_GRANTED){
    // Log.d(TAG,"should start location update");
    // startLocationUpdates();
    // }else{
    // if (ActivityCompat.shouldShowRequestPermissionRationale(this, REQUIRED_PERMISSIONS[0])) {
    // Snackbar.make(mLayout, "이 앱을 실행하려면 위치 권한이 필요합니다.",Snackbar.LENGTH_INDEFINITE).setAction("확인", new View.OnClickListener() {
    // @Override
    // public void onClick(View view) {
    // ActivityCompat.requestPermissions(UserMainActivity.this, REQUIRED_PERMISSIONS, PERMISSIONS_REQUEST_CODE);
    // }
    // }).show();
    // }else{
    // ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, PERMISSIONS_REQUEST_CODE);
    // }
    // }
    // HashMap <String, String> regMap = new HashMap<>();
    db.collection("users").document(user.getUid()).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {

        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                DocumentSnapshot document = task.getResult();
                if (document.exists()) {
                    address = (String) document.getData().get("address");
                    if (address == null) {
                        target = "성남시";
                    } else {
                        for (String temp : selectOption) {
                            if (address.contains(temp)) {
                                target = temp;
                                break;
                            }
                        }
                    }
                    for (int i = 0; i < selectOption.length; i++) {
                        if (target.equals(selectOption[i])) {
                            regionMenu.setTitle(selectOption[i]);
                            break;
                        }
                    }
                    db.collection(target).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

                        @Override
                        public void onComplete(@NonNull Task<QuerySnapshot> task) {
                            if (task.isSuccessful()) {
                                // latitude - 위도
                                // longitude - 경도
                                double cameraLat = 0.0;
                                double camreaLon = 0.0;
                                for (QueryDocumentSnapshot document : task.getResult()) {
                                    if (document.exists()) {
                                        String address = (String) document.getData().get("소재지도로명주소");
                                        double latitude = (double) document.getData().get("위도");
                                        double longitude = (double) document.getData().get("경도");
                                        if (cameraLat == 0)
                                            cameraLat = latitude;
                                        if (camreaLon == 0)
                                            camreaLon = longitude;
                                        LatLng location = new LatLng(latitude, longitude);
                                        MarkerOptions markerOptions = new MarkerOptions();
                                        markerOptions.position(location);
                                        String centerName = (String) document.getData().get("자동차정비업체명");
                                        String phone = "";
                                        phone = (String) document.getData().get("phone");
                                        if (phone == null) {
                                            phone = "미등록업체";
                                        } else {
                                            cameraLat = latitude;
                                            camreaLon = longitude;
                                            regList.add(centerName);
                                            regTable.put(centerName, phone);
                                        }
                                        // regMap.put(centerName, phone);
                                        markerOptions.title(centerName);
                                        markerOptions.snippet(address);
                                        mMap.addMarker(markerOptions);
                                        Log.d(TAG, "DocumentSnapshot data: " + document.getData() + "phone :" + phone);
                                    } else {
                                        Log.d(TAG, "No document");
                                    }
                                }
                                if (address == null) {
                                    curPo = new LatLng(cameraLat, camreaLon);
                                } else {
                                    List<Address> list = null;
                                    try {
                                        list = geocoder.getFromLocationName(address, 3);
                                    } catch (Exception e) {
                                        Log.d(TAG, e.toString());
                                    }
                                    curPo = new LatLng(list.get(0).getLatitude(), list.get(0).getLongitude());
                                }
                                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(curPo, 15));
                                mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {

                                    @Override
                                    public void onInfoWindowClick(@NonNull Marker marker) {
                                        Log.d(TAG, "Info window click :" + marker.getTitle());
                                        // Log.e(TAG,regList.get(marker.getTitle()));
                                        if (regList.contains(marker.getTitle())) {
                                            Bundle data = new Bundle();
                                            data.putString("centerName", marker.getTitle());
                                            data.putString("centerAddress", marker.getSnippet());
                                            data.putString("phone", regTable.get(marker.getTitle()));
                                            Intent intent = new Intent(UserMainActivity.this, PopUpCenterInfo.class);
                                            intent.putExtras(data);
                                            startActivity(intent);
                                        } else {
                                            StartToast("미등록업체입니다. ");
                                        }
                                    }
                                });
                            } else {
                                Log.d("TAG", "failed with", task.getException());
                            }
                        }
                    });
                }
            }
        }
    });
}
Also used : Task(com.google.android.gms.tasks.Task) MarkerOptions(com.google.android.gms.maps.model.MarkerOptions) Address(android.location.Address) QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) Bundle(android.os.Bundle) Intent(android.content.Intent) Marker(com.google.android.gms.maps.model.Marker) QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) DocumentSnapshot(com.google.firebase.firestore.DocumentSnapshot) OnCompleteListener(com.google.android.gms.tasks.OnCompleteListener) GoogleMap(com.google.android.gms.maps.GoogleMap) NonNull(androidx.annotation.NonNull) LatLng(com.google.android.gms.maps.model.LatLng)

Example 67 with QueryDocumentSnapshot

use of com.google.firebase.firestore.QueryDocumentSnapshot in project SE_TermProject by IMDongH.

the class PopUpSearchCenterName method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 액션바 제거
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_search_popup);
    db = FirebaseFirestore.getInstance();
    // 시/군 정보 받기
    Intent intent = getIntent();
    String region = intent.getStringExtra("region");
    // 어뎁터에 해당 시/군에 있는 카센터 이름이 담긴 ArrayList 를 넘긴다
    db.collection(region).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {
                    if (document.exists()) {
                        String CenterName = (String) document.getData().get("자동차정비업체명");
                        Popup_CenterNameInfo data = new Popup_CenterNameInfo(CenterName);
                        arraylist.add(data);
                    }
                }
                listView = findViewById(R.id.listview);
                adapter = new Popup_ListViewAdapter(getApplicationContext(), arraylist);
                listView.setAdapter(adapter);
                // 서치바 안에 텍스트가 바뀔 때
                editsearch = findViewById(R.id.search);
                editsearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

                    @Override
                    public boolean onQueryTextSubmit(String s) {
                        return false;
                    }

                    @Override
                    public boolean onQueryTextChange(String s) {
                        // 입력란의 문자열이 바뀔 때 처리
                        adapter.filter(s);
                        return false;
                    }
                });
                // 검색해서 나온 카센터 이름(리스트뷰) 선택 이벤트
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        result_CenterName = adapter.getItem(i).getCenterName();
                        Intent return_intent = new Intent();
                        return_intent.putExtra("name", result_CenterName);
                        setResult(RESULT_OK, return_intent);
                        finish();
                    }
                });
            }
        }
    });
}
Also used : QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) Intent(android.content.Intent) SearchView(android.widget.SearchView) View(android.view.View) AdapterView(android.widget.AdapterView) ListView(android.widget.ListView) QuerySnapshot(com.google.firebase.firestore.QuerySnapshot) AdapterView(android.widget.AdapterView)

Example 68 with QueryDocumentSnapshot

use of com.google.firebase.firestore.QueryDocumentSnapshot in project HackFest2022-Pretzel by chuanshaof.

the class ScrollJobActivity method onCreate.

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scroll_job);
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    flingAdapterView = findViewById(R.id.swipe);
    ArrayList<JobModel> data = new ArrayList<>();
    jobTracker = new HashMap<>();
    arrayAdapter = new JobAdapter(ScrollJobActivity.this, R.layout.item_in_cardview, data);
    flingAdapterView.setAdapter(arrayAdapter);
    db.collection(JobModel.getCollectionId()).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot documentSnapshot : task.getResult()) {
                    Log.d(TAG, "onComplete: " + documentSnapshot);
                    new JobDb(ScrollJobActivity.this, new JobDb.OnJobModel() {

                        @Override
                        public void onResult(JobModel jobModel) {
                            new ApplicantDb(ScrollJobActivity.this, new ApplicantDb.OnApplicantModel() {

                                @Override
                                public void onResult(ApplicantModel applicantModel) {
                                    boolean applied = false;
                                    for (DocumentReference application : applicantModel.getApplications()) {
                                        applied = applied | jobModel.getPending().contains(application);
                                    }
                                    if (applied == false) {
                                        data.add(jobModel);
                                        arrayAdapter.notifyDataSetChanged();
                                        jobTracker.put(jobModel, documentSnapshot.getReference());
                                    }
                                }
                            }).getApplicantModel(LoggedInUser.getInstance().getEmail());
                        }
                    }).getJobModel(documentSnapshot.getReference());
                }
            }
        }
    });
    flingAdapterView.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {

        @Override
        public void removeFirstObjectInAdapter() {
            data.remove(0);
            arrayAdapter.notifyDataSetChanged();
        }

        @Override
        public void onLeftCardExit(Object o) {
            Toast.makeText(ScrollJobActivity.this, "Skipped Job", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onRightCardExit(Object o) {
            new ApplicationDb(ScrollJobActivity.this, new ApplicationDb.OnApplicationUploadSuccess() {

                @Override
                public void onResult() {
                    Toast.makeText(ScrollJobActivity.this, "Applied", Toast.LENGTH_SHORT).show();
                }
            }).newApplication(LoggedInUser.getInstance().getUserDocRef(), jobTracker.get(o));
        }

        @Override
        public void onAdapterAboutToEmpty(int i) {
        }

        @Override
        public void onScroll(float v) {
        }
    });
    flingAdapterView.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {

        @Override
        public void onItemClicked(int i, Object o) {
            Intent intent = new Intent(ScrollJobActivity.this, ViewJobActivity.class);
            intent.putExtra(ViewJobActivity.TAG, data.get(i).getDocumentId());
            startActivityForResult(intent, 0);
        }
    });
    Button like, dislike;
    like = findViewById(R.id.like);
    dislike = findViewById(R.id.dislike);
    like.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            flingAdapterView.getTopCardListener().selectRight();
        }
    });
    dislike.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            flingAdapterView.getTopCardListener().selectLeft();
        }
    });
    // Initialize and assign variable
    BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
    // Set Home selected
    bottomNavigationView.setSelectedItemId(R.id.home);
    // Perform item selected listener
    bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Intent intent;
            switch(item.getItemId()) {
                case R.id.history:
                    intent = new Intent(ScrollJobActivity.this, ApplicationHistoryActivity.class);
                    startActivity(intent);
                    overridePendingTransition(0, 0);
                    return true;
                case R.id.home:
                    return true;
                case R.id.profile:
                    intent = new Intent(ScrollJobActivity.this, ProfileActivity.class);
                    intent.putExtra(ProfileActivity.TAG, LoggedInUser.getInstance().getEmail());
                    startActivity(intent);
                    overridePendingTransition(0, 0);
                    return true;
            }
            return false;
        }
    });
}
Also used : ArrayList(java.util.ArrayList) ApplicantDb(com.example.nftscmers.db.ApplicantDb) JobAdapter(com.example.nftscmers.adapters.JobAdapter) QuerySnapshot(com.google.firebase.firestore.QuerySnapshot) Button(android.widget.Button) BottomNavigationView(com.google.android.material.bottomnavigation.BottomNavigationView) ViewJobActivity(com.example.nftscmers.commonactivities.ViewJobActivity) ApplicationDb(com.example.nftscmers.db.ApplicationDb) JobModel(com.example.nftscmers.objectmodels.JobModel) DocumentReference(com.google.firebase.firestore.DocumentReference) SwipeFlingAdapterView(com.lorentzos.flingswipe.SwipeFlingAdapterView) FirebaseFirestore(com.google.firebase.firestore.FirebaseFirestore) QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) ApplicantModel(com.example.nftscmers.objectmodels.ApplicantModel) Intent(android.content.Intent) MenuItem(android.view.MenuItem) View(android.view.View) BottomNavigationView(com.google.android.material.bottomnavigation.BottomNavigationView) SwipeFlingAdapterView(com.lorentzos.flingswipe.SwipeFlingAdapterView) JobDb(com.example.nftscmers.db.JobDb)

Example 69 with QueryDocumentSnapshot

use of com.google.firebase.firestore.QueryDocumentSnapshot in project snippets-android by firebase.

the class DocSnippets method deleteQueryBatch.

/**
 * Delete all results from a query in a single WriteBatch. Must be run on a worker thread
 * to avoid blocking/crashing the main thread.
 */
@WorkerThread
private List<DocumentSnapshot> deleteQueryBatch(final Query query) throws Exception {
    QuerySnapshot querySnapshot = Tasks.await(query.get());
    WriteBatch batch = query.getFirestore().batch();
    for (QueryDocumentSnapshot snapshot : querySnapshot) {
        batch.delete(snapshot.getReference());
    }
    Tasks.await(batch.commit());
    return querySnapshot.getDocuments();
}
Also used : QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) WriteBatch(com.google.firebase.firestore.WriteBatch) QuerySnapshot(com.google.firebase.firestore.QuerySnapshot) WorkerThread(androidx.annotation.WorkerThread)

Example 70 with QueryDocumentSnapshot

use of com.google.firebase.firestore.QueryDocumentSnapshot in project PMDM2021 by arodriguezgim.

the class HomeActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    tvemail = findViewById(R.id.emailTextView);
    tvmetodo = findViewById(R.id.metodoTextView);
    logOut = findViewById(R.id.logoutButton);
    errorButton = findViewById(R.id.errorButton);
    guardarButton = findViewById(R.id.guardarButton);
    recuperarButton = findViewById(R.id.recuperrarButton);
    borrarButton = findViewById(R.id.borrarButton);
    direccionET = findViewById(R.id.addressTextView);
    telefonoET = findViewById(R.id.tfnoTextView);
    errorButton.setVisibility(View.INVISIBLE);
    // Recuperamos los datos del LoginActivity
    Bundle datos = this.getIntent().getExtras();
    String email = datos.getString("email");
    String metodo = datos.getString("metodo");
    // Guardado de datos
    SharedPreferences sesion = getSharedPreferences("sesion", Context.MODE_PRIVATE);
    SharedPreferences.Editor Obj_editor = sesion.edit();
    Obj_editor.putString("email", email);
    Obj_editor.putString("metodo", metodo);
    Obj_editor.apply();
    Obj_editor.commit();
    // Configuracion Remota (Parametros de configuracion)
    mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
    FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder().setMinimumFetchIntervalInSeconds(60).build();
    mFirebaseRemoteConfig.setConfigSettingsAsync(configSettings);
    mFirebaseRemoteConfig.fetchAndActivate().addOnCompleteListener(this, new OnCompleteListener<Boolean>() {

        @Override
        public void onComplete(@NonNull Task<Boolean> task) {
            if (task.isSuccessful()) {
                boolean updated = task.getResult();
                Toast.makeText(HomeActivity.this, "Configuracion Remota obtenida satisfactoriamente", Toast.LENGTH_LONG).show();
                mostrarBotonError = mFirebaseRemoteConfig.getBoolean("show_button");
                String textoBotonError = mFirebaseRemoteConfig.getString("button_text");
                if (mostrarBotonError) {
                    errorButton.setVisibility(View.VISIBLE);
                    errorButton.setText(textoBotonError);
                } else {
                    Toast.makeText(HomeActivity.this, "Fetch failed", Toast.LENGTH_LONG).show();
                }
            }
        }
    });
    tvemail.setText(email);
    tvmetodo.setText(metodo);
    // Firestorage
    db = FirebaseFirestore.getInstance();
    guardarButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // Obtenemos los datos del usuario actualizados
            Map<String, Object> usuario = new HashMap<>();
            usuario.put("email", email);
            usuario.put("metodo", metodo);
            usuario.put("direccion", direccionET.getText().toString());
            usuario.put("telefono", telefonoET.getText().toString());
            db.collection("usuarios").document(email).set(usuario);
        }
    });
    // CLICK EN RECUPERAR
    recuperarButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            db.collection("usuarios").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            direccionET.setText(document.getString("direccion"));
                            telefonoET.setText(document.getString("telefono"));
                        }
                    } else {
                        Log.w("TAG", "Error getting documents.", task.getException());
                    }
                }
            });
        }
    });
    borrarButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            db.collection("usuarios").document(email).delete();
        }
    });
    logOut.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // Al hacer click en Salir borramos los datos guardados en preferencias
            SharedPreferences sesion = getSharedPreferences("sesion", Context.MODE_PRIVATE);
            SharedPreferences.Editor Obj_editor = sesion.edit();
            Obj_editor.clear();
            Obj_editor.apply();
            FirebaseAuth.getInstance().signOut();
            onBackPressed();
        }
    });
}
Also used : Task(com.google.android.gms.tasks.Task) SharedPreferences(android.content.SharedPreferences) QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) Bundle(android.os.Bundle) FirebaseRemoteConfigSettings(com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings) TextView(android.widget.TextView) View(android.view.View) OnCompleteListener(com.google.android.gms.tasks.OnCompleteListener) NonNull(androidx.annotation.NonNull) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

QueryDocumentSnapshot (com.google.firebase.firestore.QueryDocumentSnapshot)73 QuerySnapshot (com.google.firebase.firestore.QuerySnapshot)33 ArrayList (java.util.ArrayList)30 View (android.view.View)22 NonNull (androidx.annotation.NonNull)19 Task (com.google.android.gms.tasks.Task)18 OnCompleteListener (com.google.android.gms.tasks.OnCompleteListener)17 Intent (android.content.Intent)16 CollectionReference (com.google.firebase.firestore.CollectionReference)13 AdapterView (android.widget.AdapterView)12 FirebaseFirestore (com.google.firebase.firestore.FirebaseFirestore)12 TextView (android.widget.TextView)10 Bundle (android.os.Bundle)9 ListView (android.widget.ListView)9 DocumentSnapshot (com.google.firebase.firestore.DocumentSnapshot)9 FirebaseFirestoreException (com.google.firebase.firestore.FirebaseFirestoreException)8 UsersDataModel (com.example.first_responder_app.dataModels.UsersDataModel)7 OnFailureListener (com.google.android.gms.tasks.OnFailureListener)6 FirebaseUser (com.google.firebase.auth.FirebaseUser)6 DocumentReference (com.google.firebase.firestore.DocumentReference)6