Search in sources :

Example 6 with ActiveUser

use of com.example.first_responder_app.interfaces.ActiveUser in project FirstResponse by mattpost1700.

the class IncidentFragment method initializeIncident.

/**
 * Setup the incident data and display it
 *
 * @param incident The incident to be displayed
 */
public void initializeIncident(IncidentDataModel incident) {
    setTextViews(incident);
    Map<String, String> status = incident.getStatus();
    // Get active user id
    ActiveUser activeUser = (ActiveUser) getActivity();
    if (activeUser != null) {
        UsersDataModel user = activeUser.getActive();
        if (user != null)
            active_id = user.getDocumentId();
    }
    // Highlight active button
    if (status != null && status.containsKey(active_id)) {
        setActiveButton(status.get(active_id));
    }
    setRespondingButtonClickListener();
    // Get the Address object of the incident
    incidentAddress = addrToCoords(incident.getLocation());
    setupLocationListener();
    AtomicInteger prevLength = new AtomicInteger();
    if (listenerRegistration == null) {
        // Ensure that the incident data is updated if database is updated
        docRef = FirestoreDatabase.getInstance().getDb().collection("incident").document(incident.getDocumentId());
        listenerRegistration = docRef.addSnapshotListener((snapshot, e) -> {
            Log.d(TAG, "READ DATABASE - INCIDENT FRAGMENT");
            if (e != null) {
                System.err.println("Listen failed: " + e);
                return;
            }
            if (snapshot != null && snapshot.exists()) {
                incidentDataModel = snapshot.toObject(IncidentDataModel.class);
                if (incidentDataModel != null) {
                    setTextViews(incidentDataModel);
                    Map<String, String> statuses = incidentDataModel.getStatus();
                    if (statuses != null) {
                        String status1 = statuses.get(active_id);
                        setActiveButton(status1);
                    }
                    // Get the Address object of the incident
                    incidentAddress = addrToCoords(incidentDataModel.getLocation());
                    int currentLength = incidentDataModel.getResponding().size();
                    if (prevLength.get() != currentLength) {
                        prevLength.set(currentLength);
                        responderList.clear();
                        populateRespondersListFromDB();
                    }
                }
            } else {
                System.out.print("Current data: null");
            }
        });
    }
}
Also used : Address(android.location.Address) CameraUpdateFactory(com.google.android.gms.maps.CameraUpdateFactory) Chip(com.google.android.material.chip.Chip) LinearLayout(android.widget.LinearLayout) Bundle(android.os.Bundle) PackageManager(android.content.pm.PackageManager) NonNull(androidx.annotation.NonNull) LocationListener(android.location.LocationListener) ColorStateList(android.content.res.ColorStateList) ActiveUser(com.example.first_responder_app.interfaces.ActiveUser) Manifest(android.Manifest) FieldPath(com.google.firebase.firestore.FieldPath) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FragmentIncidentBinding(com.example.first_responder_app.databinding.FragmentIncidentBinding) Locale(java.util.Locale) ETA(com.example.first_responder_app.DirectionAPI.ETA) Map(java.util.Map) View(android.view.View) Button(android.widget.Button) ContextCompat(androidx.core.content.ContextCompat) NavHostFragment(androidx.navigation.fragment.NavHostFragment) Log(android.util.Log) DataBindingUtil(androidx.databinding.DataBindingUtil) MapView(com.google.android.gms.maps.MapView) LatLng(com.google.android.gms.maps.model.LatLng) NavDirections(androidx.navigation.NavDirections) AppUtil(com.example.first_responder_app.AppUtil) MaterialColors(com.google.android.material.color.MaterialColors) IncidentViewModel(com.example.first_responder_app.viewModels.IncidentViewModel) Geocoder(android.location.Geocoder) ViewGroup(android.view.ViewGroup) AlertDialog(android.app.AlertDialog) R(com.example.first_responder_app.R) List(java.util.List) Nullable(androidx.annotation.Nullable) TextView(android.widget.TextView) Location(android.location.Location) Marker(com.google.android.gms.maps.model.Marker) LocationManager(android.location.LocationManager) DialogFragment(androidx.fragment.app.DialogFragment) Context(android.content.Context) ChipGroup(com.google.android.material.chip.ChipGroup) Dialog(android.app.Dialog) ArrayList(java.util.ArrayList) SuppressLint(android.annotation.SuppressLint) DocumentReference(com.google.firebase.firestore.DocumentReference) QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) IncidentDataModel(com.example.first_responder_app.dataModels.IncidentDataModel) Toast(android.widget.Toast) ListenerRegistration(com.google.firebase.firestore.ListenerRegistration) ReportViewModel(com.example.first_responder_app.viewModels.ReportViewModel) TAG(android.content.ContentValues.TAG) DialogInterface(android.content.DialogInterface) UsersDataModel(com.example.first_responder_app.dataModels.UsersDataModel) ViewModelProvider(androidx.lifecycle.ViewModelProvider) ActivityCompat(androidx.core.app.ActivityCompat) LayoutInflater(android.view.LayoutInflater) MarkerOptions(com.google.android.gms.maps.model.MarkerOptions) FirestoreDatabase(com.example.first_responder_app.FirestoreDatabase) IOException(java.io.IOException) UserViewModel(com.example.first_responder_app.viewModels.UserViewModel) OnMapReadyCallback(com.google.android.gms.maps.OnMapReadyCallback) RefreshETAs(com.example.first_responder_app.interfaces.RefreshETAs) Navigation(androidx.navigation.Navigation) GoogleMap(com.google.android.gms.maps.GoogleMap) UsersDataModel(com.example.first_responder_app.dataModels.UsersDataModel) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ActiveUser(com.example.first_responder_app.interfaces.ActiveUser) Map(java.util.Map) GoogleMap(com.google.android.gms.maps.GoogleMap)

Example 7 with ActiveUser

use of com.example.first_responder_app.interfaces.ActiveUser in project FirstResponse by mattpost1700.

the class LoginFragment method onCreateView.

@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    // lock drawer on login page
    DrawerLocker drawerLocker = ((DrawerLocker) getActivity());
    if (drawerLocker != null) {
        drawerLocker.setDrawerLocked(true);
    }
    Context context = getActivity();
    // binding fragment with nav_map by using navHostFragment, throw this block of code in there and that allows you to switch to other fragments
    binding = DataBindingUtil.inflate(inflater, R.layout.fragment_login, container, false);
    NavHostFragment navHostFragment = (NavHostFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
    assert navHostFragment != null;
    NavController navController = navHostFragment.getNavController();
    sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    // check whether user finished typing and query the data
    binding.loginUsername.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            last_text_edit = System.currentTimeMillis();
            handler.removeCallbacks(input_finish_checker);
        }

        @Override
        public void afterTextChanged(Editable editable) {
            mViewModel.setUsername(binding.loginUsername.getText().toString());
            if (binding.loginPassword.getText().length() > 0) {
                last_text_edit = System.currentTimeMillis();
                handler.postDelayed(input_finish_checker, 500);
            }
        }
    });
    binding.loginPassword.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            last_text_edit = System.currentTimeMillis();
            handler.removeCallbacks(input_finish_checker);
        }

        @Override
        public void afterTextChanged(Editable editable) {
            mViewModel.setPassword(binding.loginPassword.getText().toString());
            if (binding.loginPassword.getText().length() > 0) {
                last_text_edit = System.currentTimeMillis();
                handler.postDelayed(input_finish_checker, 500);
            }
        }
    });
    binding.loginCreateAccountFab.setOnClickListener(v -> {
        NavDirections action = LoginFragmentDirections.actionLoginFragmentToCreateUserFragment();
        Navigation.findNavController(binding.getRoot()).navigate(action);
    });
    binding.loginCreateDepartmentFab.setOnClickListener(v -> {
        NavDirections action = LoginFragmentDirections.actionLoginFragmentToCreateDepartmentFragment();
        Navigation.findNavController(binding.getRoot()).navigate(action);
    });
    binding.loginSubmit.setOnClickListener(v -> {
        if (mViewModel.getUsername() == null || mViewModel.getPassword() == null) {
            binding.loginLog.setText(R.string.loginFailMsg);
            binding.loginLog.setVisibility(View.VISIBLE);
            Log.d("testing", "login failed: wrong username/password");
        } else {
            if (checkUsernameExists(mViewModel.getUsername())) {
                if (checkPwMatch(mViewModel.getUsername(), mViewModel.getPassword())) {
                    // wraps the shared preferences and auto encrypts keys and values using a two-schemed method
                    try {
                        SharedPreferences.Editor editor = sharedPref.edit();
                        editor.putString("savedUsername", mViewModel.getUsername());
                        editor.putString("savedPassword", mViewModel.getPassword());
                        editor.apply();
                        String masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
                        sharedPref = EncryptedSharedPreferences.create("secret_shared_prefs", masterKeyAlias, context, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM);
                    } catch (Exception e) {
                        Log.d("Login Encryption: ", "Encryption failed");
                    }
                    ActiveUser activeUser = ((ActiveUser) getActivity());
                    activeUser.setActive(user);
                    successfullyHidAdminOptions();
                    NavDirections action = LoginFragmentDirections.actionLoginFragmentToHomeFragment();
                    Navigation.findNavController(binding.getRoot()).navigate(action);
                    Log.d("testing", "username: " + mViewModel.getUsername() + " pw: " + mViewModel.getPassword() + " Login success.");
                } else {
                    binding.loginLog.setText(R.string.loginFailMsg);
                    binding.loginLog.setVisibility(View.VISIBLE);
                    Log.d("testing", "login failed: wrong username/password");
                }
            } else {
                binding.loginLog.setText(R.string.loginFailMsg);
                binding.loginLog.setVisibility(View.VISIBLE);
                Log.d("testing", "login failed: wrong username/password");
            }
        }
    });
    binding.bypassBtn.setOnClickListener(v -> {
        successfullyHidAdminOptions();
        NavDirections action = LoginFragmentDirections.actionLoginFragmentToHomeFragment();
        Navigation.findNavController(binding.getRoot()).navigate(action);
    });
    return binding.getRoot();
}
Also used : Context(android.content.Context) EncryptedSharedPreferences(androidx.security.crypto.EncryptedSharedPreferences) SharedPreferences(android.content.SharedPreferences) NavController(androidx.navigation.NavController) DrawerLocker(com.example.first_responder_app.interfaces.DrawerLocker) NavDirections(androidx.navigation.NavDirections) ActiveUser(com.example.first_responder_app.interfaces.ActiveUser) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) NavHostFragment(androidx.navigation.fragment.NavHostFragment)

Example 8 with ActiveUser

use of com.example.first_responder_app.interfaces.ActiveUser in project FirstResponse by mattpost1700.

the class LoginFragment method onStart.

@Override
public void onStart() {
    super.onStart();
    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    String usernameQuickLogin = sharedPref.getString("savedUsername", null);
    String passwordQuickLogin = sharedPref.getString("savedPassword", null);
    Log.d("testing", "usernameQuick: " + usernameQuickLogin);
    Log.d("testing", "pwQuick: " + passwordQuickLogin);
    if (usernameQuickLogin != null && passwordQuickLogin != null) {
        db.collection("users").whereEqualTo("username", usernameQuickLogin).whereEqualTo("password", passwordQuickLogin).get().addOnCompleteListener(usersTask -> {
            Log.d(TAG, "READ DATABASE - LOGIN FRAGMENT");
            if (usersTask.isSuccessful()) {
                for (QueryDocumentSnapshot userDoc : usersTask.getResult()) {
                    user = userDoc.toObject(UsersDataModel.class);
                    checkExist = true;
                    if (user.getPassword().equals(passwordQuickLogin)) {
                        Log.d(TAG, "onStart: LOGIN");
                        ActiveUser activeUser = ((ActiveUser) getActivity());
                        activeUser.setActive(user);
                        if (FirestoreDatabase.getInstance().setActiveUser(user)) {
                            successfullyHidAdminOptions();
                            NavDirections action = LoginFragmentDirections.actionLoginFragmentToHomeFragment();
                            Navigation.findNavController(binding.getRoot()).navigate(action);
                        } else {
                            // User cannot make good queries
                            Toast.makeText(getContext(), "User does not have a department", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            } else {
                Log.d(TAG, "db get failed in Login page " + usersTask.getException());
                checkExist = false;
            }
        });
    }
}
Also used : UsersDataModel(com.example.first_responder_app.dataModels.UsersDataModel) EncryptedSharedPreferences(androidx.security.crypto.EncryptedSharedPreferences) SharedPreferences(android.content.SharedPreferences) QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) ActiveUser(com.example.first_responder_app.interfaces.ActiveUser) NavDirections(androidx.navigation.NavDirections)

Example 9 with ActiveUser

use of com.example.first_responder_app.interfaces.ActiveUser in project FirstResponse by mattpost1700.

the class CreateUserFragment method onCreateView.

@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    DrawerLocker drawerLocker = ((DrawerLocker) getActivity());
    if (drawerLocker != null) {
        drawerLocker.setDrawerLocked(true);
    }
    binding = DataBindingUtil.inflate(inflater, R.layout.create_user_fragment, container, false);
    mViewModel = new ViewModelProvider(requireActivity()).get(CreateUserViewModel.class);
    binding.createUserFireDepartmentIdEditText.setText(mViewModel.getFireDepartmentId());
    binding.createUserCreateButton.setOnClickListener(v -> {
        if (validInput()) {
            FirestoreDatabase.getInstance().getDb().collection(FirestoreDatabase.FIRE_DEPARTMENT_COLLECTION_DIR).document(binding.createUserFireDepartmentIdEditText.getText().toString()).get().addOnSuccessListener(documentSnapshot -> {
                if (documentSnapshot.toObject(UsersDataModel.class) != null) {
                    UsersDataModel newUser = new UsersDataModel();
                    fillUser(newUser);
                    FirestoreDatabase.getInstance().getDb().collection(FirestoreDatabase.USERS_COLLECTION_DIR).add(newUser).addOnSuccessListener(documentReference -> {
                        // Success, login
                        if (FirestoreDatabase.getInstance().setActiveUser(newUser)) {
                            newUser.setDocumentId(documentReference.getId());
                            ActiveUser activeUser = ((ActiveUser) getActivity());
                            activeUser.setActive(newUser);
                            NavDirections action = CreateUserFragmentDirections.actionCreateUserFragmentToHomeFragment();
                            Navigation.findNavController(binding.getRoot()).navigate(action);
                        } else {
                            Toast.makeText(getContext(), "User does not have a department", Toast.LENGTH_SHORT).show();
                        }
                    }).addOnFailureListener(e -> Toast.makeText(getContext(), "Failed to upload user. Network error", Toast.LENGTH_SHORT).show());
                } else {
                    Toast.makeText(getContext(), "Fire department does not exist", Toast.LENGTH_SHORT).show();
                }
            }).addOnFailureListener(e -> Toast.makeText(getContext(), "Cannot check for fire department. Network error", Toast.LENGTH_SHORT).show());
        } else {
            Toast.makeText(getContext(), "You must fill all of the text fields", Toast.LENGTH_SHORT).show();
        }
    });
    return binding.getRoot();
}
Also used : UsersDataModel(com.example.first_responder_app.dataModels.UsersDataModel) Bundle(android.os.Bundle) CreateUserViewModel(com.example.first_responder_app.viewModels.CreateUserViewModel) ViewModelProvider(androidx.lifecycle.ViewModelProvider) NavDirections(androidx.navigation.NavDirections) LayoutInflater(android.view.LayoutInflater) NonNull(androidx.annotation.NonNull) FirestoreDatabase(com.example.first_responder_app.FirestoreDatabase) ViewGroup(android.view.ViewGroup) DrawerLocker(com.example.first_responder_app.interfaces.DrawerLocker) R(com.example.first_responder_app.R) ActiveUser(com.example.first_responder_app.interfaces.ActiveUser) Nullable(androidx.annotation.Nullable) Toast(android.widget.Toast) Fragment(androidx.fragment.app.Fragment) View(android.view.View) Navigation(androidx.navigation.Navigation) CreateUserFragmentBinding(com.example.first_responder_app.databinding.CreateUserFragmentBinding) DataBindingUtil(androidx.databinding.DataBindingUtil) UsersDataModel(com.example.first_responder_app.dataModels.UsersDataModel) ActiveUser(com.example.first_responder_app.interfaces.ActiveUser) DrawerLocker(com.example.first_responder_app.interfaces.DrawerLocker) CreateUserViewModel(com.example.first_responder_app.viewModels.CreateUserViewModel) ViewModelProvider(androidx.lifecycle.ViewModelProvider) NavDirections(androidx.navigation.NavDirections)

Example 10 with ActiveUser

use of com.example.first_responder_app.interfaces.ActiveUser in project FirstResponse by mattpost1700.

the class NewEventFragment method onCreateView.

@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    FragmentEventNewBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_event_new, container, false);
    NavHostFragment navHostFragment = (NavHostFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
    // TODO: navCont created for side bar(still need to be implemented)
    NavController navController = navHostFragment.getNavController();
    // switch to Home fragment upon clicking it
    // also if you have any other code relates to onCreateView just add it from here
    mViewModel = new ViewModelProvider(this).get(NewEventViewModel.class);
    firestoreDatabase = new FirestoreDatabase();
    // Open Timepicker when the timepicker button is pressed
    binding.eventTimePicker.setOnClickListener(v -> {
        Log.d("TAG", "onCreateView: CLICKED");
        TimePickerFragment fragment = new TimePickerFragment();
        fragment.setListener(binding.newEventTime::setText);
        fragment.show(getActivity().getSupportFragmentManager(), "Timepicker");
    });
    // Open Datepicker when the datepicker button is pressed
    binding.eventDatePicker.setOnClickListener(v -> {
        Log.d("TAG", "onCreateView: CLICKED");
        DatePickerFragment fragment = new DatePickerFragment();
        fragment.setListener(binding.newEventDate::setText);
        fragment.show(getActivity().getSupportFragmentManager(), "Datepicker");
    });
    binding.eventCreateConfirm.setOnClickListener(v -> {
        // TODO: validate input if needed
        NavDirections action = NewEventFragmentDirections.actionNewEventFragmentToEventGroupFragment();
        String title = binding.newEventTitle.getText().toString();
        String description = binding.newEventDescription.getText().toString();
        String location = binding.newEventLocation.getText().toString();
        String eventDate = binding.newEventDate.getText().toString();
        String eventTime = binding.newEventTime.getText().toString();
        String duration = binding.newEventDurationText.getText().toString();
        // sends the event that includes the following:
        // title, location, description, duration
        Intent intent = new Intent(Intent.ACTION_INSERT);
        intent.setData(CalendarContract.Events.CONTENT_URI);
        intent.putExtra(CalendarContract.Events.TITLE, title);
        intent.putExtra(CalendarContract.Events.EVENT_LOCATION, location);
        intent.putExtra(CalendarContract.Events.DESCRIPTION, description);
        intent.putExtra(CalendarContract.Events.DURATION, duration);
        if (intent.resolveActivity(requireContext().getPackageManager()) != null) {
            startActivity(intent);
        } else {
            Log.d("EVENT INTENT: ", "Event setup Failed");
        }
        if (TextUtils.isEmpty(title) || TextUtils.isEmpty(description) || location.equals("") || eventDate.equals("MM/DD/YYYY") || eventTime.equals("HH:MM") || duration.equals("")) {
            binding.newEventLog.setText(R.string.event_title_description_is_empty);
            binding.newEventLog.setVisibility(View.VISIBLE);
        } else {
            try {
                Date d = new SimpleDateFormat("MM/dd/yyyy hh:mm aa", Locale.getDefault()).parse(eventDate + " " + eventTime);
                ActiveUser a = (ActiveUser) getActivity();
                firestoreDatabase.setActiveUser(a.getActive());
                firestoreDatabase.addEvent(location, title, description, d, Integer.parseInt(duration));
                try {
                    _notificationService.notifyPostReq(getContext(), "events", "New Event", title);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Navigation.findNavController(binding.getRoot()).navigate(action);
            } catch (Exception e) {
                Toast.makeText(requireContext(), "Error Creating Event", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        }
    });
    return binding.getRoot();
}
Also used : NewEventViewModel(com.example.first_responder_app.viewModels.NewEventViewModel) NavController(androidx.navigation.NavController) JSONException(org.json.JSONException) Intent(android.content.Intent) Date(java.util.Date) JSONException(org.json.JSONException) NavDirections(androidx.navigation.NavDirections) ActiveUser(com.example.first_responder_app.interfaces.ActiveUser) FragmentEventNewBinding(com.example.first_responder_app.databinding.FragmentEventNewBinding) NavHostFragment(androidx.navigation.fragment.NavHostFragment) SimpleDateFormat(java.text.SimpleDateFormat) FirestoreDatabase(com.example.first_responder_app.FirestoreDatabase) ViewModelProvider(androidx.lifecycle.ViewModelProvider)

Aggregations

ActiveUser (com.example.first_responder_app.interfaces.ActiveUser)11 UsersDataModel (com.example.first_responder_app.dataModels.UsersDataModel)9 NavDirections (androidx.navigation.NavDirections)7 ViewModelProvider (androidx.lifecycle.ViewModelProvider)6 NavHostFragment (androidx.navigation.fragment.NavHostFragment)6 Bundle (android.os.Bundle)5 View (android.view.View)5 NonNull (androidx.annotation.NonNull)5 NavController (androidx.navigation.NavController)5 FirestoreDatabase (com.example.first_responder_app.FirestoreDatabase)5 TAG (android.content.ContentValues.TAG)4 Log (android.util.Log)4 LayoutInflater (android.view.LayoutInflater)4 ViewGroup (android.view.ViewGroup)4 Toast (android.widget.Toast)4 Nullable (androidx.annotation.Nullable)4 DataBindingUtil (androidx.databinding.DataBindingUtil)4 Navigation (androidx.navigation.Navigation)4 R (com.example.first_responder_app.R)4 QueryDocumentSnapshot (com.google.firebase.firestore.QueryDocumentSnapshot)4