Repository: Ahmed-plusplus/Good_Point Branch: temp2 Commit: 4881376f6f2b Files: 362 Total size: 38.3 MB Directory structure: gitextract_2l0lu64v/ ├── .gitignore ├── .idea/ │ ├── .name │ ├── codeStyles/ │ │ └── Project.xml │ ├── compiler.xml │ ├── gradle.xml │ ├── jarRepositories.xml │ ├── misc.xml │ ├── render.experimental.xml │ ├── runConfigurations.xml │ ├── shelf/ │ │ ├── Uncommitted_changes_before_Update_at_2_13_2021_11_27_PM_[Default_Changelist]/ │ │ │ └── shelved.patch │ │ ├── Uncommitted_changes_before_Update_at_2_13_2021_11_27_PM__Default_Changelist_.xml │ │ └── Uncommitted_changes_before_Update_at_5_26_2021_1_21_AM_[Default_Changelist]/ │ │ └── shelved.patch │ └── vcs.xml ├── README.md ├── app/ │ ├── .gitignore │ ├── .idea/ │ │ └── workspace.xml │ ├── build.gradle │ ├── google-services.json │ ├── proguard-rules.pro │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── com/ │ │ └── helloworld/ │ │ └── goodpoint/ │ │ └── ExampleInstrumentedTest.java │ ├── debug/ │ │ └── res/ │ │ └── values/ │ │ └── google_maps_api.xml │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── assets/ │ │ │ ├── detect.tflite │ │ │ ├── face_model_v5.tflite │ │ │ ├── labelmap.txt │ │ │ └── objectDetection.tflite │ │ ├── java/ │ │ │ ├── com/ │ │ │ │ └── helloworld/ │ │ │ │ └── goodpoint/ │ │ │ │ ├── App.java │ │ │ │ ├── adapter/ │ │ │ │ │ ├── MyExpandableListAdapter.java │ │ │ │ │ └── NotificationListAdapter.java │ │ │ │ ├── detection/ │ │ │ │ │ ├── CameraActivity.java │ │ │ │ │ ├── CameraConnectionFragment.java │ │ │ │ │ ├── DetectorActivity.java │ │ │ │ │ ├── LegacyCameraConnectionFragment.java │ │ │ │ │ ├── customview/ │ │ │ │ │ │ ├── AutoFitTextureView.java │ │ │ │ │ │ ├── OverlayView.java │ │ │ │ │ │ ├── RecognitionScoreView.java │ │ │ │ │ │ └── ResultsView.java │ │ │ │ │ ├── env/ │ │ │ │ │ │ ├── BorderedText.java │ │ │ │ │ │ ├── ImageUtils.java │ │ │ │ │ │ ├── Logger.java │ │ │ │ │ │ └── Size.java │ │ │ │ │ └── tracking/ │ │ │ │ │ └── MultiBoxTracker.java │ │ │ │ ├── pojo/ │ │ │ │ │ ├── FoundItem.java │ │ │ │ │ ├── FoundPerson.java │ │ │ │ │ ├── LostItem.java │ │ │ │ │ ├── LostObject.java │ │ │ │ │ ├── LostPerson.java │ │ │ │ │ ├── NotificationItem.java │ │ │ │ │ ├── ObjectLocation.java │ │ │ │ │ ├── RegUser.java │ │ │ │ │ ├── Token.java │ │ │ │ │ ├── User.java │ │ │ │ │ └── UserMap.java │ │ │ │ ├── retrofit/ │ │ │ │ │ ├── ApiClient.java │ │ │ │ │ ├── ApiInterface.java │ │ │ │ │ └── Decode.java │ │ │ │ ├── ui/ │ │ │ │ │ ├── ActionActivity.java │ │ │ │ │ ├── AdapterOfMatchFragment.java │ │ │ │ │ ├── Alert.java │ │ │ │ │ ├── DetailsActivity.java │ │ │ │ │ ├── ExternalActivity.java │ │ │ │ │ ├── FoundMapFragment.java │ │ │ │ │ ├── GlobalVar.java │ │ │ │ │ ├── HomeActivity.java │ │ │ │ │ ├── HomeFragment.java │ │ │ │ │ ├── ID_cardDetection.java │ │ │ │ │ ├── IdCard.java │ │ │ │ │ ├── MainActivity.java │ │ │ │ │ ├── MatchFragment.java │ │ │ │ │ ├── NotificationActivity.java │ │ │ │ │ ├── PrefManager.java │ │ │ │ │ ├── ProfileFragment.java │ │ │ │ │ ├── SigninActivity.java │ │ │ │ │ ├── SignupActivity.java │ │ │ │ │ ├── SlideAdapter.java │ │ │ │ │ ├── WelcomeActivity.java │ │ │ │ │ ├── candidate/ │ │ │ │ │ │ ├── CandidatePage.java │ │ │ │ │ │ ├── Item.java │ │ │ │ │ │ ├── ItemAdapter.java │ │ │ │ │ │ ├── SubItem.java │ │ │ │ │ │ ├── SubItemAdapter.java │ │ │ │ │ │ └── lostitem.java │ │ │ │ │ ├── check_registration.java │ │ │ │ │ ├── forgetPasswordScreens/ │ │ │ │ │ │ ├── ForgetPassSuccessMessage.java │ │ │ │ │ │ ├── ForgetPasswordWithEmail.java │ │ │ │ │ │ ├── ForgetPasswordWithPhone.java │ │ │ │ │ │ ├── MakeSelection.java │ │ │ │ │ │ ├── SetNewPassword.java │ │ │ │ │ │ └── VerifiyCode.java │ │ │ │ │ ├── lostFoundObject/ │ │ │ │ │ │ ├── FoundObjectActivity.java │ │ │ │ │ │ ├── LostObjectDetailsActivity.java │ │ │ │ │ │ ├── ObjectFragment.java │ │ │ │ │ │ ├── PersonFragment.java │ │ │ │ │ │ └── objectDataType.java │ │ │ │ │ ├── myService/ │ │ │ │ │ │ ├── MyService.java │ │ │ │ │ │ └── NotificationBroadcast.java │ │ │ │ │ ├── prepareList.java │ │ │ │ │ ├── select_multiple_faces/ │ │ │ │ │ │ ├── ItemList.java │ │ │ │ │ │ ├── ItemListAdapter.java │ │ │ │ │ │ ├── Selection.java │ │ │ │ │ │ ├── SubItemList.java │ │ │ │ │ │ └── SubItemListAdapter.java │ │ │ │ │ ├── sub.java │ │ │ │ │ ├── subAdapter.java │ │ │ │ │ └── test.java │ │ │ │ └── utils/ │ │ │ │ └── Draw.java │ │ │ └── fragments/ │ │ │ ├── PageFragment1.java │ │ │ ├── PageFragment2.java │ │ │ └── PageFragment3.java │ │ └── res/ │ │ ├── anim/ │ │ │ └── rotate_splash.xml │ │ ├── drawable/ │ │ │ ├── account_circle.xml │ │ │ ├── active_dot.xml │ │ │ ├── add_new_photo2.xml │ │ │ ├── application_icon.xml │ │ │ ├── application_icon2.xml │ │ │ ├── background.xml │ │ │ ├── background2.xml │ │ │ ├── bottom_sheet_background.xml │ │ │ ├── btn_login.xml │ │ │ ├── buttons.xml │ │ │ ├── circle.xml │ │ │ ├── circle2.xml │ │ │ ├── custom_button.xml │ │ │ ├── custom_button_location.xml │ │ │ ├── default_dot.xml │ │ │ ├── details_background.xml │ │ │ ├── details_btns.xml │ │ │ ├── general_back_icon.xml │ │ │ ├── halfcircle.xml │ │ │ ├── ic_account_circle.xml │ │ │ ├── ic_add.xml │ │ │ ├── ic_background.xml │ │ │ ├── ic_baseline_account_circle_150.xml │ │ │ ├── ic_baseline_account_circle_24.xml │ │ │ ├── ic_baseline_add_a_photo_24.xml │ │ │ ├── ic_baseline_archive_24.xml │ │ │ ├── ic_baseline_assignment_turned_in_24.xml │ │ │ ├── ic_baseline_business_center_24.xml │ │ │ ├── ic_baseline_check_24.xml │ │ │ ├── ic_baseline_check_circle_24.xml │ │ │ ├── ic_baseline_date_range_24.xml │ │ │ ├── ic_baseline_email_24.xml │ │ │ ├── ic_baseline_exit_to_app_24.xml │ │ │ ├── ic_baseline_fact_check_24.xml │ │ │ ├── ic_baseline_feedback_24.xml │ │ │ ├── ic_baseline_gallery_24.xml │ │ │ ├── ic_baseline_help_24.xml │ │ │ ├── ic_baseline_location_on_24.xml │ │ │ ├── ic_baseline_location_on_241.xml │ │ │ ├── ic_baseline_location_on_242.xml │ │ │ ├── ic_baseline_location_on_243.xml │ │ │ ├── ic_baseline_lock_24.xml │ │ │ ├── ic_baseline_navigate_next_24.xml │ │ │ ├── ic_baseline_notifications_24.xml │ │ │ ├── ic_baseline_person_24.xml │ │ │ ├── ic_baseline_phone_android_24.xml │ │ │ ├── ic_baseline_photo_camera_24.xml │ │ │ ├── ic_baseline_remove_red_eye_24.xml │ │ │ ├── ic_baseline_room_24.xml │ │ │ ├── ic_baseline_search_24.xml │ │ │ ├── ic_baseline_search_241.xml │ │ │ ├── ic_baseline_settings_24.xml │ │ │ ├── ic_baseline_share_24.xml │ │ │ ├── ic_baseline_star_rate_24.xml │ │ │ ├── ic_baseline_visibility_24.xml │ │ │ ├── ic_baseline_visibility_off_24.xml │ │ │ ├── ic_close.xml │ │ │ ├── ic_design.xml │ │ │ ├── ic_done.xml │ │ │ ├── ic_found.xml │ │ │ ├── ic_home.xml │ │ │ ├── ic_home_background.xml │ │ │ ├── ic_image.xml │ │ │ ├── ic_launcher_background.xml │ │ │ ├── ic_launcher_background1.xml │ │ │ ├── ic_launcher_foreground.xml │ │ │ ├── ic_location.xml │ │ │ ├── ic_lock.xml │ │ │ ├── ic_lost.xml │ │ │ ├── ic_notification.xml │ │ │ ├── ic_password.xml │ │ │ ├── ic_password_reset.xml │ │ │ ├── ic_photo.xml │ │ │ ├── ic_prof_pic.xml │ │ │ ├── ic_profile.xml │ │ │ ├── ic_realcam.xml │ │ │ ├── ic_rotat_image.xml │ │ │ ├── ic_signup.xml │ │ │ ├── location_signin.xml │ │ │ ├── nav_head_color.xml │ │ │ ├── notification_button1.xml │ │ │ ├── notification_button2.xml │ │ │ ├── oval.xml │ │ │ ├── q_circle.xml │ │ │ ├── radius_expand.xml │ │ │ ├── show_password.xml │ │ │ ├── signin_background.xml │ │ │ ├── switch_icon.xml │ │ │ ├── wave.xml │ │ │ └── white_oval.xml │ │ ├── drawable-mdpi/ │ │ │ └── avd_done.xml │ │ ├── drawable-v24/ │ │ │ └── ic_launcher_foreground.xml │ │ ├── drawable-xxxhdpi/ │ │ │ ├── bottom_sheet_bg.xml │ │ │ ├── ic_baseline_add.xml │ │ │ ├── ic_baseline_remove.xml │ │ │ ├── ic_launcher_background.xml │ │ │ ├── ic_launcher_foreground.xml │ │ │ └── rectangle.xml │ │ ├── font/ │ │ │ ├── muli_black.xml │ │ │ ├── muli_extralight.xml │ │ │ └── roboto_bold.xml │ │ ├── layout/ │ │ │ ├── activity_action.xml │ │ │ ├── activity_candidate_page.xml │ │ │ ├── activity_check_registration.xml │ │ │ ├── activity_details.xml │ │ │ ├── activity_external.xml │ │ │ ├── activity_forget_pass_success_message.xml │ │ │ ├── activity_forget_password.xml │ │ │ ├── activity_forget_password_with_phone.xml │ │ │ ├── activity_found_object.xml │ │ │ ├── activity_home.xml │ │ │ ├── activity_i_d_card_detection.xml │ │ │ ├── activity_item.xml │ │ │ ├── activity_lost_object_details.xml │ │ │ ├── activity_main.xml │ │ │ ├── activity_make_selection.xml │ │ │ ├── activity_notification.xml │ │ │ ├── activity_set_new_password.xml │ │ │ ├── activity_signin.xml │ │ │ ├── activity_signup.xml │ │ │ ├── activity_verifiy_code.xml │ │ │ ├── activity_welcome.xml │ │ │ ├── alert.xml │ │ │ ├── alert_id_card.xml │ │ │ ├── bottom_sheet_dialog.xml │ │ │ ├── child_item.xml │ │ │ ├── custom_map_dialog.xml │ │ │ ├── fragment_home.xml │ │ │ ├── fragment_map.xml │ │ │ ├── fragment_match.xml │ │ │ ├── fragment_object.xml │ │ │ ├── fragment_person.xml │ │ │ ├── fragment_profile.xml │ │ │ ├── group_item.xml │ │ │ ├── head_nav.xml │ │ │ ├── images.xml │ │ │ ├── images_be_removed.xml │ │ │ ├── layout_sub_item.xml │ │ │ ├── layout_sub_list_items.xml │ │ │ ├── multiple_faces_selection.xml │ │ │ ├── notification_item.xml │ │ │ ├── progress_bar_alert.xml │ │ │ ├── r.xml │ │ │ ├── recycler_view_of_images.xml │ │ │ ├── row.xml │ │ │ ├── rr.xml │ │ │ ├── slider_page1.xml │ │ │ ├── slider_page2.xml │ │ │ ├── slider_page3.xml │ │ │ ├── spinner_item.xml │ │ │ ├── tfe_od_activity_camera.xml │ │ │ └── tfe_od_camera_connection_fragment_tracking.xml │ │ ├── layout-land/ │ │ │ ├── activity_action.xml │ │ │ ├── activity_found_object.xml │ │ │ ├── activity_lost_object_details.xml │ │ │ ├── activity_main.xml │ │ │ ├── activity_signin.xml │ │ │ ├── activity_signup.xml │ │ │ ├── activity_welcome.xml │ │ │ ├── fragment_object.xml │ │ │ ├── fragment_person.xml │ │ │ ├── fragment_profile.xml │ │ │ ├── slider_page1.xml │ │ │ ├── slider_page2.xml │ │ │ └── slider_page3.xml │ │ ├── menu/ │ │ │ ├── bottom_nav_menu.xml │ │ │ ├── choose_location.xml │ │ │ ├── choose_photo.xml │ │ │ ├── drawer_menu.xml │ │ │ ├── home_menu.xml │ │ │ └── menu_main.xml │ │ ├── raw/ │ │ │ └── haarcascade_frontalface_alt2.xml │ │ └── values/ │ │ ├── colors.xml │ │ ├── font_certs.xml │ │ ├── preloaded_fonts.xml │ │ ├── strings.xml │ │ └── styles.xml │ ├── release/ │ │ └── res/ │ │ └── values/ │ │ └── google_maps_api.xml │ └── test/ │ └── java/ │ └── com/ │ └── helloworld/ │ └── goodpoint/ │ └── ExampleUnitTest.java ├── backend/ │ ├── .idea/ │ │ ├── .gitignore │ │ ├── inspectionProfiles/ │ │ │ └── profiles_settings.xml │ │ ├── misc.xml │ │ ├── modules.xml │ │ └── vcs.xml │ ├── find_losts/ │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── map.txt │ │ ├── migrations/ │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_alter_matchedperson_percent.py │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── serializers.py │ │ ├── tests.py │ │ ├── url.py │ │ └── views.py │ ├── good_point/ │ │ ├── .idea/ │ │ │ ├── .gitignore │ │ │ ├── inspectionProfiles/ │ │ │ │ └── profiles_settings.xml │ │ │ ├── misc.xml │ │ │ ├── modules.xml │ │ │ ├── vcs.xml │ │ │ └── workspace.xml │ │ ├── __init__.py │ │ ├── asgi.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── manage.py │ ├── notification/ │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations/ │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_notification_user_id.py │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── serializers.py │ │ ├── tests.py │ │ ├── url.py │ │ └── views.py │ └── user_account/ │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations/ │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── serializers.py │ ├── tests.py │ ├── url.py │ └── views.py ├── build.gradle ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── lib_task_api/ │ ├── .gitignore │ ├── build.gradle │ ├── consumer-rules.pro │ ├── proguard-rules.pro │ └── src/ │ ├── main/ │ │ ├── AndroidManifest.xml │ │ └── java/ │ │ └── com/ │ │ └── example/ │ │ └── lib_task_api/ │ │ ├── Detector.java │ │ └── TFLiteObjectDetectionAPIModel.java │ └── test/ │ └── java/ │ └── com/ │ └── example/ │ └── lib_task_api/ │ └── ExampleUnitTest.java ├── mylibrary/ │ ├── .gitignore │ ├── build.gradle │ ├── consumer-rules.pro │ ├── proguard-rules.pro │ └── src/ │ ├── main/ │ │ ├── AndroidManifest.xml │ │ └── java/ │ │ └── com/ │ │ └── example/ │ │ └── lib_task_api/ │ │ ├── Detector.java │ │ └── TFLiteObjectDetectionAPIModel.java │ └── test/ │ └── java/ │ └── com/ │ └── example/ │ └── lib_task_api/ │ └── ExampleUnitTest.java └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.iml .gradle /local.properties /.idea/caches /.idea/libraries /.idea/modules.xml /.idea/workspace.xml /.idea/navEditor.xml /.idea/assetWizardSettings.xml .DS_Store /build /captures .externalNativeBuild .cxx #GoodPoint ================================================ FILE: .idea/.name ================================================ Good Point ================================================ FILE: .idea/codeStyles/Project.xml ================================================
xmlns:android ^$
xmlns:.* ^$ BY_NAME
.*:id http://schemas.android.com/apk/res/android
.*:name http://schemas.android.com/apk/res/android
name ^$
style ^$
.* ^$ BY_NAME
.* http://schemas.android.com/apk/res/android ANDROID_ATTRIBUTE_ORDER
.* .* BY_NAME
================================================ FILE: .idea/compiler.xml ================================================ ================================================ FILE: .idea/gradle.xml ================================================ ================================================ FILE: .idea/jarRepositories.xml ================================================ ================================================ FILE: .idea/misc.xml ================================================ ================================================ FILE: .idea/render.experimental.xml ================================================ ================================================ FILE: .idea/runConfigurations.xml ================================================ ================================================ FILE: .idea/shelf/Uncommitted_changes_before_Update_at_2_13_2021_11_27_PM_[Default_Changelist]/shelved.patch ================================================ Index: backend/.env IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== --- backend/.env (date 1613017568849) +++ backend/.env (date 1613017568849) @@ -0,0 +1,1 @@ +export JWT_SECRET_KEY = '[,]f,dkjSECRET_KEY' \ No newline at end of file ================================================ FILE: .idea/shelf/Uncommitted_changes_before_Update_at_2_13_2021_11_27_PM__Default_Changelist_.xml ================================================ ================================================ FILE: .idea/shelf/Uncommitted_changes_before_Update_at_5_26_2021_1_21_AM_[Default_Changelist]/shelved.patch ================================================ Index: app/src/main/res/layout/fragment_profile.xml IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.BaseRevisionTextPatchEP <+>\r\n\r\n\r\n \r\n\r\n \r\n\r\n \r\n\r\n \r\n\r\n \r\n \r\n\r\n \r\n\r\n \r\n\r\n \r\n \r\n \r\n \r\n\r\n\r\n \r\n\r\n \r\n\r\n \r\n\r\n \r\n \r\n \r\n \r\n\r\n \r\n\r\n \r\n\r\n \r\n\r\n \r\n \r\n \r\n \r\n\r\n \r\n\r\n\r\n \r\n\r\n \r\n \r\n\r\n \r\n \r\n \r\n \r\n \r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n \r\n \r\n \r\n \r\n \r\n\r\n\r\n \r\n Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== --- app/src/main/res/layout/fragment_profile.xml (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ app/src/main/res/layout/fragment_profile.xml (date 1621855100318) @@ -22,8 +22,8 @@ Index: app/src/main/java/com/helloworld/goodpoint/ui/lostFoundObject/FoundObjectActivity.java IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.BaseRevisionTextPatchEP <+>package com.helloworld.goodpoint.ui.lostFoundObject;\r\n\r\nimport android.Manifest;\r\nimport android.annotation.SuppressLint;\r\nimport android.app.AlertDialog;\r\nimport android.app.DatePickerDialog;\r\nimport android.app.Fragment;\r\nimport android.app.FragmentManager;\r\nimport android.app.FragmentTransaction;\r\nimport android.content.Context;\r\nimport android.content.Intent;\r\nimport android.content.pm.PackageManager;\r\nimport android.database.Cursor;\r\nimport android.graphics.Bitmap;\r\nimport android.graphics.Color;\r\nimport android.graphics.drawable.ColorDrawable;\r\nimport android.location.Address;\r\nimport android.location.Geocoder;\r\nimport android.location.Location;\r\nimport android.location.LocationManager;\r\nimport android.net.ConnectivityManager;\r\nimport android.net.NetworkInfo;\r\nimport android.net.Uri;\r\nimport android.net.wifi.WifiManager;\r\nimport android.os.AsyncTask;\r\nimport android.os.Bundle;\r\nimport android.os.Looper;\r\nimport android.provider.MediaStore;\r\nimport android.provider.Settings;\r\nimport android.util.Log;\r\nimport android.util.SparseArray;\r\nimport android.view.MenuItem;\r\nimport android.view.View;\r\nimport android.widget.AutoCompleteTextView;\r\nimport android.widget.Button;\r\nimport android.widget.DatePicker;\r\nimport android.widget.EditText;\r\nimport android.widget.ProgressBar;\r\nimport android.widget.TextView;\r\nimport android.widget.Toast;\r\n\r\nimport androidx.annotation.NonNull;\r\nimport androidx.annotation.Nullable;\r\nimport androidx.appcompat.app.AppCompatActivity;\r\nimport androidx.appcompat.widget.PopupMenu;\r\nimport androidx.core.app.ActivityCompat;\r\nimport androidx.loader.content.CursorLoader;\r\n\r\nimport com.google.android.gms.common.GooglePlayServicesNotAvailableException;\r\nimport com.google.android.gms.common.GooglePlayServicesRepairableException;\r\nimport com.google.android.gms.location.FusedLocationProviderClient;\r\nimport com.google.android.gms.location.LocationCallback;\r\nimport com.google.android.gms.location.LocationRequest;\r\nimport com.google.android.gms.location.LocationResult;\r\nimport com.google.android.gms.location.LocationServices;\r\nimport com.google.android.gms.location.places.Place;\r\nimport com.google.android.gms.location.places.ui.PlacePicker;\r\nimport com.google.android.gms.tasks.OnCompleteListener;\r\nimport com.google.android.gms.tasks.Task;\r\nimport com.google.android.gms.vision.Frame;\r\nimport com.google.android.gms.vision.face.Face;\r\nimport com.google.android.gms.vision.face.FaceDetector;\r\nimport com.google.gson.JsonObject;\r\nimport com.helloworld.goodpoint.R;\r\nimport com.helloworld.goodpoint.pojo.FoundItem;\r\nimport com.helloworld.goodpoint.pojo.FoundPerson;\r\nimport com.helloworld.goodpoint.pojo.LostItem;\r\nimport com.helloworld.goodpoint.pojo.LostPerson;\r\nimport com.helloworld.goodpoint.pojo.User;\r\nimport com.helloworld.goodpoint.retrofit.ApiClient;\r\nimport com.helloworld.goodpoint.retrofit.ApiInterface;\r\nimport com.helloworld.goodpoint.ui.Alert;\r\nimport com.helloworld.goodpoint.ui.GlobalVar;\r\nimport com.helloworld.goodpoint.ui.PrefManager;\r\nimport com.helloworld.goodpoint.ui.prepareList;\r\nimport com.shashank.sony.fancytoastlib.FancyToast;\r\n\r\nimport org.json.JSONException;\r\nimport org.json.JSONObject;\r\n\r\nimport java.io.ByteArrayOutputStream;\r\nimport java.io.File;\r\nimport java.io.IOException;\r\nimport java.util.ArrayList;\r\nimport java.util.Calendar;\r\nimport java.util.List;\r\nimport java.util.Locale;\r\n\r\nimport okhttp3.MediaType;\r\nimport okhttp3.MultipartBody;\r\nimport okhttp3.RequestBody;\r\nimport retrofit2.Call;\r\nimport retrofit2.Callback;\r\nimport retrofit2.Response;\r\n\r\n\r\npublic class FoundObjectActivity extends AppCompatActivity implements View.OnClickListener, objectDataType {\r\n private TextView DateFound;\r\n private EditText Location;\r\n private DatePickerDialog.OnDateSetListener DateSet;\r\n private int year, month, Day;\r\n private Button Person;\r\n private Button Object;\r\n private Button MatchFound;\r\n private prepareList List;\r\n private List listColor;\r\n private Fragment PersonF, ObjectF;\r\n private String location, City;\r\n private String ObjectColor, Serial, brand, textArea_information, Type;\r\n private String PName;\r\n private ProgressBar progressbar;\r\n private WifiManager wifiManager;\r\n private final static int PLACE_PICKER_REQUEST = 999;\r\n private List Person_Images;\r\n double Latitude;\r\n double Longitude;\r\n private FaceDetector faceDetector;\r\n FusedLocationProviderClient fusedLocationProviderClient;\r\n private boolean flagPerson, flagObject;\r\n\r\n @Override\r\n protected void onCreate(Bundle savedInstanceState) {\r\n super.onCreate(savedInstanceState);\r\n setContentView(R.layout.activity_found_object);\r\n Calendar cal = Calendar.getInstance();//To get today's date\r\n inti();\r\n if (savedInstanceState != null) {\r\n year = savedInstanceState.getInt(\"year\");\r\n month = savedInstanceState.getInt(\"month\");\r\n Day = savedInstanceState.getInt(\"Day\");\r\n flagPerson = savedInstanceState.getBoolean(\"flagPerson\");\r\n flagObject = savedInstanceState.getBoolean(\"flagObject\");\r\n if (flagPerson == true) {\r\n Person.setTextColor(0xFFF38E3A);\r\n Object.setTextColor(Color.BLACK);\r\n } else if (flagObject == true) {\r\n Object.setTextColor(0xFFF38E3A);\r\n Person.setTextColor(Color.BLACK);\r\n }\r\n } else {\r\n year = cal.get(Calendar.YEAR);\r\n month = cal.get(Calendar.MONTH);\r\n Day = cal.get(Calendar.DAY_OF_MONTH);\r\n }\r\n //String todayDate = year + \"/\" + (month + 1) + \"/\" + Day;\r\n String todayDate = year + \"-\" + (month + 1) + \"-\" + Day;\r\n DateFound.setText(todayDate);\r\n\r\n DateSet = new DatePickerDialog.OnDateSetListener() {\r\n @Override\r\n public void onDateSet(DatePicker datePicker, int y, int m, int d) {\r\n m++;\r\n if (y > year || (m - 1 > month && y >= year) || (d > Day && m - 1 >= month && y >= year)) {\r\n FancyToast.makeText(FoundObjectActivity.this, \"Invalid date\", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show();\r\n //String todayDate = year + \"/\" + (month + 1) + \"/\" + Day;\r\n String todayDate = year + \"-\" + (month + 1) + \"-\" + Day;\r\n DateFound.setText(todayDate);\r\n } else {\r\n year = y;\r\n month = m - 1;\r\n Day = d;\r\n //String Date = y + \"/\" + m + \"/\" + d;\r\n String Date = y + \"-\" + m + \"-\" + d;\r\n DateFound.setText(Date);\r\n }\r\n }\r\n };\r\n }\r\n\r\n @Override\r\n protected void onStart() {\r\n super.onStart();\r\n fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(FoundObjectActivity.this);\r\n if (ActivityCompat.checkSelfPermission(FoundObjectActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED\r\n && ActivityCompat.checkSelfPermission(FoundObjectActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {\r\n ActivityCompat.requestPermissions(FoundObjectActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 12);\r\n } else {\r\n getCurrentLocation();\r\n }\r\n }\r\n\r\n @Override\r\n public void onClick(View view) {\r\n FragmentManager FM = getFragmentManager();\r\n FragmentTransaction FT = FM.beginTransaction();\r\n switch (view.getId()) {\r\n case R.id.DateFound:\r\n DatePickerDialog dialog = new DatePickerDialog(\r\n FoundObjectActivity.this,\r\n android.R.style.Theme_Holo_Light_Dialog_MinWidth,\r\n DateSet,\r\n year, month, Day\r\n );\r\n dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));\r\n dialog.show();\r\n break;\r\n case R.id.FoundLocatin:\r\n PopupMenu popupMenu = new PopupMenu(this, view);\r\n popupMenu.getMenuInflater().inflate(R.menu.choose_location, popupMenu.getMenu());\r\n popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {\r\n @Override\r\n public boolean onMenuItemClick(MenuItem item) {\r\n if (ActivityCompat.checkSelfPermission(FoundObjectActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED\r\n && ActivityCompat.checkSelfPermission(FoundObjectActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {\r\n ActivityCompat.requestPermissions(FoundObjectActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 12);\r\n } else {\r\n switch (item.getItemId()) {\r\n case R.id.TakeCurrLocation:\r\n isInternetAvailable Available = new isInternetAvailable();\r\n Available.execute();\r\n CurrentLocation Locate = new CurrentLocation();\r\n Locate.execute();\r\n break;\r\n case R.id.DeteLocation:\r\n boolean flag = false;\r\n wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);\r\n if (wifiManager.isWifiEnabled())\r\n wifiManager.setWifiEnabled(false);\r\n else {\r\n flag = true;\r\n }\r\n PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();\r\n try {\r\n Intent intent = builder.build(FoundObjectActivity.this);\r\n startActivityForResult(intent, PLACE_PICKER_REQUEST);\r\n if (!flag) wifiManager.setWifiEnabled(true);\r\n } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {\r\n e.printStackTrace();\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n }\r\n break;\r\n }\r\n }\r\n return true;\r\n }\r\n });\r\n popupMenu.show();\r\n break;\r\n case R.id.PersonFound:\r\n flagPerson = true;\r\n flagObject = false;\r\n FT.replace(R.id.FragmentFoundID, PersonF, null);\r\n Person.setTextColor(0xFFF38E3A);\r\n Object.setTextColor(Color.BLACK);\r\n\r\n FT.commit();\r\n break;\r\n case R.id.ObjectFound:\r\n flagObject = true;\r\n flagPerson = false;\r\n FT.replace(R.id.FragmentFoundID, ObjectF, null);\r\n Object.setTextColor(0xFFF38E3A);\r\n Person.setTextColor(Color.BLACK);\r\n\r\n FT.commit();\r\n break;\r\n case R.id.MatchFound:\r\n GlobalVar.allFaces.clear();\r\n if (!flagObject && !flagPerson) {\r\n FancyToast.makeText(this, \"Specify the type of the missing object\", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show();\r\n } else if (flagObject && CheckMatchObject()) {\r\n FoundItems();\r\n FancyToast.makeText(this, \"The data has been saved successfully\", FancyToast.LENGTH_LONG, FancyToast.SUCCESS, false).show();\r\n finish();\r\n } else if (flagPerson && CheckMatchPerson()) {\r\n faceDetector = new FaceDetector.Builder(this)\r\n .setTrackingEnabled(false)\r\n .setLandmarkType(FaceDetector.ALL_LANDMARKS)\r\n .setMode(FaceDetector.FAST_MODE).build();\r\n if (!faceDetector.isOperational()) {\r\n Toast.makeText(this, \"Face Detection can't be setup\", Toast.LENGTH_SHORT).show();\r\n }\r\n checkFaces N = new checkFaces(this);\r\n N.execute();\r\n }\r\n break;\r\n }\r\n }\r\n\r\n private boolean CheckMatchPerson() {\r\n EditText PersonName = PersonF.getView().findViewById(R.id.PersonName);\r\n PName = PersonName.getText().toString();\r\n location = Location.getText().toString();\r\n if (location.isEmpty()) {\r\n FancyToast.makeText(this, \"Specify where you found this object\", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show();\r\n return false;\r\n } else if (Person_Images.size() == 0) {\r\n FancyToast.makeText(this, \"You must put at least one picture!\", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show();\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n class checkFaces extends AsyncTask {\r\n AlertDialog.Builder builder;\r\n AlertDialog dialog;\r\n Context context;\r\n\r\n private checkFaces(Context context) {\r\n this.context = context.getApplicationContext();\r\n builder = new AlertDialog.Builder(FoundObjectActivity.this);\r\n }\r\n\r\n @Override\r\n protected void onPreExecute() {\r\n super.onPreExecute();\r\n builder.setCancelable(false);\r\n View view = getLayoutInflater().inflate(R.layout.progress_bar_alert, null);\r\n builder.setView(view);\r\n dialog = builder.create();\r\n dialog.show();\r\n }\r\n\r\n @Override\r\n protected void onPostExecute(Void a) {\r\n super.onPostExecute(a);\r\n Log.e(\"img\", \"onPostExecute: \" + GlobalVar.ImgThatHaveMoreThanOneFace.size() + \" \" + GlobalVar.FinialFacesThatWillGoToDataBase.size());\r\n if (GlobalVar.allFaces.size() > 0) {\r\n startActivity(new Intent(FoundObjectActivity.this, Alert.class));\r\n finish();\r\n\r\n } else {\r\n FancyToast.makeText(FoundObjectActivity.this, \"The data has been saved successfully\", FancyToast.LENGTH_LONG, FancyToast.SUCCESS, false).show();\r\n finish();\r\n }\r\n dialog.dismiss();\r\n FoundPerson();\r\n\r\n }\r\n\r\n @Override\r\n protected Void doInBackground(Void... voids) {\r\n GlobalVar.ImgThatHaveMoreThanOneFace.clear();\r\n GlobalVar.FinialFacesThatWillGoToDataBase.clear();\r\n GlobalVar.allFaces.clear();\r\n boolean flag = false;\r\n for (int i = 0; i < Person_Images.size(); i++) {\r\n Bitmap My = Person_Images.get(i);\r\n Bitmap faceBitmap;\r\n List faces = new ArrayList<>();//In one Img;\r\n Frame frame = new Frame.Builder().setBitmap(My).build();\r\n SparseArray sparseArray = faceDetector.detect(frame);\r\n for (int j = 0; j < sparseArray.size(); j++) {\r\n flag = false;\r\n Face face = sparseArray.valueAt(j);\r\n if (((int) face.getPosition().y + (int) face.getHeight()) > My.getHeight()) {\r\n int H = My.getHeight() - (int) face.getPosition().y;\r\n faceBitmap = Bitmap.createBitmap(My, (int) face.getPosition().x, (int) face.getPosition().y, (int) face.getWidth(), H);\r\n } else if (((int) face.getPosition().x + (int) face.getWidth()) > My.getWidth()) {\r\n int W = My.getWidth() - (int) face.getPosition().x;\r\n faceBitmap = Bitmap.createBitmap(My, (int) face.getPosition().x, (int) face.getPosition().y, W, (int) face.getHeight());\r\n } else if ((((int) face.getPosition().x + (int) face.getWidth()) > My.getWidth()) && (((int) face.getPosition().y + (int) face.getHeight()) > My.getHeight())) {\r\n int H = My.getHeight() - (int) face.getPosition().y;\r\n int W = My.getWidth() - (int) face.getPosition().x;\r\n faceBitmap = Bitmap.createBitmap(My, (int) face.getPosition().x, (int) face.getPosition().y, W, H);\r\n } else {\r\n faceBitmap = Bitmap.createBitmap(My, (int) face.getPosition().x, (int) face.getPosition().y, (int) face.getWidth(), (int) face.getHeight());\r\n\r\n }\r\n if (sparseArray.size() == 1) {\r\n GlobalVar.FinialFacesThatWillGoToDataBase.add(faceBitmap);\r\n flag = true;\r\n } else {\r\n faces.add(faceBitmap);\r\n }\r\n }\r\n if (!flag) {\r\n GlobalVar.ImgThatHaveMoreThanOneFace.add(My);\r\n GlobalVar.allFaces.add(faces);\r\n }\r\n\r\n }\r\n return null;\r\n }\r\n }\r\n\r\n private boolean CheckMatchObject() {\r\n location = Location.getText().toString();\r\n AutoCompleteTextView V = ObjectF.getView().findViewById(R.id.ColorOfObject);\r\n EditText serialObject = ObjectF.getView().findViewById(R.id.Serial);\r\n EditText brandObject = ObjectF.getView().findViewById(R.id.brand);\r\n EditText textArea_informationObject = ObjectF.getView().findViewById(R.id.textArea_information);\r\n EditText TypeObject;\r\n\r\n ObjectColor = V.getText().toString();\r\n Serial = serialObject.getText().toString();\r\n brand = brandObject.getText().toString();\r\n textArea_information = textArea_informationObject.getText().toString();\r\n if (location.isEmpty()) {\r\n FancyToast.makeText(this, \"Specify where you found this object\", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show();\r\n return false;\r\n } else if (Type.equals(\"Type\")) {\r\n FancyToast.makeText(this, \"You must Choose the Type!\", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show();\r\n return false;\r\n } else if (Type.equals(\"Others\")) {\r\n TypeObject = ObjectF.getView().findViewById(R.id.Other);\r\n if (TypeObject.getText().toString().isEmpty()) {\r\n TypeObject.setError(\"Field can't be empty\");\r\n return false;\r\n } else {\r\n Type = TypeObject.getText().toString();\r\n }\r\n } else if (brand.isEmpty()) {\r\n brandObject.setError(\"Field can't be empty\");\r\n return false;\r\n } else if (ObjectColor.isEmpty()) {\r\n V.setError(\"Field can't be empty\");\r\n return false;\r\n } else if (!listColor.contains(ObjectColor.trim())) {\r\n V.setError(\"Color isn't known!\");\r\n return false;\r\n } else if (textArea_information.isEmpty()) {\r\n textArea_informationObject.setError(\"Field can't be empty\");\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n @Override\r\n protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {\r\n super.onActivityResult(requestCode, resultCode, data);\r\n if (requestCode == PLACE_PICKER_REQUEST && resultCode == RESULT_OK) {\r\n Place place = PlacePicker.getPlace(data, this);\r\n StringBuilder stringBuilder = new StringBuilder();\r\n Latitude = place.getLatLng().latitude;\r\n Longitude = place.getLatLng().longitude;\r\n isInternetAvailable Available = new isInternetAvailable();\r\n Available.execute();\r\n CurrentLocation Locate = new CurrentLocation();\r\n Locate.execute();\r\n }\r\n }\r\n\r\n @Override\r\n public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {\r\n if (requestCode == 12 && (grantResults.length > 0) &&\r\n grantResults[0] == PackageManager.PERMISSION_GRANTED) {\r\n getCurrentLocation();\r\n } else if (requestCode == 12 && (grantResults.length > 0) &&\r\n grantResults[0] == PackageManager.PERMISSION_DENIED) {\r\n\r\n FancyToast.makeText(this, \"Permission denied\", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show();\r\n } else if (requestCode == 11 && (grantResults.length > 0) &&\r\n grantResults[0] == PackageManager.PERMISSION_DENIED) {\r\n FancyToast.makeText(this, \"Permission denied\", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show();\r\n }\r\n\r\n }\r\n\r\n @SuppressLint(\"MissingPermission\")\r\n private void getCurrentLocation() {\r\n LocationManager locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);\r\n\r\n if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)\r\n || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)\r\n ) {\r\n fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener() {\r\n @SuppressLint(\"MissingPermission\")\r\n @Override\r\n public void onComplete(@NonNull Task task) {\r\n Location location = task.getResult();\r\n if (location != null) {\r\n Longitude = location.getLongitude();\r\n Latitude = location.getLatitude();\r\n } else {\r\n @SuppressLint(\"RestrictedApi\") LocationRequest locationRequest = new LocationRequest()\r\n .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)\r\n .setInterval(10000)\r\n .setFastestInterval(1000)\r\n .setNumUpdates(1);\r\n LocationCallback locationCallback = new LocationCallback() {\r\n @Override\r\n public void onLocationResult(LocationResult locationResult) {\r\n Location location1 = locationResult.getLastLocation();\r\n Longitude = location1.getLongitude();\r\n Latitude = location1.getLatitude();\r\n }\r\n };\r\n fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());\r\n\r\n }\r\n }\r\n });\r\n } else {\r\n //when location servies is not enabled\r\n //open location setting\r\n startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));\r\n }\r\n }\r\n\r\n class CurrentLocation extends AsyncTask {\r\n\r\n @Override\r\n protected void onPreExecute() {\r\n super.onPreExecute();\r\n progressbar.setVisibility(View.VISIBLE);\r\n }\r\n\r\n @Override\r\n protected void onPostExecute(String Locate) {\r\n super.onPostExecute(Locate);\r\n if (Locate.isEmpty())\r\n FancyToast.makeText(FoundObjectActivity.this, \"An error has occurred , please try again\", FancyToast.LENGTH_LONG, FancyToast.WARNING, false).show();\r\n Location.setText(Locate);\r\n progressbar.setVisibility(View.GONE);\r\n }\r\n\r\n @Override\r\n protected String doInBackground(Void... voids) {\r\n Geocoder geocoder = new Geocoder(FoundObjectActivity.this, new Locale(\"en\"));\r\n String Locate = \"\";\r\n try {\r\n List
addresses = geocoder.getFromLocation(Latitude, Longitude, 1);\r\n String Country = addresses.get(0).getCountryName();\r\n String CityG = addresses.get(0).getAdminArea();\r\n City = CityG.substring(0, CityG.lastIndexOf(' '));\r\n String area = addresses.get(0).getLocality();\r\n Locate = area + \",\" + CityG + \",\" + Country + \".\";\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n }\r\n return Locate;\r\n }\r\n\r\n }\r\n\r\n public boolean isNetworkAvailable(Context context) {\r\n ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);\r\n NetworkInfo nInfo = cm.getActiveNetworkInfo();\r\n boolean connected = nInfo != null && nInfo.isAvailable() && nInfo.isConnected();\r\n return connected;\r\n }\r\n\r\n class isInternetAvailable extends AsyncTask {\r\n\r\n @Override\r\n protected void onPreExecute() {\r\n super.onPreExecute();\r\n progressbar.setVisibility(View.VISIBLE);\r\n }\r\n\r\n @Override\r\n protected void onPostExecute(Boolean aBoolean) {\r\n super.onPostExecute(aBoolean);\r\n progressbar.setVisibility(View.GONE);\r\n if (!aBoolean)\r\n FancyToast.makeText(FoundObjectActivity.this, \"No Internet Connection\", FancyToast.LENGTH_LONG, FancyToast.WARNING, false).show();\r\n }\r\n\r\n @Override\r\n protected Boolean doInBackground(Void... voids) {\r\n Boolean flag;\r\n try {\r\n String command = \"ping -c 1 google.com\";\r\n flag = (Runtime.getRuntime().exec(command).waitFor() == 0);\r\n } catch (Exception e) {\r\n flag = false;\r\n }\r\n return flag;\r\n }\r\n }\r\n\r\n protected void inti() {\r\n\r\n DateFound = findViewById(R.id.DateFound);\r\n progressbar = findViewById(R.id.ProgressBar);\r\n Button foundLocatin = findViewById(R.id.FoundLocatin);\r\n Person = findViewById(R.id.PersonFound);\r\n Object = findViewById(R.id.ObjectFound);\r\n MatchFound = findViewById(R.id.MatchFound);\r\n Location = findViewById(R.id.Location);\r\n DateFound.setOnClickListener(this);\r\n foundLocatin.setOnClickListener(this);\r\n Person.setOnClickListener(this);\r\n Object.setOnClickListener(this);\r\n MatchFound.setOnClickListener(this);\r\n PersonF = new PersonFragment();\r\n ObjectF = new ObjectFragment();\r\n List = new prepareList();\r\n listColor = List.prepareListColor(this);\r\n\r\n }\r\n\r\n @Override\r\n public void getType(String T) {\r\n Type = T;\r\n }\r\n\r\n @Override\r\n public void getImageCheck(Boolean check) {\r\n }\r\n\r\n @Override\r\n public void getBitmap_Image(Bitmap Bitmap_Image) {\r\n }\r\n\r\n @Override\r\n public void getBitmap_ImagePersonImages(List PImages) {\r\n Person_Images = PImages;\r\n Log.e(\"img\", \"getBitmap_ImagePersonImages: Hi \" + Person_Images.size());\r\n }\r\n\r\n @Override\r\n public void onSaveInstanceState(@NonNull Bundle outState) {\r\n super.onSaveInstanceState(outState);\r\n\r\n outState.putInt(\"year\", year);\r\n outState.putInt(\"month\", month);\r\n outState.putInt(\"Day\", Day);\r\n outState.putBoolean(\"flagPerson\", flagPerson);\r\n outState.putBoolean(\"flagObject\", flagObject);\r\n }\r\n\r\n/*\r\n public Uri getImageUri(Bitmap bitmap_Image) {\r\n ByteArrayOutputStream bytes = new ByteArrayOutputStream();\r\n bitmap_Image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);\r\n String path = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap_Image, \"LostItem\", null);\r\n return Uri.parse(path);\r\n }\r\n\r\n private String getRealPathFromURI(Uri imageUri) {\r\n String[] proj = {MediaStore.Images.Media.DATA};\r\n CursorLoader loader = new CursorLoader(this, imageUri, proj, null, null, null);\r\n Cursor cursor = loader.loadInBackground();\r\n int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);\r\n cursor.moveToFirst();\r\n String result = cursor.getString(column_index);\r\n cursor.close();\r\n return result;\r\n }\r\n*/\r\n\r\n public void FoundItems() {\r\n\r\n String Datee = DateFound.getText().toString().trim();\r\n ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class);\r\n\r\n Call call = apiInterface.storeFoundObj(User.getUser().getId(), Datee, City, Longitude , Latitude);\r\n call.enqueue(new Callback() {\r\n @Override\r\n public void onResponse(Call call, Response response) {\r\n if (response.isSuccessful()) {\r\n\r\n try {\r\n JSONObject jsonObject = new JSONObject(response.body().toString());\r\n String id = jsonObject.getString(\"id\");\r\n Toast.makeText(FoundObjectActivity.this, \"Object is posted.\", Toast.LENGTH_SHORT).show();\r\n\r\n\r\n Call call2 = apiInterface.storeFoundItem(id, Type, Serial, brand, ObjectColor, textArea_information);\r\n call2.enqueue(new Callback() {\r\n @Override\r\n public void onResponse(Call call, Response response) {\r\n if (response.isSuccessful()) {\r\n Toast.makeText(FoundObjectActivity.this, \"Item is posted.\", Toast.LENGTH_SHORT).show();\r\n } else\r\n Toast.makeText(FoundObjectActivity.this, \"The item is not posted.\", Toast.LENGTH_SHORT).show();\r\n }\r\n\r\n @Override\r\n public void onFailure(Call call, Throwable t) {\r\n Toast.makeText(FoundObjectActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();\r\n }\r\n });\r\n\r\n\r\n } catch (JSONException e) {\r\n e.printStackTrace();\r\n }\r\n\r\n } else\r\n Toast.makeText(FoundObjectActivity.this, \"Objec is not posted.\", Toast.LENGTH_SHORT).show();\r\n }\r\n\r\n @Override\r\n public void onFailure(Call call, Throwable t) {\r\n Toast.makeText(FoundObjectActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();\r\n }\r\n });\r\n\r\n }\r\n\r\n public Uri getImageUri(Bitmap bitmap_Image) {\r\n ByteArrayOutputStream bytes = new ByteArrayOutputStream();\r\n bitmap_Image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);\r\n String path = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap_Image, \"LostItem\", null);\r\n return Uri.parse(path);\r\n }\r\n\r\n private String getRealPathFromURI(Uri imageUri) {\r\n String[] proj = {MediaStore.Images.Media.DATA};\r\n CursorLoader loader = new CursorLoader(this, imageUri, proj, null, null, null);\r\n Cursor cursor = loader.loadInBackground();\r\n int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);\r\n cursor.moveToFirst();\r\n String result = cursor.getString(column_index);\r\n cursor.close();\r\n return result;\r\n }\r\n\r\n public void FoundPerson()\r\n {\r\n\r\n String Datee = DateFound.getText().toString().trim();\r\n ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class);\r\n\r\n Uri imageURI = getImageUri(Person_Images.get(0));\r\n File file = new File(getRealPathFromURI(imageURI));\r\n RequestBody requestBody = RequestBody.create(MediaType.parse(\"multipart/form-data\"), file);\r\n MultipartBody.Part Pimage = MultipartBody.Part.createFormData(\"image\", file.getName(), requestBody);\r\n\r\n Call call = apiInterface.storeFoundPerson(User.getUser().getId(), Datee, City, Longitude , Latitude, PName, Pimage);\r\n call.enqueue(new Callback() {\r\n @Override\r\n public void onResponse(Call call, Response response) {\r\n if(response.isSuccessful()) {\r\n Toast.makeText(FoundObjectActivity.this, \"The object posted.\", Toast.LENGTH_SHORT).show();\r\n }else\r\n Toast.makeText(FoundObjectActivity.this, \"The object is not posted.\", Toast.LENGTH_SHORT).show();\r\n\r\n }\r\n\r\n @Override\r\n public void onFailure(Call call, Throwable t) {\r\n Toast.makeText(FoundObjectActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();\r\n }\r\n });\r\n\r\n\r\n }\r\n\r\n\r\n\r\n\r\n\r\n} Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== --- app/src/main/java/com/helloworld/goodpoint/ui/lostFoundObject/FoundObjectActivity.java (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ app/src/main/java/com/helloworld/goodpoint/ui/lostFoundObject/FoundObjectActivity.java (date 1621852290573) @@ -514,7 +514,11 @@ List
addresses = geocoder.getFromLocation(Latitude, Longitude, 1); String Country = addresses.get(0).getCountryName(); String CityG = addresses.get(0).getAdminArea(); - City = CityG.substring(0, CityG.lastIndexOf(' ')); + int index = CityG.lastIndexOf(' '); + if(index == -1) + City = CityG; + else + City = CityG.substring(0, index); String area = addresses.get(0).getLocality(); Locate = area + "," + CityG + "," + Country + "."; } catch (IOException e) { Index: app/src/main/java/com/helloworld/goodpoint/retrofit/ApiInterface.java IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.BaseRevisionTextPatchEP <+>package com.helloworld.goodpoint.retrofit;\r\n\r\nimport com.google.gson.JsonObject;\r\nimport com.helloworld.goodpoint.pojo.FoundItem;\r\nimport com.helloworld.goodpoint.pojo.FoundPerson;\r\nimport com.helloworld.goodpoint.pojo.LostItem;\r\nimport com.helloworld.goodpoint.pojo.LostPerson;\r\nimport com.helloworld.goodpoint.pojo.ObjectLocation;\r\nimport com.helloworld.goodpoint.pojo.RegUser;\r\nimport com.helloworld.goodpoint.pojo.Token;\r\nimport com.helloworld.goodpoint.pojo.User;\r\nimport com.helloworld.goodpoint.pojo.UserMap;\r\n\r\nimport org.json.JSONObject;\r\n\r\nimport java.util.List;\r\n\r\nimport okhttp3.MultipartBody;\r\nimport okhttp3.RequestBody;\r\nimport okhttp3.ResponseBody;\r\nimport retrofit2.Call;\r\nimport retrofit2.http.Body;\r\nimport retrofit2.http.Field;\r\nimport retrofit2.http.FormUrlEncoded;\r\nimport retrofit2.http.GET;\r\nimport retrofit2.http.Header;\r\nimport retrofit2.http.Headers;\r\nimport retrofit2.http.Multipart;\r\nimport retrofit2.http.POST;\r\nimport retrofit2.http.Part;\r\nimport retrofit2.http.Path;\r\nimport retrofit2.http.Query;\r\n\r\npublic interface ApiInterface {\r\n\r\n @FormUrlEncoded\r\n @POST(\"auth/signup/\")\r\n Call storePost(@Field(\"username\") String emailInput\r\n , @Field(\"password\") String passwordInput, @Field(\"first_name\") String usernameInput\r\n , @Field(\"phone\") String pInput, @Field(\"city\") String cityInput\r\n , @Field(\"birthdate\") String Datee);\r\n\r\n\r\n @Multipart\r\n @POST(\"auth/signup/\")\r\n Call storePost(@Part(\"username\") String emailInput\r\n , @Part(\"password\") String passwordInput, @Part(\"first_name\") String usernameInput\r\n , @Part(\"phone\") String pInput, @Part(\"city\") String cityInput\r\n , @Part(\"birthdate\") String Datee, @Part MultipartBody.Part profile_pic);\r\n\r\n\r\n @FormUrlEncoded\r\n @POST(\"api/token/\")\r\n Call getToken(@Field(\"username\") String emailInput, @Field(\"password\") String passwordInput);\r\n\r\n @FormUrlEncoded\r\n @POST(\"api/token/refresh/\")\r\n Call refresh(@Field(\"refresh\") String refresh);\r\n\r\n\r\n @POST(\"auth/signin/\")\r\n Call getData(@Header(\"Authorization\") String token);\r\n\r\n //----------------------------------------------------------------------------------------------\r\n\r\n @FormUrlEncoded\r\n @POST(\"losts/lostobject/\")\r\n Call storeLostObj(@Field(\"user_id\") String id, @Field(\"date\") String Datee, @Field(\"city\") String cityInput);\r\n\r\n @FormUrlEncoded\r\n @POST(\"losts/lostitem/\")\r\n Call storeLostItem(@Field(\"id\") String obj_id, @Field(\"type\") String Type, @Field(\"serial_number\") String Serial\r\n , @Field(\"brand\") String brand, @Field(\"color\") String ObjectColor\r\n , @Field(\"description\") String textArea_information);\r\n\r\n @Multipart\r\n @POST(\"losts/lostitem/\")\r\n Call storeLostItem(@Part(\"id\") String obj_id, @Part(\"type\") String Type, @Part(\"serial_number\") String Serial\r\n , @Part(\"brand\") String brand, @Part(\"color\") String ObjectColor\r\n , @Part(\"description\") String textArea_information, @Part MultipartBody.Part image);\r\n\r\n @Multipart\r\n @POST(\"losts/lostperson/\")\r\n Call storeLostPerson(@Part(\"date\") String Date, @Part(\"city\") String city, @Part(\"user_id\") String user_id\r\n , @Part(\"name\") String name, @Part MultipartBody.Part images);\r\n\r\n\r\n @Multipart\r\n @POST(\"losts/lostperson_image/\")\r\n Call storeLostPersonImage(@Part(\"id\") String person_id/*, @Part MultipartBody.Part image*/);\r\n //----------------------------------------------------------------------------------------------\r\n\r\n @FormUrlEncoded\r\n @POST(\"losts/foundobject/\")\r\n Call storeFoundObj(@Field(\"user_id\") String id, @Field(\"date\") String Datee, @Field(\"city\") String cityInput\r\n , @Field(\"longitude\") double longitude, @Field(\"latitude\") double latitude);\r\n\r\n @FormUrlEncoded\r\n @POST(\"losts/founditem/\")\r\n Call storeFoundItem(@Field(\"id\") String obj_id, @Field(\"type\") String Type, @Field(\"serial_number\") String Serial\r\n , @Field(\"brand\") String brand, @Field(\"color\") String ObjectColor\r\n , @Field(\"description\") String textArea_information);\r\n\r\n @FormUrlEncoded\r\n @POST(\"losts/foundperson/\")\r\n Call storeFoundPerson(@Field(\"user_id\") String id, @Field(\"date\") String Datee, @Field(\"city\") String cityInput\r\n , @Field(\"longitude\") double longitude, @Field(\"latitude\") double latitude, @Field(\"name\") String name\r\n , @Part MultipartBody.Part image);\r\n\r\n @Multipart\r\n @POST(\"losts/foundperson_image/\")\r\n Call storeFoundPersonImage(@Part(\"id\") String person_id/*, @Part MultipartBody.Part image*/);\r\n\r\n //----------------------------------------------------------------------------------------------\r\n\r\n @GET(\"losts/map/\")\r\n Call> getPoint();\r\n\r\n @GET(\"losts/founder/{id}\")\r\n Call getUserMap(@Path(\"id\") int id);\r\n\r\n\r\n\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== --- app/src/main/java/com/helloworld/goodpoint/retrofit/ApiInterface.java (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ app/src/main/java/com/helloworld/goodpoint/retrofit/ApiInterface.java (date 1621853230298) @@ -101,10 +101,10 @@ , @Field("brand") String brand, @Field("color") String ObjectColor , @Field("description") String textArea_information); - @FormUrlEncoded + @Multipart @POST("losts/foundperson/") - Call storeFoundPerson(@Field("user_id") String id, @Field("date") String Datee, @Field("city") String cityInput - , @Field("longitude") double longitude, @Field("latitude") double latitude, @Field("name") String name + Call storeFoundPerson(@Part("user_id") String id, @Part("date") String Datee, @Part("city") String cityInput + , @Part("longitude") Double longitude, @Part("latitude") Double latitude, @Part("name") String name , @Part MultipartBody.Part image); @Multipart Index: app/src/main/java/com/helloworld/goodpoint/ui/HomeActivity.java IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.BaseRevisionTextPatchEP <+>package com.helloworld.goodpoint.ui;\r\nimport androidx.annotation.NonNull;\r\nimport androidx.appcompat.app.ActionBarDrawerToggle;\r\nimport androidx.appcompat.app.AlertDialog;\r\nimport androidx.appcompat.app.AppCompatActivity;\r\nimport androidx.appcompat.widget.Toolbar;\r\nimport androidx.core.view.GravityCompat;\r\nimport androidx.drawerlayout.widget.DrawerLayout;\r\nimport androidx.fragment.app.Fragment;\r\nimport android.content.DialogInterface;\r\nimport android.content.Intent;\r\nimport android.graphics.Bitmap;\r\nimport android.graphics.BitmapFactory;\r\nimport android.graphics.Color;\r\nimport android.graphics.PorterDuff;\r\nimport android.os.AsyncTask;\r\nimport android.os.Bundle;\r\nimport android.util.Log;\r\nimport android.view.LayoutInflater;\r\nimport android.view.Menu;\r\nimport android.view.MenuItem;\r\nimport android.view.View;\r\nimport android.widget.EditText;\r\nimport android.widget.LinearLayout;\r\nimport android.widget.TextView;\r\nimport android.widget.Toast;\r\n\r\nimport com.google.android.material.bottomnavigation.BottomNavigationView;\r\nimport com.google.android.material.bottomsheet.BottomSheetDialog;\r\nimport com.google.android.material.floatingactionbutton.FloatingActionButton;\r\nimport com.google.android.material.navigation.NavigationView;\r\nimport com.helloworld.goodpoint.R;\r\nimport com.helloworld.goodpoint.pojo.RegUser;\r\nimport com.helloworld.goodpoint.pojo.User;\r\nimport com.helloworld.goodpoint.ui.lostFoundObject.FoundObjectActivity;\r\nimport com.helloworld.goodpoint.ui.lostFoundObject.LostObjectDetailsActivity;\r\n\r\nimport java.io.IOException;\r\nimport java.io.InputStream;\r\nimport java.net.HttpURLConnection;\r\nimport java.net.MalformedURLException;\r\nimport java.net.URL;\r\n\r\nimport de.hdodenhof.circleimageview.CircleImageView;\r\n\r\npublic class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {\r\n DrawerLayout drawerLayout;\r\n NavigationView navigationView;\r\n Toolbar toolbar;\r\n AlertDialog.Builder dialog;\r\n BottomNavigationView bottomNavigationView;\r\n FloatingActionButton fab;\r\n Fragment fhome, fmatch, fprofile;\r\n TextView namenavigator;\r\n TextView mailnavigator;\r\n CircleImageView imgnavigator;\r\n\r\n @Override\r\n protected void onCreate(Bundle savedInstanceState) {\r\n super.onCreate(savedInstanceState);\r\n setContentView(R.layout.activity_home);\r\n\r\n init();\r\n setToolBarAndDrawer();\r\n setBottomNavigator();\r\n\r\n if(savedInstanceState == null) {\r\n //To make first fragment is home when opening the app\r\n getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fhome).commit();\r\n }\r\n\r\n }\r\n\r\n private void setBottomNavigator() {\r\n bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);\r\n fab = (FloatingActionButton) findViewById(R.id.fab);\r\n\r\n //To Disable item under Fab\r\n Menu menuNav=bottomNavigationView.getMenu();\r\n MenuItem nav_item2 = menuNav.findItem(R.id.placeholder);\r\n nav_item2.setEnabled(false);\r\n\r\n bottomNavigationView.setBackgroundColor(0); //To hide the color of nav view\r\n bottomNavigationView.setOnNavigationItemSelectedListener(navListner);\r\n }\r\n\r\n private void setToolBarAndDrawer() {\r\n setSupportActionBar(toolbar);\r\n ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.nav_drawer_open,R.string.nav_drawer_close);\r\n toggle.getDrawerArrowDrawable().setColor(getResources().getColor(android.R.color.white));\r\n drawerLayout.addDrawerListener(toggle);\r\n toggle.syncState();\r\n navigationView.setNavigationItemSelectedListener(this);\r\n }\r\n\r\n private void init() {\r\n drawerLayout = findViewById(R.id.drawer_layout);\r\n toolbar = findViewById(R.id.toolbar);\r\n navigationView = findViewById(R.id.nv);\r\n navigationView.bringToFront();\r\n fhome = new HomeFragment();\r\n fmatch = new MatchFragment();\r\n fprofile = new ProfileFragment();\r\n View view = navigationView.getHeaderView(0);\r\n namenavigator = (TextView) view.findViewById(R.id.namenav);\r\n mailnavigator = (TextView) view.findViewById(R.id.mailnav);\r\n imgnavigator = view.findViewById(R.id.circuler_profile_img);\r\n namenavigator.setText(User.getUser().getUsername());\r\n mailnavigator.setText(User.getUser().getEmail());\r\n if(!User.getUser().getProfile_pic().isEmpty() && User.getUser().getProfile_bitmap() == null) {\r\n DownloadProfilePic download = new DownloadProfilePic();\r\n download.execute(User.getUser().getProfile_pic());\r\n }\r\n }\r\n\r\n @Override\r\n public boolean onCreateOptionsMenu(Menu menu) {\r\n getMenuInflater().inflate(R.menu.home_menu, menu);\r\n menu.getItem(0).getIcon().mutate().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);\r\n return true;\r\n }\r\n\r\n @Override\r\n public boolean onOptionsItemSelected(@NonNull MenuItem item) {\r\n if(item.getItemId() == R.id.notification)\r\n startActivity(new Intent(this,NotificationActivity.class));\r\n return super.onOptionsItemSelected(item);\r\n }\r\n\r\n @Override\r\n public boolean onNavigationItemSelected(@NonNull MenuItem item) {\r\n switch (item.getItemId()){\r\n case R.id.drawer_share:\r\n\r\n break;\r\n case R.id.drawer_rate:\r\n\r\n break;\r\n case R.id.drawer_feedback:\r\n\r\n break;\r\n case R.id.drawer_about_us:\r\n\r\n break;\r\n case R.id.drawer_setting:\r\n\r\n break;\r\n case R.id.drawer_logout:\r\n dialog = createDialog(\"Logout\",R.drawable.ic_baseline_exit_to_app_24);\r\n dialog.create().show();\r\n break;\r\n default:\r\n return false;\r\n }\r\n drawerLayout.closeDrawer(GravityCompat.START);\r\n return false;\r\n }\r\n\r\n private AlertDialog.Builder createDialog(String title, int icon) {\r\n return new AlertDialog.Builder(this)\r\n .setTitle(title)\r\n .setMessage(\"Are you sure?\")\r\n .setIcon(icon)\r\n .setNegativeButton(\"OK\", new DialogInterface.OnClickListener() {\r\n @Override\r\n public void onClick(DialogInterface dialog, int which) {\r\n PrefManager prefManager = new PrefManager(getApplicationContext());\r\n prefManager.setLogout();\r\n startActivity(new Intent(HomeActivity.this,SigninActivity.class));\r\n finish();\r\n }\r\n }).setPositiveButton(\"Cancel\", new DialogInterface.OnClickListener() {\r\n @Override\r\n public void onClick(DialogInterface dialog, int which) {\r\n\r\n }\r\n }).setCancelable(false);\r\n }\r\n\r\n @Override\r\n public void onBackPressed() {\r\n if(drawerLayout.isDrawerOpen(GravityCompat.START))\r\n drawerLayout.closeDrawer(GravityCompat.START);\r\n else\r\n super.onBackPressed();\r\n }\r\n\r\n public void showPopup(View v) { //Fab Action\r\n\r\n final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(HomeActivity.this, R.style.BottomSheetTheme);\r\n View bottomSheetView = LayoutInflater.from(getApplicationContext())\r\n .inflate(R.layout.bottom_sheet_dialog, (LinearLayout)findViewById(R.id.bottom_sheet));\r\n\r\n bottomSheetView.findViewById(R.id.hide_sheet).setOnClickListener(new View.OnClickListener() {\r\n @Override\r\n public void onClick(View v) {\r\n bottomSheetDialog.dismiss();\r\n }\r\n });\r\n\r\n bottomSheetView.findViewById(R.id.ilost).setOnClickListener(new View.OnClickListener() {\r\n @Override\r\n public void onClick(View v) {\r\n startActivity(new Intent(HomeActivity.this, LostObjectDetailsActivity.class));\r\n bottomSheetDialog.dismiss();\r\n }\r\n });\r\n\r\n bottomSheetView.findViewById(R.id.ifound).setOnClickListener(new View.OnClickListener() {\r\n @Override\r\n public void onClick(View v) {\r\n startActivity(new Intent(HomeActivity.this, FoundObjectActivity.class));\r\n bottomSheetDialog.dismiss();\r\n }\r\n });\r\n\r\n bottomSheetDialog.setContentView(bottomSheetView);\r\n bottomSheetDialog.show();\r\n\r\n }\r\n\r\n\r\n private BottomNavigationView.OnNavigationItemSelectedListener navListner =\r\n new BottomNavigationView.OnNavigationItemSelectedListener() {\r\n @Override\r\n public boolean onNavigationItemSelected(@NonNull MenuItem item) {\r\n Fragment selectedFragment = getSupportFragmentManager().getFragments().get(0);\r\n switch (item.getItemId()) {\r\n case R.id.miHome:\r\n if(!(selectedFragment instanceof HomeFragment))\r\n selectedFragment = fhome;\r\n break;\r\n case R.id.miMatch:\r\n if(!(selectedFragment instanceof MatchFragment))\r\n selectedFragment = fmatch;\r\n break;\r\n case R.id.miProfile:\r\n if(!(selectedFragment instanceof ProfileFragment))\r\n selectedFragment = fprofile;\r\n break;\r\n case R.id.miLocation:\r\n selectedFragment = new FoundMapFragment();\r\n break;\r\n }\r\n getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();\r\n return true;\r\n }\r\n };\r\n\r\n class DownloadProfilePic extends AsyncTask {\r\n\r\n private Bitmap download(String urlLink) throws IOException {\r\n Bitmap bitmap = null;\r\n URL url = null;\r\n HttpURLConnection httpConn;\r\n InputStream is = null;\r\n try {\r\n url = new URL(urlLink);\r\n httpConn = (HttpURLConnection) url.openConnection();\r\n httpConn.connect();\r\n is = httpConn.getInputStream();\r\n bitmap = BitmapFactory.decodeStream(is);\r\n }catch (MalformedURLException e){\r\n Log.e(\"DownloadProfilePic\", \"download: \"+e.getMessage());\r\n }\r\n return bitmap;\r\n }\r\n\r\n @Override\r\n protected Bitmap doInBackground(String... urls) {\r\n try {\r\n return download(urls[0]);\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n }\r\n return null;\r\n }\r\n\r\n @Override\r\n protected void onPostExecute(Bitmap bitmap) {\r\n super.onPostExecute(bitmap);\r\n if(bitmap==null)return;\r\n User.getUser().setProfile_bitmap(bitmap);\r\n imgnavigator.setImageBitmap(bitmap);\r\n }\r\n }\r\n} Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== --- app/src/main/java/com/helloworld/goodpoint/ui/HomeActivity.java (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ app/src/main/java/com/helloworld/goodpoint/ui/HomeActivity.java (date 1621854743164) @@ -107,9 +107,11 @@ imgnavigator = view.findViewById(R.id.circuler_profile_img); namenavigator.setText(User.getUser().getUsername()); mailnavigator.setText(User.getUser().getEmail()); - if(!User.getUser().getProfile_pic().isEmpty() && User.getUser().getProfile_bitmap() == null) { + if(User.getUser().getProfile_pic() != null &&!User.getUser().getProfile_pic().isEmpty() && User.getUser().getProfile_bitmap() == null) { + Log.e("Profile Pic", User.getUser().getProfile_pic()); + String dnsLink = new PrefManager(this).getNGROKLink(); DownloadProfilePic download = new DownloadProfilePic(); - download.execute(User.getUser().getProfile_pic()); + download.execute(dnsLink+User.getUser().getProfile_pic()+"/"); } } @@ -254,6 +256,7 @@ URL url = null; HttpURLConnection httpConn; InputStream is = null; + Log.e("ProfilePic", urlLink); try { url = new URL(urlLink); httpConn = (HttpURLConnection) url.openConnection(); Index: backend/find_losts/migrations/0003_auto_20210429_1627.py =================================================================== --- backend/find_losts/migrations/0003_auto_20210429_1627.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/find_losts/migrations/0003_auto_20210429_1627.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) @@ -1,18 +0,0 @@ -# Generated by Django 3.1.7 on 2021-04-29 14:27 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ('find_losts', '0002_auto_20210216_2354'), - ] - - operations = [ - migrations.AlterField( - model_name='lostitem', - name='image', - field=models.ImageField(blank=True, null=True, upload_to=''), - ), - ] Index: backend/find_losts/migrations/0011_auto_20210503_0616.py =================================================================== --- backend/find_losts/migrations/0011_auto_20210503_0616.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/find_losts/migrations/0011_auto_20210503_0616.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) @@ -1,19 +0,0 @@ -# Generated by Django 3.1.7 on 2021-05-03 04:16 - -from django.db import migrations, models -import django.db.models.deletion - - -class Migration(migrations.Migration): - - dependencies = [ - ('find_losts', '0010_auto_20210503_0612'), - ] - - operations = [ - migrations.AlterField( - model_name='lostpersonimage', - name='id', - field=models.OneToOneField(db_column='id', on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to='find_losts.lostperson'), - ), - ] Index: backend/find_losts/migrations/0008_auto_20210503_0451.py =================================================================== --- backend/find_losts/migrations/0008_auto_20210503_0451.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/find_losts/migrations/0008_auto_20210503_0451.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) @@ -1,18 +0,0 @@ -# Generated by Django 3.1.7 on 2021-05-03 02:51 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ('find_losts', '0007_auto_20210503_0451'), - ] - - operations = [ - migrations.AlterField( - model_name='lostpersonimage', - name='image', - field=models.ImageField(unique=True, upload_to=''), - ), - ] Index: backend/user_account/migrations/0002_auto_20210318_0955.py =================================================================== --- backend/user_account/migrations/0002_auto_20210318_0955.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/user_account/migrations/0002_auto_20210318_0955.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) @@ -1,18 +0,0 @@ -# Generated by Django 3.1.4 on 2021-03-18 07:55 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ('user_account', '0001_initial'), - ] - - operations = [ - migrations.AlterField( - model_name='user', - name='email', - field=models.EmailField(blank=True, max_length=1), - ), - ] Index: backend/find_losts/migrations/0010_auto_20210503_0612.py =================================================================== --- backend/find_losts/migrations/0010_auto_20210503_0612.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/find_losts/migrations/0010_auto_20210503_0612.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) @@ -1,18 +0,0 @@ -# Generated by Django 3.1.7 on 2021-05-03 04:12 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ('find_losts', '0009_auto_20210503_0456'), - ] - - operations = [ - migrations.AlterField( - model_name='foundobject', - name='date', - field=models.DateField(), - ), - ] Index: backend/find_losts/migrations/0014_remove_founditem_image.py =================================================================== --- backend/find_losts/migrations/0014_remove_founditem_image.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/find_losts/migrations/0014_remove_founditem_image.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) @@ -1,17 +0,0 @@ -# Generated by Django 3.1.7 on 2021-05-15 13:14 - -from django.db import migrations - - -class Migration(migrations.Migration): - - dependencies = [ - ('find_losts', '0013_auto_20210514_0152'), - ] - - operations = [ - migrations.RemoveField( - model_name='founditem', - name='image', - ), - ] Index: backend/user_account/migrations/0001_initial.py IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== --- backend/user_account/migrations/0001_initial.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/user_account/migrations/0001_initial.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) @@ -1,48 +0,0 @@ -# Generated by Django 3.1.4 on 2021-02-16 21:54 - -import django.contrib.auth.models -import django.contrib.auth.validators -from django.db import migrations, models -import django.utils.timezone -import user_account.models - - -class Migration(migrations.Migration): - - initial = True - - dependencies = [ - ('auth', '0012_alter_user_first_name_max_length'), - ] - - operations = [ - migrations.CreateModel( - name='User', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('password', models.CharField(max_length=128, verbose_name='password')), - ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), - ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), - ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), - ('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')), - ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), - ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), - ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), - ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), - ('email', models.EmailField(max_length=65, unique=True)), - ('phone', models.CharField(max_length=20, unique=True)), - ('birthdate', models.DateField()), - ('city', models.CharField(max_length=35)), - ('profile_pic', models.ImageField(blank=True, null=True, upload_to=user_account.models.profile_pic_dir)), - ('id_card_pic', models.ImageField(blank=True, null=True, upload_to=user_account.models.idcard_pic_dir)), - ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), - ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), - ], - options={ - 'db_table': 'user', - }, - managers=[ - ('objects', django.contrib.auth.models.UserManager()), - ], - ), - ] Index: backend/find_losts/migrations/0001_initial.py IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== --- backend/find_losts/migrations/0001_initial.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/find_losts/migrations/0001_initial.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) @@ -1,113 +0,0 @@ -# Generated by Django 3.1.4 on 2021-02-16 21:54 - -from django.db import migrations, models -import django.db.models.deletion - - -class Migration(migrations.Migration): - - initial = True - - dependencies = [ - ] - - operations = [ - migrations.CreateModel( - name='Candidate', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('percent', models.DecimalField(decimal_places=4, max_digits=5)), - ('is_matched', models.BooleanField(default=False)), - ], - options={ - 'db_table': 'candidate', - }, - ), - migrations.CreateModel( - name='FoundObject', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('date', models.DateTimeField()), - ('longitude', models.DecimalField(decimal_places=10, default=0.0, max_digits=14)), - ('latitude', models.DecimalField(decimal_places=10, default=0.0, max_digits=14)), - ('city', models.CharField(max_length=35)), - ('is_matched', models.BooleanField(default=False)), - ], - options={ - 'db_table': 'found_object', - }, - ), - migrations.CreateModel( - name='LostObject', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('date', models.DateTimeField()), - ('city', models.CharField(max_length=35)), - ('is_matched', models.BooleanField(default=False)), - ], - options={ - 'db_table': 'lost_object', - }, - ), - migrations.CreateModel( - name='FoundItem', - fields=[ - ('id', models.OneToOneField(db_column='id', on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to='find_losts.foundobject')), - ('type', models.CharField(max_length=20)), - ('color', models.CharField(max_length=20)), - ('brand', models.CharField(max_length=50)), - ('description', models.CharField(max_length=700)), - ('serial_number', models.CharField(blank=True, max_length=100, null=True)), - ('image', models.ImageField(unique=True, upload_to='')), - ], - options={ - 'db_table': 'found_item', - }, - ), - migrations.CreateModel( - name='FoundPerson', - fields=[ - ('id', models.OneToOneField(db_column='id', on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to='find_losts.foundobject')), - ('name', models.CharField(blank=True, max_length=150, null=True)), - ], - options={ - 'db_table': 'found_person', - }, - ), - migrations.CreateModel( - name='LostItem', - fields=[ - ('id', models.OneToOneField(db_column='id', on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to='find_losts.lostobject')), - ('type', models.CharField(max_length=20)), - ('color', models.CharField(max_length=20)), - ('brand', models.CharField(max_length=50)), - ('description', models.CharField(max_length=700)), - ('serial_number', models.CharField(blank=True, max_length=100, null=True)), - ('image', models.ImageField(blank=True, null=True, unique=True, upload_to='')), - ], - options={ - 'db_table': 'lost_item', - }, - ), - migrations.CreateModel( - name='LostPerson', - fields=[ - ('id', models.OneToOneField(db_column='id', on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to='find_losts.lostobject')), - ('name', models.CharField(max_length=150)), - ], - options={ - 'db_table': 'lost_person', - }, - ), - migrations.CreateModel( - name='MatchedPerson', - fields=[ - ('id_fp', models.OneToOneField(db_column='found_person_id', on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='match', serialize=False, to='find_losts.foundobject')), - ('date_of_receiving', models.DateTimeField(auto_now_add=True)), - ('percent', models.DecimalField(decimal_places=4, max_digits=5)), - ], - options={ - 'db_table': 'matched_Person', - }, - ), - ] Index: backend/find_losts/migrations/0012_auto_20210503_1505.py =================================================================== --- backend/find_losts/migrations/0012_auto_20210503_1505.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/find_losts/migrations/0012_auto_20210503_1505.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) @@ -1,18 +0,0 @@ -# Generated by Django 3.1.7 on 2021-05-03 13:05 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ('find_losts', '0011_auto_20210503_0616'), - ] - - operations = [ - migrations.AlterField( - model_name='lostobject', - name='date', - field=models.DateField(), - ), - ] Index: backend/find_losts/migrations/0009_auto_20210503_0456.py =================================================================== --- backend/find_losts/migrations/0009_auto_20210503_0456.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/find_losts/migrations/0009_auto_20210503_0456.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) @@ -1,17 +0,0 @@ -# Generated by Django 3.1.7 on 2021-05-03 02:56 - -from django.db import migrations - - -class Migration(migrations.Migration): - - dependencies = [ - ('find_losts', '0008_auto_20210503_0451'), - ] - - operations = [ - migrations.AlterUniqueTogether( - name='lostpersonimage', - unique_together={('id', 'image')}, - ), - ] Index: backend/notification/migrations/0001_initial.py IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== --- backend/notification/migrations/0001_initial.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/notification/migrations/0001_initial.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) @@ -1,29 +0,0 @@ -# Generated by Django 3.1.4 on 2021-02-16 21:54 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - initial = True - - dependencies = [ - ] - - operations = [ - migrations.CreateModel( - name='Notification', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('title', models.CharField(max_length=30)), - ('description', models.CharField(max_length=100)), - ('type', models.IntegerField()), - ('date_time', models.DateTimeField(auto_now_add=True)), - ('is_sent', models.BooleanField(default=False)), - ('is_read', models.BooleanField(default=False)), - ], - options={ - 'db_table': 'notification', - }, - ), - ] Index: backend/find_losts/migrations/0006_auto_20210501_1627.py =================================================================== --- backend/find_losts/migrations/0006_auto_20210501_1627.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/find_losts/migrations/0006_auto_20210501_1627.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) @@ -1,19 +0,0 @@ -# Generated by Django 3.1.7 on 2021-05-01 14:27 - -from django.db import migrations, models -import django.db.models.deletion - - -class Migration(migrations.Migration): - - dependencies = [ - ('find_losts', '0005_auto_20210501_1552'), - ] - - operations = [ - migrations.AlterField( - model_name='foundpersonimage', - name='id', - field=models.ForeignKey(db_column='id', on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to='find_losts.foundperson'), - ), - ] Index: backend/notification/migrations/0004_auto_20210514_1846.py =================================================================== --- backend/notification/migrations/0004_auto_20210514_1846.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/notification/migrations/0004_auto_20210514_1846.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) @@ -1,18 +0,0 @@ -# Generated by Django 3.1.7 on 2021-05-14 16:46 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ('notification', '0003_auto_20210503_0612'), - ] - - operations = [ - migrations.AlterField( - model_name='notification', - name='date_time', - field=models.DateTimeField(auto_now_add=True), - ), - ] Index: backend/notification/migrations/0002_notification_user_id.py IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== --- backend/notification/migrations/0002_notification_user_id.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/notification/migrations/0002_notification_user_id.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) @@ -1,23 +0,0 @@ -# Generated by Django 3.1.4 on 2021-02-16 21:54 - -from django.conf import settings -from django.db import migrations, models -import django.db.models.deletion - - -class Migration(migrations.Migration): - - initial = True - - dependencies = [ - ('notification', '0001_initial'), - migrations.swappable_dependency(settings.AUTH_USER_MODEL), - ] - - operations = [ - migrations.AddField( - model_name='notification', - name='user_id', - field=models.ForeignKey(db_column='user_id', on_delete=django.db.models.deletion.CASCADE, related_name='notify', to=settings.AUTH_USER_MODEL), - ), - ] Index: backend/find_losts/migrations/0004_auto_20210501_0251.py =================================================================== --- backend/find_losts/migrations/0004_auto_20210501_0251.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/find_losts/migrations/0004_auto_20210501_0251.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) @@ -1,18 +0,0 @@ -# Generated by Django 3.1.7 on 2021-05-01 00:51 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ('find_losts', '0003_auto_20210429_1627'), - ] - - operations = [ - migrations.AlterField( - model_name='lostobject', - name='date', - field=models.DateField(), - ), - ] Index: backend/find_losts/migrations/0007_auto_20210503_0451.py =================================================================== --- backend/find_losts/migrations/0007_auto_20210503_0451.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/find_losts/migrations/0007_auto_20210503_0451.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) @@ -1,48 +0,0 @@ -# Generated by Django 3.1.7 on 2021-05-03 02:51 - -from django.db import migrations, models -import django.db.models.deletion - - -class Migration(migrations.Migration): - - dependencies = [ - ('find_losts', '0006_auto_20210501_1627'), - ] - - operations = [ - migrations.AlterField( - model_name='foundobject', - name='date', - field=models.DateTimeField(), - ), - migrations.AlterField( - model_name='foundpersonimage', - name='id', - field=models.OneToOneField(db_column='id', on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to='find_losts.foundperson'), - ), - migrations.AlterField( - model_name='lostitem', - name='image', - field=models.ImageField(blank=True, null=True, unique=True, upload_to=''), - ), - migrations.AlterField( - model_name='lostobject', - name='date', - field=models.DateTimeField(), - ), - migrations.AlterField( - model_name='lostpersonimage', - name='id', - field=models.AutoField(primary_key=True, serialize=False), - ), - migrations.AlterField( - model_name='lostpersonimage', - name='image', - field=models.ImageField(upload_to=''), - ), - migrations.AlterUniqueTogether( - name='lostpersonimage', - unique_together=set(), - ), - ] Index: backend/notification/migrations/0003_auto_20210503_0612.py =================================================================== --- backend/notification/migrations/0003_auto_20210503_0612.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/notification/migrations/0003_auto_20210503_0612.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) @@ -1,18 +0,0 @@ -# Generated by Django 3.1.7 on 2021-05-03 04:12 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ('notification', '0002_notification_user_id'), - ] - - operations = [ - migrations.AlterField( - model_name='notification', - name='date_time', - field=models.DateField(auto_now_add=True), - ), - ] Index: backend/find_losts/migrations/0002_auto_20210216_2354.py =================================================================== --- backend/find_losts/migrations/0002_auto_20210216_2354.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/find_losts/migrations/0002_auto_20210216_2354.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) @@ -1,85 +0,0 @@ -# Generated by Django 3.1.4 on 2021-02-16 21:54 - -from django.conf import settings -from django.db import migrations, models -import django.db.models.deletion - - -class Migration(migrations.Migration): - - initial = True - - dependencies = [ - ('find_losts', '0001_initial'), - ('notification', '0001_initial'), - migrations.swappable_dependency(settings.AUTH_USER_MODEL), - ] - - operations = [ - migrations.AddField( - model_name='lostobject', - name='user_id', - field=models.ForeignKey(db_column='user_id', on_delete=django.db.models.deletion.CASCADE, related_name='lost', to=settings.AUTH_USER_MODEL), - ), - migrations.AddField( - model_name='foundobject', - name='user_id', - field=models.ForeignKey(db_column='user_id', on_delete=django.db.models.deletion.CASCADE, related_name='found', to=settings.AUTH_USER_MODEL), - ), - migrations.AddField( - model_name='candidate', - name='notify_id', - field=models.ForeignKey(db_column='notify_id', on_delete=django.db.models.deletion.CASCADE, related_name='reach_candidates_to_who_found', to='notification.notification'), - ), - migrations.AddField( - model_name='matchedperson', - name='id_lp', - field=models.OneToOneField(db_column='lost_person_id', on_delete=django.db.models.deletion.CASCADE, related_name='match', to='find_losts.lostobject'), - ), - migrations.AddField( - model_name='matchedperson', - name='notify_id_fp', - field=models.ForeignKey(db_column='notify_id_fp', on_delete=django.db.models.deletion.CASCADE, related_name='reach_match_to_who_found', to='notification.notification'), - ), - migrations.AddField( - model_name='matchedperson', - name='notify_id_lp', - field=models.ForeignKey(db_column='notify_id_lp', on_delete=django.db.models.deletion.CASCADE, related_name='reach_match_to_who_lost', to='notification.notification'), - ), - migrations.AddField( - model_name='candidate', - name='id_fi', - field=models.ForeignKey(db_column='found_item_id', on_delete=django.db.models.deletion.CASCADE, related_name='candidate', to='find_losts.founditem'), - ), - migrations.AddField( - model_name='candidate', - name='id_li', - field=models.ForeignKey(db_column='lost_item_id', on_delete=django.db.models.deletion.CASCADE, related_name='candidate', to='find_losts.lostitem'), - ), - migrations.CreateModel( - name='LostPersonImage', - fields=[ - ('id', models.OneToOneField(db_column='id', on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to='find_losts.lostperson')), - ('image', models.ImageField(unique=True, upload_to='')), - ], - options={ - 'db_table': 'lost_person_image', - 'unique_together': {('id', 'image')}, - }, - ), - migrations.CreateModel( - name='FoundPersonImage', - fields=[ - ('id', models.OneToOneField(db_column='id', on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to='find_losts.foundperson')), - ('image', models.ImageField(unique=True, upload_to='')), - ], - options={ - 'db_table': 'found_person_image', - 'unique_together': {('id', 'image')}, - }, - ), - migrations.AlterUniqueTogether( - name='candidate', - unique_together={('id_li', 'id_fi')}, - ), - ] Index: backend/find_losts/migrations/0013_auto_20210514_0152.py =================================================================== --- backend/find_losts/migrations/0013_auto_20210514_0152.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/find_losts/migrations/0013_auto_20210514_0152.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) @@ -1,18 +0,0 @@ -# Generated by Django 3.1.7 on 2021-05-13 23:52 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ('find_losts', '0012_auto_20210503_1505'), - ] - - operations = [ - migrations.AlterField( - model_name='lostitem', - name='image', - field=models.ImageField(blank=True, null=True, upload_to=''), - ), - ] Index: backend/find_losts/migrations/0005_auto_20210501_1552.py =================================================================== --- backend/find_losts/migrations/0005_auto_20210501_1552.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/find_losts/migrations/0005_auto_20210501_1552.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) @@ -1,18 +0,0 @@ -# Generated by Django 3.1.7 on 2021-05-01 13:52 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ('find_losts', '0004_auto_20210501_0251'), - ] - - operations = [ - migrations.AlterField( - model_name='foundobject', - name='date', - field=models.DateField(), - ), - ] Index: backend/find_losts/serializers.py IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.BaseRevisionTextPatchEP <+>from rest_framework import serializers\r\nfrom rest_framework_simplejwt.tokens import RefreshToken, TokenError\r\nfrom .models import *\r\nfrom user_account.models import User\r\n\r\n\r\nclass LostObjectSerializer(serializers.ModelSerializer):\r\n\r\n class Meta:\r\n model = LostObject\r\n fields = ['id', 'date', 'city', 'is_matched', 'user_id']\r\n\r\n\r\nclass LostItemSerializer(serializers.ModelSerializer):\r\n\r\n class Meta:\r\n model = LostItem\r\n fields = ['id', 'type', 'serial_number', 'brand', 'color', 'description', 'image']\r\n\r\n def validate(self, attrs):\r\n if LostPerson.objects.filter(id=attrs.get('id', '')).exists():\r\n raise serializers.ValidationError({'id': {'id already exists'}})\r\n return super().validate(attrs)\r\n\r\n\r\nclass LostPersonSerializer(serializers.ModelSerializer):\r\n\r\n class Meta:\r\n model = LostPerson\r\n fields = ['id', 'name']\r\n\r\n def validate(self, attrs):\r\n if LostItem.objects.filter(id=attrs.get('id', '')).exists():\r\n raise serializers.ValidationError({'id': {'id already exists'}})\r\n return super().validate(attrs)\r\n\r\n\r\nclass LostPersonImageSerializer(serializers.ModelSerializer):\r\n class Meta:\r\n model = LostPersonImage\r\n fields = '__all__'\r\n\r\n\r\n\r\nclass FoundObjectSerializer(serializers.ModelSerializer):\r\n class Meta:\r\n model = FoundObject\r\n fields = ['id', 'date', 'longitude', 'latitude', 'city', 'user_id', 'is_matched']\r\n\r\nclass FoundItemSerializer(serializers.ModelSerializer):\r\n class Meta:\r\n model = FoundItem\r\n fields = ['id', 'type', 'color', 'brand', 'description', 'serial_number']#image_removed\r\n\r\n def validate(self, attrs):\r\n if FoundPerson.objects.filter(id=attrs.get('id', '')).exists():\r\n raise serializers.ValidationError({'id': {'id already exists'}})\r\n return super().validate(attrs)\r\n\r\n\r\nclass FoundPersonSerializer(serializers.ModelSerializer):\r\n class Meta:\r\n model = FoundPerson\r\n fields = ['id', 'name']\r\n\r\n def validate(self, attrs):\r\n if FoundItem.objects.filter(id=attrs.get('id', '')).exists():\r\n raise serializers.ValidationError({'id': {'id already exists'}})\r\n return super().validate(attrs)\r\n\r\n\r\nclass FoundPersonImageSerializer(serializers.ModelSerializer):\r\n class Meta:\r\n model = FoundPersonImage\r\n fields = ['id_image', 'image']\r\n\r\nclass MapSerializer(serializers.ModelSerializer):\r\n longitude = serializers.DecimalField(max_digits=14, decimal_places=10, source='id.longitude')\r\n latitude = serializers.DecimalField(max_digits=14, decimal_places=10, source='id.latitude')\r\n user_id = serializers.IntegerField(source='id.user_id.id')\r\n\r\n class Meta:\r\n model = FoundItem\r\n fields = ['longitude', 'latitude', 'user_id']\r\n Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== --- backend/find_losts/serializers.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/find_losts/serializers.py (date 1621860226693) @@ -2,13 +2,16 @@ from rest_framework_simplejwt.tokens import RefreshToken, TokenError from .models import * from user_account.models import User +from django.db.models import Count +import face_recognition +import numpy as np class LostObjectSerializer(serializers.ModelSerializer): class Meta: model = LostObject - fields = ['id', 'date', 'city', 'is_matched', 'user_id'] + fields = ['date', 'city','user_id'] class LostItemSerializer(serializers.ModelSerializer): @@ -21,36 +24,122 @@ if LostPerson.objects.filter(id=attrs.get('id', '')).exists(): raise serializers.ValidationError({'id': {'id already exists'}}) return super().validate(attrs) - - -class LostPersonSerializer(serializers.ModelSerializer): - - class Meta: - model = LostPerson - fields = ['id', 'name'] - - def validate(self, attrs): - if LostItem.objects.filter(id=attrs.get('id', '')).exists(): - raise serializers.ValidationError({'id': {'id already exists'}}) - return super().validate(attrs) class LostPersonImageSerializer(serializers.ModelSerializer): class Meta: model = LostPersonImage - fields = '__all__' + fields = ['image'] + + +def match_with_found_person(pk): + source_img = face_recognition.load_image_file(f'media/lostperson/{pk}.jpg') + source_encoding = face_recognition.face_encodings(source_img)[0] + founds = list(FoundPerson.objects.values_list('id')) + + encodings = [] + ids = [] + min_val = -1 + for id_f in founds: + face = face_recognition.load_image_file(f'media/foundperson/{id_f[0]}.jpg') + encodings.append(face_recognition.face_encodings(face)[0]) + ids.append(id_f[0]) + dist = face_recognition.face_distance(encodings,source_encoding) + if dist.size > 0: + min_val = min(dist) + if 0 < min_val <= 0.52: + return min_val, ids[dist.argmin()] + else: + return -1, -1 + +""" + mini = 1.0 + minid = -1 + for id in ids: + sum_dist = 0.0 + for img_num in range(id.number_of_images): + face = face_recognition.load_image_file(f'media/foundperson/{source_id.pk}/{img_num + 1}.jpg') + encoding = face_recognition.face_encodings(face)[0] + dist = list(face_recognition.face_distance(source_encodings, encoding)) + sum_dist = sum_dist + sum(dist) + + avg = sum_dist/(source_id.number_of_images*id.number_of_images) + if avg < mini: + mini = avg + minid = id + + if 0 < mini <= 0.52: + return mini, minid + else: + return -1, -1 +""" + + +class LostPersonSerializer(serializers.ModelSerializer): + date = serializers.DateField() + city = serializers.CharField(max_length=35) + user_id = serializers.IntegerField() + + class Meta: + model = LostPerson + fields = ['date', 'city', 'user_id', 'name', 'image'] + + def create(self, validated_data): + data = validated_data.copy() + #images_data = data.pop('images') + #self.context.get('request').data.pop('images') + user = User.objects.get(id=data.pop('user_id')) + person_id = LostObject.objects.create(date=data.pop('date'), city=data.pop('city'), user_id=user) + person = None + + try: + person = LostPerson.objects.create(id=person_id, **data) + print(person) + except TypeError: + obj = LostObject.objects.get(id=person.id) + obj.delete() + raise TypeError('TypeError: LostPerson.objects.create()') + """ + try: + cnt = 0 + for img in images_data: + cnt = cnt + 1 + image = LostPersonImage.objects.create(id_lp=person.pk, image_number=cnt, image=img) + person.person_image.add(image) + except TypeError: + person = LostPerson.objects.get(id=person.id) + obj = LostObject.objects.get(id=person.id) + person.delete() + obj.delete() + raise TypeError('TypeError: LostPersonImage.objects.create()') + """ + + res_match = match_with_found_person(person.pk) + print(res_match) + matched = False + """ + if res_match != -1: + matched = True + matched_person = FoundPerson.objects.filter(id=res_match[0]) + #Notification.objects.create() + #Notification.objects.create() + #MatchedPerson.objects.create() + pass + """ + + return validated_data class FoundObjectSerializer(serializers.ModelSerializer): class Meta: model = FoundObject - fields = ['id', 'date', 'longitude', 'latitude', 'city', 'user_id', 'is_matched'] + fields = ['date', 'longitude', 'latitude', 'city', 'user_id', 'is_matched'] class FoundItemSerializer(serializers.ModelSerializer): class Meta: model = FoundItem - fields = ['id', 'type', 'color', 'brand', 'description', 'serial_number']#image_removed + fields = ['id', 'type', 'color', 'brand', 'description', 'serial_number', 'image'] def validate(self, attrs): if FoundPerson.objects.filter(id=attrs.get('id', '')).exists(): @@ -58,15 +147,86 @@ return super().validate(attrs) +def match_with_lost_person(pk): + source_img = face_recognition.load_image_file(f'media/foundperson/{pk}.jpg') + source_encoding = face_recognition.face_encodings(source_img)[0] + losts = list(LostPerson.objects.values_list('id')) + print(losts) + encodings = [] + ids = [] + for id_l in losts: + face = face_recognition.load_image_file(f'media/lostperson/{id_l[0]}.jpg') + encodings.append(face_recognition.face_encodings(face)[0]) + ids.append(id_l[0]) + + dist = face_recognition.face_distance(encodings, source_encoding) + min_val = min(dist) + + if dist.size > 0: + min_val = min(dist) + + if 0 < min_val <= 0.52: + return min_val, ids[dist.argmin()] + else: + return -1, -1 + + class FoundPersonSerializer(serializers.ModelSerializer): + date = serializers.DateField() + longitude = serializers.DecimalField(max_digits=14, decimal_places=10, default=0.0) + latitude = serializers.DecimalField(max_digits=14, decimal_places=10, default=0.0) + city = serializers.CharField(max_length=35) + user_id = serializers.IntegerField() + class Meta: model = FoundPerson - fields = ['id', 'name'] + fields = ['date', 'longitude', 'latitude', 'city', 'user_id', 'name', 'image'] + + def create(self, validated_data): + data = validated_data.copy() + #images_data = data.pop('images') + #self.context.get('request').data.pop('images') + user = User.objects.get(id=data.pop('user_id')) + person_id = FoundObject.objects.create(date=data.pop('date'), longitude=data.pop('longitude'), + latitude=data.pop('latitude'), city=data.pop('city'), user_id=user) + person = None - def validate(self, attrs): - if FoundItem.objects.filter(id=attrs.get('id', '')).exists(): - raise serializers.ValidationError({'id': {'id already exists'}}) - return super().validate(attrs) + try: + person = FoundPerson.objects.create(id=person_id, **data) + print(person) + except TypeError: + obj = FoundObject.objects.get(id=person.id) + obj.delete() + raise TypeError('TypeError: FoundPerson.objects.create()') + """ + try: + cnt = 0 + for img in images_data: + cnt = cnt + 1 + image = LostPersonImage.objects.create(id_lp=person.pk, image_number=cnt, image=img) + person.person_image.add(image) + except TypeError: + person = LostPerson.objects.get(id=person.id) + obj = LostObject.objects.get(id=person.id) + person.delete() + obj.delete() + raise TypeError('TypeError: LostPersonImage.objects.create()') + """ + + res_match = match_with_lost_person(person.pk) + print(res_match) + matched = False + """ + if res_match != -1: + matched = True + matched_person = LostPerson.objects.filter(id=res_match[0]) + #Notification.objects.create() + #Notification.objects.create() + #MatchedPerson.objects.create() + pass + """ + + return validated_data class FoundPersonImageSerializer(serializers.ModelSerializer): @@ -74,6 +234,7 @@ model = FoundPersonImage fields = ['id_image', 'image'] + class MapSerializer(serializers.ModelSerializer): longitude = serializers.DecimalField(max_digits=14, decimal_places=10, source='id.longitude') latitude = serializers.DecimalField(max_digits=14, decimal_places=10, source='id.latitude') Index: backend/user_account/serializers.py IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.BaseRevisionTextPatchEP <+>from rest_framework import serializers\r\nfrom rest_framework_simplejwt.tokens import RefreshToken, TokenError\r\nfrom .models import User\r\n\r\n\r\nclass SignupSerializer(serializers.ModelSerializer):\r\n username = serializers.CharField(max_length=150)\r\n # email = serializers.EmailField(max_length=65, min_length=4)\r\n password = serializers.CharField(max_length=65, min_length=8, write_only=True)\r\n first_name = serializers.CharField(max_length=255, min_length=2)\r\n phone = serializers.CharField(max_length=20, min_length=5)\r\n city = serializers.CharField(max_length=35)\r\n birthdate = serializers.DateField\r\n profile_pic = serializers.ImageField\r\n\r\n class Meta:\r\n model = User\r\n fields = ['username', 'password', 'first_name', 'phone', 'city', 'birthdate', 'profile_pic']\r\n\r\n def validate(self, attrs):\r\n exist_email = User.objects.filter(username=attrs.get('username', '')).exists()\r\n exist_phone = User.objects.filter(phone=attrs.get('phone', '')).exists()\r\n if exist_email and exist_phone:\r\n raise serializers.ValidationError(\r\n {\r\n 'error': {\r\n 'username': 'Email already exists',\r\n 'phone': 'Phone number already exists'\r\n }\r\n })\r\n if exist_email:\r\n raise serializers.ValidationError({'error': {'username': 'Email already exists', 'phone': ''}})\r\n if exist_phone:\r\n raise serializers.ValidationError({'error': {'username': '', 'phone': 'Phone number already exists'}})\r\n return super().validate(attrs)\r\n\r\n def create(self, validated_data):\r\n return User.objects.create_user(**validated_data)\r\n\r\n\r\nclass LogoutSerializer(serializers.Serializer):\r\n token = serializers.CharField()\r\n\r\n def validate(self, attrs):\r\n self.token = attrs['refresh']\r\n return attrs\r\n\r\n def save(self, **kwargs):\r\n try:\r\n RefreshToken(self.token).blacklist()\r\n except TokenError:\r\n self.fail('bad_token')\r\n\r\n def update(self, instance, validated_data):\r\n pass\r\n\r\n def create(self, validated_data):\r\n pass\r\n\r\n\r\nclass WhoFoundItemSerializer(serializers.ModelSerializer):\r\n name = serializers.CharField(source='first_name')\r\n email = serializers.CharField(source='username')\r\n\r\n class Meta:\r\n model = User\r\n fields = ['name', 'email', 'phone']\r\n Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== --- backend/user_account/serializers.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/user_account/serializers.py (date 1621783334231) @@ -4,14 +4,6 @@ class SignupSerializer(serializers.ModelSerializer): - username = serializers.CharField(max_length=150) - # email = serializers.EmailField(max_length=65, min_length=4) - password = serializers.CharField(max_length=65, min_length=8, write_only=True) - first_name = serializers.CharField(max_length=255, min_length=2) - phone = serializers.CharField(max_length=20, min_length=5) - city = serializers.CharField(max_length=35) - birthdate = serializers.DateField - profile_pic = serializers.ImageField class Meta: model = User Index: backend/find_losts/models.py IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.BaseRevisionTextPatchEP <+>from django.db import models\r\nfrom user_account.models import User\r\nfrom notification.models import Notification\r\n\r\n\r\n# Create your models here.\r\n\r\nclass LostObject(models.Model):\r\n date = models.DateField()\r\n city = models.CharField(max_length=35)\r\n user_id = models.ForeignKey(User, related_name='lost', on_delete=models.CASCADE, db_column='user_id')\r\n is_matched = models.BooleanField(default=False)\r\n\r\n class Meta:\r\n db_table = 'lost_object'\r\n\r\n\r\nclass LostPerson(models.Model):\r\n id = models.OneToOneField(LostObject, primary_key=True, on_delete=models.CASCADE, db_column='id')\r\n name = models.CharField(max_length=150)\r\n\r\n class Meta:\r\n db_table = 'lost_person'\r\n\r\n\r\nclass LostPersonImage(models.Model):\r\n #id = models.AutoField(primary_key=True)\r\n id = models.OneToOneField(LostPerson, primary_key=True, on_delete=models.CASCADE, db_column='id')\r\n image = models.ImageField(unique=True)\r\n\r\n class Meta:\r\n db_table = 'lost_person_image'\r\n unique_together = (('id', 'image'),)\r\n\r\ndef lost_item_image(instance,filename):\r\n return f\"lost_item/{instance.pk}.jpg/\"\r\n\r\nclass LostItem(models.Model):\r\n id = models.OneToOneField(LostObject, primary_key=True, on_delete=models.CASCADE, db_column='id')\r\n type = models.CharField(max_length=20)\r\n color = models.CharField(max_length=20)\r\n brand = models.CharField(max_length=50)\r\n description = models.CharField(max_length=700)\r\n serial_number = models.CharField(max_length=100, blank=True, null=True)\r\n image = models.ImageField(blank=True, null=True, upload_to=lost_item_image)\r\n\r\n class Meta:\r\n db_table = 'lost_item'\r\n\r\n\r\n\r\nclass FoundObject(models.Model):\r\n date = models.DateField()\r\n longitude = models.DecimalField(max_digits=14, decimal_places=10, default=0.0)\r\n latitude = models.DecimalField(max_digits=14, decimal_places=10, default=0.0)\r\n city = models.CharField(max_length=35)\r\n user_id = models.ForeignKey(User, related_name='found', on_delete=models.CASCADE, db_column='user_id')\r\n is_matched = models.BooleanField(default=False)\r\n\r\n class Meta:\r\n db_table = 'found_object'\r\n\r\n\r\nclass FoundPerson(models.Model):\r\n id = models.OneToOneField(FoundObject, primary_key=True, on_delete=models.CASCADE, db_column='id')\r\n name = models.CharField(max_length=150, blank=True, null=True)\r\n\r\n class Meta:\r\n db_table = 'found_person'\r\n\r\n\r\nclass FoundPersonImage(models.Model):\r\n id = models.OneToOneField(FoundPerson, primary_key=True, on_delete=models.CASCADE, db_column='id')\r\n image = models.ImageField(unique=True)\r\n\r\n class Meta:\r\n db_table = 'found_person_image'\r\n unique_together = (('id', 'image'),)\r\n\r\n\r\nclass FoundItem(models.Model):\r\n id = models.OneToOneField(FoundObject, primary_key=True, on_delete=models.CASCADE, db_column='id')\r\n type = models.CharField(max_length=20)\r\n color = models.CharField(max_length=20)\r\n brand = models.CharField(max_length=50)\r\n description = models.CharField(max_length=700)\r\n serial_number = models.CharField(max_length=100, blank=True, null=True)\r\n #image = models.ImageField(unique=True)\r\n\r\n class Meta:\r\n db_table = 'found_item'\r\n\r\n\r\nclass Candidate(models.Model):\r\n id_fi = models.ForeignKey(FoundItem, related_name='candidate', on_delete=models.CASCADE, db_column='found_item_id')\r\n id_li = models.ForeignKey(LostItem, related_name='candidate', on_delete=models.CASCADE, db_column='lost_item_id')\r\n percent = models.DecimalField(max_digits=5, decimal_places=4)\r\n is_matched = models.BooleanField(default=False)\r\n notify_id = models.ForeignKey(Notification, related_name='reach_candidates_to_who_found', on_delete=models.CASCADE,\r\n db_column='notify_id')\r\n\r\n class Meta:\r\n db_table = 'candidate'\r\n unique_together = (('id_li', 'id_fi'),)\r\n\r\n\r\nclass MatchedPerson(models.Model):\r\n id_fp = models.OneToOneField(FoundObject, primary_key=True, unique=True, related_name='match',\r\n on_delete=models.CASCADE, db_column='found_person_id')\r\n id_lp = models.OneToOneField(LostObject, unique=True, related_name='match', on_delete=models.CASCADE,\r\n db_column='lost_person_id')\r\n date_of_receiving = models.DateTimeField(auto_now_add=True)\r\n percent = models.DecimalField(max_digits=5, decimal_places=4)\r\n notify_id_fp = models.ForeignKey(Notification, related_name='reach_match_to_who_found', on_delete=models.CASCADE,\r\n db_column='notify_id_fp')\r\n notify_id_lp = models.ForeignKey(Notification, related_name='reach_match_to_who_lost', on_delete=models.CASCADE,\r\n db_column='notify_id_lp')\r\n\r\n class Meta:\r\n db_table = 'matched_Person'\r\n Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== --- backend/find_losts/models.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/find_losts/models.py (date 1621853397255) @@ -15,26 +15,29 @@ db_table = 'lost_object' +def lost_person_images(instance,filename): + return f"lostperson/{instance.pk}.jpg" + + +class LostPersonImage(models.Model): + id_lp = models.IntegerField + image_number = models.IntegerField + image = models.ImageField(blank=True, null=True, upload_to=lost_person_images) + + class Meta: + db_table = 'lost_person_image' + + class LostPerson(models.Model): - id = models.OneToOneField(LostObject, primary_key=True, on_delete=models.CASCADE, db_column='id') + id = models.OneToOneField(LostObject, primary_key=True, on_delete=models.CASCADE, db_column='id', blank=True) name = models.CharField(max_length=150) + #person_image = models.ManyToManyField(LostPersonImage, db_column='images', related_name='images') + image = models.ImageField(blank=True, null=True, upload_to=lost_person_images) class Meta: db_table = 'lost_person' -class LostPersonImage(models.Model): - #id = models.AutoField(primary_key=True) - id = models.OneToOneField(LostPerson, primary_key=True, on_delete=models.CASCADE, db_column='id') - image = models.ImageField(unique=True) - - class Meta: - db_table = 'lost_person_image' - unique_together = (('id', 'image'),) - -def lost_item_image(instance,filename): - return f"lost_item/{instance.pk}.jpg/" - class LostItem(models.Model): id = models.OneToOneField(LostObject, primary_key=True, on_delete=models.CASCADE, db_column='id') type = models.CharField(max_length=20) @@ -42,13 +45,12 @@ brand = models.CharField(max_length=50) description = models.CharField(max_length=700) serial_number = models.CharField(max_length=100, blank=True, null=True) - image = models.ImageField(blank=True, null=True, upload_to=lost_item_image) + image = models.ImageField(blank=True, null=True) class Meta: db_table = 'lost_item' - class FoundObject(models.Model): date = models.DateField() longitude = models.DecimalField(max_digits=14, decimal_places=10, default=0.0) @@ -61,9 +63,14 @@ db_table = 'found_object' +def found_person_images(instance,filename): + return f"foundperson/{instance.pk}.jpg" + + class FoundPerson(models.Model): id = models.OneToOneField(FoundObject, primary_key=True, on_delete=models.CASCADE, db_column='id') name = models.CharField(max_length=150, blank=True, null=True) + image = models.ImageField(blank=True, null=True, upload_to=found_person_images) class Meta: db_table = 'found_person' @@ -85,7 +92,7 @@ brand = models.CharField(max_length=50) description = models.CharField(max_length=700) serial_number = models.CharField(max_length=100, blank=True, null=True) - #image = models.ImageField(unique=True) + image = models.ImageField(null=True, blank=True) class Meta: db_table = 'found_item' Index: backend/user_account/models.py IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.BaseRevisionTextPatchEP <+>from django.db import models\r\nfrom django.contrib.auth.models import AbstractUser\r\nfrom rest_framework_simplejwt.tokens import RefreshToken\r\n\r\n\r\n# Create your models here.\r\n\r\ndef profile_pic_dir(instance, filename):\r\n return 'profile/{0}/'.format(filename)\r\n\r\n\r\ndef idcard_pic_dir(instance, filename):\r\n return 'idcard/{0}/'.format(filename)\r\n\r\n\r\nclass User(AbstractUser):\r\n email = models.EmailField(max_length=1, blank=True)\r\n phone = models.CharField(max_length=20, unique=True)\r\n birthdate = models.DateField()\r\n city = models.CharField(max_length=35)\r\n profile_pic = models.ImageField(blank=True, null=True, upload_to=profile_pic_dir)\r\n id_card_pic = models.ImageField(blank=True, null=True, upload_to=idcard_pic_dir)\r\n\r\n def __str__(self):\r\n return self.username\r\n\r\n def tokens(self):\r\n refresh = RefreshToken.for_user(self)\r\n return {\r\n 'refresh': str(refresh),\r\n 'access': str(refresh.access_token)\r\n }\r\n\r\n class Meta:\r\n db_table = 'user'\r\n Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== --- backend/user_account/models.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/user_account/models.py (date 1621784448372) @@ -6,11 +6,11 @@ # Create your models here. def profile_pic_dir(instance, filename): - return 'profile/{0}/'.format(filename) + return f"profile/{filename}" def idcard_pic_dir(instance, filename): - return 'idcard/{0}/'.format(filename) + return f"idcard/{filename}" class User(AbstractUser): Index: backend/find_losts/views.py IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.BaseRevisionTextPatchEP <+>from django.shortcuts import render\r\nfrom rest_framework_simplejwt.tokens import RefreshToken, TokenError\r\nfrom rest_framework import serializers\r\nfrom django.http import HttpResponse\r\nfrom .models import LostObject, LostItem, LostPerson, LostPersonImage\r\nfrom rest_framework import status\r\nfrom .serializers import *\r\nfrom rest_framework import generics\r\nfrom rest_framework.views import APIView\r\nfrom rest_framework.response import Response\r\nfrom rest_framework.reverse import reverse\r\nfrom rest_framework import status\r\nfrom rest_framework import viewsets\r\nfrom rest_framework import permissions\r\n\r\n# Create your views here.\r\nclass LostObjectView(generics.ListCreateAPIView):\r\n queryset = LostObject.objects.all()\r\n serializer_class = LostObjectSerializer\r\n\r\n\r\nclass LostObjectDetailsView(generics.RetrieveUpdateDestroyAPIView):\r\n queryset = LostObject.objects.all()\r\n serializer_class = LostObjectSerializer\r\n\r\n\r\nclass LostItemView(generics.ListCreateAPIView):\r\n queryset = LostItem.objects.all()\r\n serializer_class = LostItemSerializer\r\n\r\nclass LostItemDetailsView(generics.RetrieveUpdateDestroyAPIView):\r\n queryset = LostItem.objects.all()\r\n serializer_class = LostItemSerializer\r\n\r\n\r\nclass LostPersonView(generics.ListCreateAPIView):\r\n queryset = LostPerson.objects.all()\r\n serializer_class = LostPersonSerializer\r\n def post(self, request):\r\n serializer = self.serializer_class(data=request.data)\r\n if serializer.is_valid():\r\n serializer.save()\r\n return Response(serializer.data, status=status.HTTP_204_NO_CONTENT)\r\n\r\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\r\n\r\nclass LostPersonDetailsView(generics.RetrieveUpdateDestroyAPIView):\r\n queryset = LostPerson.objects.all()\r\n serializer_class = LostPersonSerializer\r\n\r\n\r\nclass LostPersonImageView(generics.ListCreateAPIView):\r\n queryset = LostPersonImage.objects.all()\r\n serializer_class = LostPersonImageSerializer\r\n\r\nclass LostPersonImageDetailsView(generics.RetrieveUpdateDestroyAPIView):\r\n queryset = LostPersonImage.objects.all()\r\n serializer_class = LostPersonImageSerializer\r\n\r\n\r\nclass FoundObjectView(generics.ListCreateAPIView):\r\n queryset = FoundObject.objects.all()\r\n serializer_class = FoundObjectSerializer\r\n\r\nclass FoundObjectDetalisView(generics.RetrieveUpdateDestroyAPIView):\r\n queryset = FoundObject.objects.all()\r\n serializer_class = FoundObjectSerializer\r\n\r\n\r\nclass FoundItemView(generics.ListCreateAPIView):\r\n queryset = FoundItem.objects.all()\r\n serializer_class = FoundItemSerializer\r\n\r\nclass FoundItemDetailsView(generics.RetrieveUpdateDestroyAPIView):\r\n queryset = FoundItem.objects.all()\r\n serializer_class = FoundItemSerializer\r\n\r\n\r\nclass FoundPersonView(generics.ListCreateAPIView):\r\n queryset = FoundPerson.objects.all()\r\n serializer_class = FoundPersonSerializer\r\n\r\n\r\nclass FoundPersonImageView(generics.ListCreateAPIView):\r\n queryset = FoundPersonImage.objects.all()\r\n serializer_class = FoundPersonImageSerializer\r\n\r\n\r\nclass LostObject_cityView(generics.ListAPIView):\r\n serializer_class = LostObjectSerializer\r\n\r\n def get_queryset(self):\r\n obj = self.kwargs['city']\r\n return LostObject.objects.filter(city=obj)\r\n\r\n\r\nclass MapView(generics.ListAPIView):\r\n queryset = FoundItem.objects.select_related('id')\r\n serializer_class = MapSerializer\r\n \r\n#@api_view()\r\n#def comp_lost_itemView(request,pk):\r\n Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== --- backend/find_losts/views.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/find_losts/views.py (date 1621860000816) @@ -12,6 +12,7 @@ from rest_framework import status from rest_framework import viewsets from rest_framework import permissions +from rest_framework.parsers import MultiPartParser, FormParser # Create your views here. class LostObjectView(generics.ListCreateAPIView): @@ -24,9 +25,20 @@ serializer_class = LostObjectSerializer -class LostItemView(generics.ListCreateAPIView): +class LostItemView(generics.GenericAPIView): queryset = LostItem.objects.all() serializer_class = LostItemSerializer + parser_classes = (MultiPartParser, FormParser) + + def create(self, request): + print(request.data) + serializer = self.get_serializer(data=request.data) + if serializer.is_valid(): + serializer.save() + return Response(serializer.data, status=status.HTTP_201_CREATED) + + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + class LostItemDetailsView(generics.RetrieveUpdateDestroyAPIView): queryset = LostItem.objects.all() @@ -34,15 +46,10 @@ class LostPersonView(generics.ListCreateAPIView): + http_method_names = ['post'] queryset = LostPerson.objects.all() serializer_class = LostPersonSerializer - def post(self, request): - serializer = self.serializer_class(data=request.data) - if serializer.is_valid(): - serializer.save() - return Response(serializer.data, status=status.HTTP_204_NO_CONTENT) - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class LostPersonDetailsView(generics.RetrieveUpdateDestroyAPIView): queryset = LostPerson.objects.all() @@ -77,6 +84,7 @@ class FoundPersonView(generics.ListCreateAPIView): + http_method_names = ['post'] queryset = FoundPerson.objects.all() serializer_class = FoundPersonSerializer @@ -86,17 +94,6 @@ serializer_class = FoundPersonImageSerializer -class LostObject_cityView(generics.ListAPIView): - serializer_class = LostObjectSerializer - - def get_queryset(self): - obj = self.kwargs['city'] - return LostObject.objects.filter(city=obj) - - class MapView(generics.ListAPIView): queryset = FoundItem.objects.select_related('id') serializer_class = MapSerializer - -#@api_view() -#def comp_lost_itemView(request,pk): Index: backend/user_account/views.py IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.BaseRevisionTextPatchEP <+>from rest_framework import generics\r\nfrom rest_framework import status\r\nfrom rest_framework.generics import GenericAPIView\r\nfrom rest_framework.permissions import IsAuthenticated\r\nfrom rest_framework.response import Response\r\nfrom rest_framework.views import APIView\r\nfrom .serializers import SignupSerializer, LogoutSerializer, WhoFoundItemSerializer\r\nfrom .models import User\r\nfrom find_losts.models import LostObject, FoundObject\r\n\r\n# Create your views here.\r\n\r\n\r\nclass SignupView(generics.CreateAPIView):\r\n serializer_class = SignupSerializer\r\n\r\n\r\nclass LoginView(APIView):\r\n permission_classes = [IsAuthenticated]\r\n\r\n def post(self, request):\r\n user = request.user\r\n user_pic = \"\"\r\n losts = list(LostObject.objects.filter(user_id=user.pk).values('id'))\r\n founds = list(FoundObject.objects.filter(user_id=user.pk).values('id'))\r\n if user.profile_pic is not None:\r\n user_pic = user.profile_pic.url\r\n response = {\r\n 'id': user.pk,\r\n 'username': user.first_name,\r\n 'email': user.username,\r\n 'phone': user.phone,\r\n 'city': user.city,\r\n 'birthdate': user.birthdate,\r\n 'profile_pic': user_pic,\r\n 'losts': losts,\r\n 'founds': founds\r\n }\r\n return Response({'user': response}, status=status.HTTP_200_OK)\r\n\r\n\r\nclass LogoutView(GenericAPIView):\r\n serializer_class = LogoutSerializer\r\n permission_classes = {IsAuthenticated, }\r\n\r\n def post(self, request):\r\n serializer = self.serializer_class(data=request.data)\r\n if serializer.is_valid():\r\n serializer.save()\r\n return Response(serializer.data, status=status.HTTP_204_NO_CONTENT)\r\n\r\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\r\n\r\n\r\nclass WhoFoundItemView(generics.RetrieveAPIView):\r\n queryset = User.objects.all()\r\n serializer_class = WhoFoundItemSerializer\r\n lookup_field = 'id'\r\n Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== --- backend/user_account/views.py (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/user_account/views.py (date 1621784088894) @@ -12,6 +12,7 @@ class SignupView(generics.CreateAPIView): + queryset = User.objects.all() serializer_class = SignupSerializer @@ -23,7 +24,7 @@ user_pic = "" losts = list(LostObject.objects.filter(user_id=user.pk).values('id')) founds = list(FoundObject.objects.filter(user_id=user.pk).values('id')) - if user.profile_pic is not None: + if user.profile_pic: user_pic = user.profile_pic.url response = { 'id': user.pk, Index: backend/.idea/misc.xml IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.BaseRevisionTextPatchEP <+>\r\n\r\n \r\n \r\n \r\n Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== --- backend/.idea/misc.xml (revision bfce80dfbed98c3cdb08a2bc51083229e26cebc2) +++ backend/.idea/misc.xml (date 1621778344681) @@ -1,6 +1,6 @@ - + ================================================ FILE: .idea/vcs.xml ================================================ ================================================ FILE: README.md ================================================ # The Team ### Team Members * Team Leader : Esraa Sayed Ahmed * Team Member 1 : Dina Mishahed Mousa * Team Member 2 : Abdelrahman Mamdouh Ismail * Team Member 3 : Ahmed Mostafa Abdelaziz * Team Member 4 : Walid Mohamed El-Sayed ## Problem Statement The thought of a family member, a friend, or someone else you care about going missing can be terrifying. You don’t know where they are, if they’re hurt or if they need help. When this person lives with a mental health condition, the situation may be even more serious. Also, time required for finding lost person is may be long so, taking action quickly can make a difference. ## Solution * Steps taken for solving the problem.
First, parents that lose their child will add his/her picture in the application then If anyone suspects that the child has been kidnapped or lost, he will open the application and the camera and point the camera at the child. then the application compare between the child's photo and all the lost children's photos. If a match occurs, it will appear to the user that the child has been kidnapped.
* Frameworks/Tools/Technologies stacks used.
We use Pycharm framework(Django framework), face recognition tools, Android Studio, PostgreSQL Database
We used Django framework :-
Where a lot of libraries are available to help us detect and recongize the faces.
We used PostgreSQL Database :-
Where it is suitable for us to update the data easier than MySQL.
We used Android Studio :-
This project can be converted into an application that anyone can use easily. ## Methodology * Use Case: ![Screenshot 2021-09-23 165529](https://user-images.githubusercontent.com/63111171/134538337-3451c5cb-f019-4b5e-9f38-5e9d975a4f6a.png) * Dataset: TensorFlow. * Database: PostgreSQL SQLite. * ML Kit for Firebase (For real-time detection) * [Face Detection and Recognition Algorithms.docx](https://github.com/abdelrhman-mamdouh/J6_Hackathon_Jefive/files/7219037/Face.Detection.and.Recognition.Algorithms.docx) ## System Architecture proposal (if any) Explain the following in detail: * Mobile Phone device to test our project by Android Studio. * ![image](https://user-images.githubusercontent.com/63111171/134538831-76884e8e-fd1b-4ea3-b59b-e95fd5cc43df.png) * Before recognizing a face, it is first essential to detect and extract the faces from the original pictures. For recognizing a face, the algorithms compare only faces. Any other element in the picture that is not part of a face deteriorates the recognition. ## Screenshots ## Step to run the software * Install Python 3.8.3 * Install Django Framework * Install face-recognition library * Install Android Studio * Download ngrok tool to help you share a app running on your local machine with the world. * Run app by Android studio and copy ngrok code to good point app. ================================================ FILE: app/.gitignore ================================================ /build ================================================ FILE: app/.idea/workspace.xml ================================================ 1607176500258 ================================================ FILE: app/build.gradle ================================================ apply plugin: 'com.android.application' android { compileSdkVersion 31 buildToolsVersion "30.0.1" defaultConfig { applicationId "com.helloworld.goodpoint" minSdkVersion 21 targetSdkVersion 30 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" vectorDrawables.useSupportLibrary = true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } aaptOptions { noCompress "tflite" } } apply plugin: 'com.android.application' apply plugin: 'com.google.gms.google-services' dependencies { implementation platform('com.google.firebase:firebase-bom:28.4.1') implementation 'com.google.firebase:firebase-analytics' implementation 'com.github.d-max:spots-dialog:1.1@aar' implementation fileTree(dir: "libs", include: ["*.jar"]) implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'androidx.constraintlayout:constraintlayout:2.0.4' implementation 'androidx.legacy:legacy-support-v4:1.0.0' implementation 'com.google.android.gms:play-services-maps:17.0.0' implementation 'com.google.android.gms:play-services-places:17.0.0' implementation 'com.android.support:support-v4:30.0.1' implementation 'com.android.support:design:30.0.1' implementation 'com.google.android.gms:play-services-location:17.1.0' implementation project(path: ':mylibrary') implementation 'com.google.firebase:firebase-ml-vision:24.1.0' testImplementation 'junit:junit:4.13.1' androidTestImplementation 'androidx.test.ext:junit:1.1.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' implementation 'com.android.support:support-annotations:28.0.0' implementation 'com.google.android.material:material:1.3.0' implementation 'com.chaos.view:pinview:1.4.3' implementation 'androidx.fragment:fragment:1.2.5' implementation 'com.github.Shashank02051997:FancyToast-Android:0.1.8' //recyclerView implementation "androidx.recyclerview:recyclerview:1.1.0" // For control over item selection of both touch and mouse driven selection implementation "androidx.recyclerview:recyclerview-selection:1.1.0-rc03" implementation 'com.google.android.material:material:1.3.0' implementation 'com.android.support:design:30.0.0' //glide implementation 'com.github.bumptech.glide:glide:4.4.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.4.0' //sdp and ssp implementation 'com.intuit.sdp:sdp-android:1.0.6' implementation 'com.intuit.ssp:ssp-android:1.0.6' //retrofit implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0' //circular image implementation 'de.hdodenhof:circleimageview:3.1.0' implementation 'com.squareup.retrofit2:converter-scalars:2.1.0' // implementation "com.android.support:support-core-utils" // for camerax def camerax_version = '1.1.0-alpha09' implementation "androidx.camera:camera-core:${camerax_version}" implementation "androidx.camera:camera-camera2:${camerax_version}" implementation "androidx.camera:camera-view:1.0.0-alpha29" implementation "androidx.camera:camera-lifecycle:${camerax_version}" // // for google material elements implementation 'com.google.android.material:material:1.1.0' // added MLKit dependencies for face detector implementation 'com.google.mlkit:face-detection:16.1.2' implementation 'com.google.mlkit:object-detection-custom:16.3.0' implementation 'org.tensorflow:tensorflow-lite:+' implementation 'com.google.android.gms:play-services-vision:20.1.3' } ================================================ FILE: app/google-services.json ================================================ { "project_info": { "project_number": "311132691163", "project_id": "goodpoint-72323", "storage_bucket": "goodpoint-72323.appspot.com" }, "client": [ { "client_info": { "mobilesdk_app_id": "1:311132691163:android:bbb123fe5d1b460c1b0afe", "android_client_info": { "package_name": "com.helloworld.goodpoint" } }, "oauth_client": [ { "client_id": "311132691163-2i2t19bnloefe5k6dd7u9i10jvvsbejg.apps.googleusercontent.com", "client_type": 3 } ], "api_key": [ { "current_key": "AIzaSyCVfw7eY2thtJlQHAwMLIXKW6BcpMFOqps" } ], "services": { "appinvite_service": { "other_platform_oauth_client": [ { "client_id": "311132691163-2i2t19bnloefe5k6dd7u9i10jvvsbejg.apps.googleusercontent.com", "client_type": 3 } ] } } } ], "configuration_version": "1" } ================================================ FILE: app/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # You can control the set of applied configuration files using the # proguardFiles setting in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} # Uncomment this to preserve the line number information for # debugging stack traces. #-keepattributes SourceFile,LineNumberTable # If you keep the line number information, uncomment this to # hide the original source file name. #-renamesourcefileattribute SourceFile ================================================ FILE: app/src/androidTest/java/com/helloworld/goodpoint/ExampleInstrumentedTest.java ================================================ package com.helloworld.goodpoint; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see Testing documentation */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.helloworld.goodpoint", appContext.getPackageName()); } } ================================================ FILE: app/src/debug/res/values/google_maps_api.xml ================================================ AIzaSyDSlxIGBsvMZkpSZTMLnQ8MVKup40YFR6g ================================================ FILE: app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: app/src/main/assets/face_model_v5.tflite ================================================ [File too large to display: 36.8 MB] ================================================ FILE: app/src/main/assets/labelmap.txt ================================================ person bicycle car motorcycle airplane bus train truck boat traffic light fire hydrant ??? stop sign parking meter bench bird cat dog horse sheep cow elephant bear zebra giraffe ??? backpack umbrella ??? ??? handbag tie suitcase frisbee skis snowboard sports ball kite baseball bat baseball glove skateboard surfboard tennis racket bottle ??? wine glass cup fork knife spoon bowl banana apple sandwich orange broccoli carrot hot dog pizza donut cake chair couch potted plant bed ??? dining table ??? ??? toilet ??? tv laptop mouse remote keyboard cell phone microwave oven toaster sink refrigerator ??? book clock vase scissors teddy bear hair drier toothbrush ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/App.java ================================================ package com.helloworld.goodpoint; import android.app.Application; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.os.Build; import com.helloworld.goodpoint.pojo.User; import com.helloworld.goodpoint.ui.myService.NotificationBroadcast; public class App extends Application { private static App mInstance; private static Resources res; @Override public void onCreate() { super.onCreate(); mInstance = this; res = getResources(); IntentFilter filter = new IntentFilter(); filter.addAction("android.intent.action.BOOT_COMPLETED"); filter.addAction("android.intent.action.LOCKED_BOOT_COMPLETED"); filter.addAction("android.intent.action.QUICKBOOT_POWERON"); filter.addAction("android.intent.action.MY_PACKAGE_REPLACED"); filter.addAction("com.helloworld.goodpoint.ui.myService.NotificationBroadcast"); filter.addCategory("android.intent.category.DEFAULT"); registerReceiver(new NotificationBroadcast(), filter); } public static App getInstance() { return mInstance; } public static Resources getResourses() { return res; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/adapter/MyExpandableListAdapter.java ================================================ package com.helloworld.goodpoint.adapter; import android.content.Context; import android.graphics.Typeface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.TextView; import com.helloworld.goodpoint.R; import java.util.List; import java.util.Map; public class MyExpandableListAdapter extends BaseExpandableListAdapter { private Context context; private Map> objects; private List groupList; public MyExpandableListAdapter(Context context, List groupList, Map> objects) { this.context = context; this.objects = objects; this.groupList = groupList; } @Override public int getGroupCount() { return objects.size(); } @Override public int getChildrenCount(int i) { return objects.get(groupList.get(i)).size(); } @Override public Object getGroup(int i) { return groupList.get(i); } @Override public Object getChild(int i, int i1) { return objects.get(groupList.get(i)).get(i1); } @Override public long getGroupId(int i) { return i; } @Override public long getChildId(int i, int i1) { return i1; } @Override public boolean hasStableIds() { return true; } @Override public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) { String group = getGroup(i).toString(); if(view == null){ LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.group_item, null); } TextView item = view.findViewById(R.id.group); item.setTypeface(null, Typeface.BOLD); item.setText(group); return view; } @Override public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) { String model = getChild(i,i1).toString(); if (view == null){ LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.child_item, null); } TextView item = view.findViewById(R.id.model); item.setText(model); return view; } @Override public boolean isChildSelectable(int i, int i1) { return true; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/adapter/NotificationListAdapter.java ================================================ package com.helloworld.goodpoint.adapter; import android.content.Context; import android.graphics.Color; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.gson.JsonObject; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.pojo.NotificationItem; import com.helloworld.goodpoint.pojo.User; import com.helloworld.goodpoint.retrofit.ApiClient; import com.helloworld.goodpoint.retrofit.ApiInterface; import com.helloworld.goodpoint.ui.PrefManager; import org.jetbrains.annotations.NotNull; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import de.hdodenhof.circleimageview.CircleImageView; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class NotificationListAdapter extends ArrayAdapter { Context context; List list; Locale locale = new Locale("en"); public NotificationListAdapter(@NonNull Context context, int resource, @NonNull List list) { super(context, resource, list); this.context = context; this.list = list; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { View notificationItem = convertView; ViewHolder viewHolder; final int revposition = list.size()-position-1; if(notificationItem == null){ notificationItem = createItem(parent); viewHolder = new ViewHolder(notificationItem); notificationItem.setTag(viewHolder); }else viewHolder = (ViewHolder) notificationItem.getTag(); if(list.get(revposition).isRead()) viewHolder.getLayout().setBackgroundColor(Color.WHITE); else viewHolder.getLayout().setBackgroundColor(context.getResources().getColor(R.color.table_detail)); setItemDetails(viewHolder,revposition); return notificationItem; } private void setItemDetails(@NotNull ViewHolder viewHolder, int revposition) { viewHolder.getTitle().setText(list.get(revposition).getTitle()); Date date = list.get(revposition).getDate(); SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm",locale); String date_time = dateFormat.format(date); viewHolder.getDate().setText(date_time); viewHolder.getDescription().setText(list.get(revposition).getDescription()); switch (list.get(revposition).getType()){ case 1: case 2: viewHolder.getImageView().setImageResource(R.drawable.ic_account_circle); break; case 3: viewHolder.getImageView().setImageResource(R.drawable.ic_baseline_fact_check_24); break; case 4: case 5: viewHolder.getImageView().setImageResource(R.drawable.ic_baseline_assignment_turned_in_24); break; } if(!list.get(revposition).isSent()){ ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(context).getNGROKLink()).create(ApiInterface.class); Call call = apiInterface.updateSent(list.get(revposition).getId(),true); call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { Log.e("TAG", "onResponse: "+response.body()); } @Override public void onFailure(Call call, Throwable t) { Log.e("TAG", "onFailure: "+t.getMessage()); } }); } } private View createItem(ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); return inflater.inflate(R.layout.notification_item, parent, false); } private class ViewHolder{ private View convertView; private TextView title, date, description; private CircleImageView imageView; private LinearLayout layout; public ViewHolder(View view) { this.convertView = view; } public TextView getTitle() { if(title == null) title = convertView.findViewById(R.id.notification_title); return title; } public TextView getDate() { if(date == null) date = convertView.findViewById(R.id.notification_date); return date; } public TextView getDescription() { if(description == null) description = convertView.findViewById(R.id.notification_description); return description; } public CircleImageView getImageView() { if(imageView == null) imageView = convertView.findViewById(R.id.notification_image); return imageView; } public LinearLayout getLayout() { if(layout == null) layout = convertView.findViewById(R.id.notification_layout); return layout; } } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/detection/CameraActivity.java ================================================ /* * Copyright 2019 The TensorFlow Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helloworld.goodpoint.detection; import android.Manifest; import android.app.Fragment; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.hardware.Camera; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraManager; import android.hardware.camera2.params.StreamConfigurationMap; import android.media.Image; import android.media.Image.Plane; import android.media.ImageReader; import android.media.ImageReader.OnImageAvailableListener; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Trace; import android.util.Size; import android.view.Surface; import android.view.View; import android.view.WindowManager; import android.widget.CompoundButton; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.SwitchCompat; import androidx.appcompat.widget.Toolbar; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.detection.env.ImageUtils; import com.helloworld.goodpoint.detection.env.Logger; import java.nio.ByteBuffer; public abstract class CameraActivity extends AppCompatActivity implements OnImageAvailableListener, Camera.PreviewCallback, CompoundButton.OnCheckedChangeListener { private static final Logger LOGGER = new Logger(); private static final int PERMISSIONS_REQUEST = 1; private static final String PERMISSION_CAMERA = Manifest.permission.CAMERA; protected int previewWidth = 0; protected int previewHeight = 0; private boolean debug = false; private Handler handler; private HandlerThread handlerThread; private boolean useCamera2API; private boolean isProcessingFrame = false; private byte[][] yuvBytes = new byte[3][]; private int[] rgbBytes = null; private int yRowStride; private Runnable postInferenceCallback; private Runnable imageConverter; private LinearLayout bottomSheetLayout; private LinearLayout gestureLayout; //private BottomSheetBehavior sheetBehavior; protected ImageButton Crop; private SwitchCompat apiSwitchCompat; @Override protected void onCreate(final Bundle savedInstanceState) { LOGGER.d("onCreate " + this); super.onCreate(null); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.tfe_od_activity_camera); Toolbar toolbar = findViewById(R.id.toolbar); // setSupportActionBar(toolbar); // getSupportActionBar().setDisplayShowTitleEnabled(false); if (hasPermission()) { setFragment(); } else { requestPermission(); } Crop = findViewById(R.id.Crop); Crop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent My = new Intent(); setResult(RESULT_OK,My); finish(); } }); } protected int[] getRgbBytes() { imageConverter.run(); return rgbBytes; } /** Callback for android.hardware.Camera API */ @Override public void onPreviewFrame(final byte[] bytes, final Camera camera) { if (isProcessingFrame) { LOGGER.w("Dropping frame!"); return; } try { // Initialize the storage bitmaps once when the resolution is known. if (rgbBytes == null) { Camera.Size previewSize = camera.getParameters().getPreviewSize(); previewHeight = previewSize.height; previewWidth = previewSize.width; rgbBytes = new int[previewWidth * previewHeight]; onPreviewSizeChosen(new Size(previewSize.width, previewSize.height), 90); } } catch (final Exception e) { LOGGER.e(e, "Exception!"); return; } isProcessingFrame = true; yuvBytes[0] = bytes; yRowStride = previewWidth; imageConverter = new Runnable() { @Override public void run() { ImageUtils.convertYUV420SPToARGB8888(bytes, previewWidth, previewHeight, rgbBytes); } }; postInferenceCallback = new Runnable() { @Override public void run() { camera.addCallbackBuffer(bytes); isProcessingFrame = false; } }; processImage(); } /** Callback for Camera2 API */ @Override public void onImageAvailable(final ImageReader reader) { // We need wait until we have some size from onPreviewSizeChosen if (previewWidth == 0 || previewHeight == 0) { return; } if (rgbBytes == null) { rgbBytes = new int[previewWidth * previewHeight]; } try { final Image image = reader.acquireLatestImage(); if (image == null) { return; } if (isProcessingFrame) { image.close(); return; } isProcessingFrame = true; Trace.beginSection("imageAvailable"); final Plane[] planes = image.getPlanes(); fillBytes(planes, yuvBytes); yRowStride = planes[0].getRowStride(); final int uvRowStride = planes[1].getRowStride(); final int uvPixelStride = planes[1].getPixelStride(); imageConverter = new Runnable() { @Override public void run() { ImageUtils.convertYUV420ToARGB8888( yuvBytes[0], yuvBytes[1], yuvBytes[2], previewWidth, previewHeight, yRowStride, uvRowStride, uvPixelStride, rgbBytes); } }; postInferenceCallback = new Runnable() { @Override public void run() { image.close(); isProcessingFrame = false; } }; processImage(); } catch (final Exception e) { LOGGER.e(e, "Exception!"); Trace.endSection(); return; } Trace.endSection(); } @Override public synchronized void onStart() { LOGGER.d("onStart " + this); super.onStart(); } @Override public synchronized void onResume() { LOGGER.d("onResume " + this); super.onResume(); handlerThread = new HandlerThread("inference"); handlerThread.start(); handler = new Handler(handlerThread.getLooper()); } @Override public synchronized void onPause() { LOGGER.d("onPause " + this); handlerThread.quitSafely(); try { handlerThread.join(); handlerThread = null; handler = null; } catch (final InterruptedException e) { LOGGER.e(e, "Exception!"); } super.onPause(); } @Override public synchronized void onStop() { LOGGER.d("onStop " + this); super.onStop(); } @Override public synchronized void onDestroy() { LOGGER.d("onDestroy " + this); super.onDestroy(); } protected synchronized void runInBackground(final Runnable r) { if (handler != null) { handler.post(r); } } @Override public void onRequestPermissionsResult( final int requestCode, final String[] permissions, final int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == PERMISSIONS_REQUEST) { if (allPermissionsGranted(grantResults)) { setFragment(); } else { requestPermission(); } } } private static boolean allPermissionsGranted(final int[] grantResults) { for (int result : grantResults) { if (result != PackageManager.PERMISSION_GRANTED) { return false; } } return true; } private boolean hasPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return checkSelfPermission(PERMISSION_CAMERA) == PackageManager.PERMISSION_GRANTED; } else { return true; } } private void requestPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (shouldShowRequestPermissionRationale(PERMISSION_CAMERA)) { Toast.makeText( CameraActivity.this, "Camera permission is required for this demo", Toast.LENGTH_LONG) .show(); } requestPermissions(new String[] {PERMISSION_CAMERA}, PERMISSIONS_REQUEST); } } // Returns true if the device supports the required hardware level, or better. private boolean isHardwareLevelSupported( CameraCharacteristics characteristics, int requiredLevel) { int deviceLevel = characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL); if (deviceLevel == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) { return requiredLevel == deviceLevel; } // deviceLevel is not LEGACY, can use numerical sort return requiredLevel <= deviceLevel; } private String chooseCamera() { final CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); try { for (final String cameraId : manager.getCameraIdList()) { final CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); // We don't use a front facing camera in this sample. final Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING); if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) { continue; } final StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); if (map == null) { continue; } // Fallback to camera1 API for internal cameras that don't have full support. // This should help with legacy situations where using the camera2 API causes // distorted or otherwise broken previews. useCamera2API = (facing == CameraCharacteristics.LENS_FACING_EXTERNAL) || isHardwareLevelSupported( characteristics, CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL); LOGGER.i("Camera API lv2?: %s", useCamera2API); return cameraId; } } catch (CameraAccessException e) { LOGGER.e(e, "Not allowed to access camera"); } return null; } protected void setFragment() { String cameraId = chooseCamera(); Fragment fragment; if (useCamera2API) { CameraConnectionFragment camera2Fragment = CameraConnectionFragment.newInstance( new CameraConnectionFragment.ConnectionCallback() { @Override public void onPreviewSizeChosen(final Size size, final int rotation) { previewHeight = size.getHeight(); previewWidth = size.getWidth(); CameraActivity.this.onPreviewSizeChosen(size, rotation); } }, this, getLayoutId(), getDesiredPreviewFrameSize()); camera2Fragment.setCamera(cameraId); fragment = camera2Fragment; } else { fragment = new LegacyCameraConnectionFragment(this, getLayoutId(), getDesiredPreviewFrameSize()); } getFragmentManager().beginTransaction().replace(R.id.container, fragment).commit(); } protected void fillBytes(final Plane[] planes, final byte[][] yuvBytes) { // Because of the variable row stride it's not possible to know in // advance the actual necessary dimensions of the yuv planes. for (int i = 0; i < planes.length; ++i) { final ByteBuffer buffer = planes[i].getBuffer(); if (yuvBytes[i] == null) { LOGGER.d("Initializing buffer %d at size %d", i, buffer.capacity()); yuvBytes[i] = new byte[buffer.capacity()]; } buffer.get(yuvBytes[i]); } } public boolean isDebug() { return debug; } protected void readyForNextImage() { if (postInferenceCallback != null) { postInferenceCallback.run(); } } protected int getScreenOrientation() { switch (getWindowManager().getDefaultDisplay().getRotation()) { case Surface.ROTATION_270: return 270; case Surface.ROTATION_180: return 180; case Surface.ROTATION_90: return 90; default: return 0; } } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { setUseNNAPI(isChecked); if (isChecked) apiSwitchCompat.setText("NNAPI"); else apiSwitchCompat.setText("TFLITE"); } protected abstract void processImage(); protected abstract void onPreviewSizeChosen(final Size size, final int rotation); protected abstract int getLayoutId(); protected abstract Size getDesiredPreviewFrameSize(); protected abstract void setNumThreads(int numThreads); protected abstract void setUseNNAPI(boolean isChecked); } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/detection/CameraConnectionFragment.java ================================================ /* * Copyright 2019 The TensorFlow Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helloworld.goodpoint.detection; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.app.Fragment; import android.content.Context; import android.content.DialogInterface; import android.content.res.Configuration; import android.graphics.ImageFormat; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.SurfaceTexture; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCaptureSession; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraDevice; import android.hardware.camera2.CameraManager; import android.hardware.camera2.CaptureRequest; import android.hardware.camera2.CaptureResult; import android.hardware.camera2.TotalCaptureResult; import android.hardware.camera2.params.StreamConfigurationMap; import android.media.ImageReader; import android.media.ImageReader.OnImageAvailableListener; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.text.TextUtils; import android.util.Size; import android.util.SparseIntArray; import android.view.LayoutInflater; import android.view.Surface; import android.view.TextureView; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.detection.customview.AutoFitTextureView; import com.helloworld.goodpoint.detection.env.Logger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; @SuppressLint("ValidFragment") public class CameraConnectionFragment extends Fragment { private static final Logger LOGGER = new Logger(); /** * The camera preview size will be chosen to be the smallest frame by pixel size capable of * containing a DESIRED_SIZE x DESIRED_SIZE square. */ private static final int MINIMUM_PREVIEW_SIZE = 320; /** Conversion from screen rotation to JPEG orientation. */ private static final SparseIntArray ORIENTATIONS = new SparseIntArray(); private static final String FRAGMENT_DIALOG = "dialog"; static { ORIENTATIONS.append(Surface.ROTATION_0, 90); ORIENTATIONS.append(Surface.ROTATION_90, 0); ORIENTATIONS.append(Surface.ROTATION_180, 270); ORIENTATIONS.append(Surface.ROTATION_270, 180); } /** A {@link Semaphore} to prevent the app from exiting before closing the camera. */ private final Semaphore cameraOpenCloseLock = new Semaphore(1); /** A {@link OnImageAvailableListener} to receive frames as they are available. */ private final OnImageAvailableListener imageListener; /** The input size in pixels desired by TensorFlow (width and height of a square bitmap). */ private final Size inputSize; /** The layout identifier to inflate for this Fragment. */ private final int layout; private final ConnectionCallback cameraConnectionCallback; private final CameraCaptureSession.CaptureCallback captureCallback = new CameraCaptureSession.CaptureCallback() { @Override public void onCaptureProgressed( final CameraCaptureSession session, final CaptureRequest request, final CaptureResult partialResult) {} @Override public void onCaptureCompleted( final CameraCaptureSession session, final CaptureRequest request, final TotalCaptureResult result) {} }; /** ID of the current {@link CameraDevice}. */ private String cameraId; /** An {@link AutoFitTextureView} for camera preview. */ private AutoFitTextureView textureView; /** A {@link CameraCaptureSession } for camera preview. */ private CameraCaptureSession captureSession; /** A reference to the opened {@link CameraDevice}. */ private CameraDevice cameraDevice; /** The rotation in degrees of the camera sensor from the display. */ private Integer sensorOrientation; /** The {@link Size} of camera preview. */ private Size previewSize; /** An additional thread for running tasks that shouldn't block the UI. */ private HandlerThread backgroundThread; /** A {@link Handler} for running tasks in the background. */ private Handler backgroundHandler; /** An {@link ImageReader} that handles preview frame capture. */ private ImageReader previewReader; /** {@link CaptureRequest.Builder} for the camera preview */ private CaptureRequest.Builder previewRequestBuilder; /** {@link CaptureRequest} generated by {@link #previewRequestBuilder} */ private CaptureRequest previewRequest; /** {@link CameraDevice.StateCallback} is called when {@link CameraDevice} changes its state. */ private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() { @Override public void onOpened(final CameraDevice cd) { // This method is called when the camera is opened. We start camera preview here. cameraOpenCloseLock.release(); cameraDevice = cd; createCameraPreviewSession(); } @Override public void onDisconnected(final CameraDevice cd) { cameraOpenCloseLock.release(); cd.close(); cameraDevice = null; } @Override public void onError(final CameraDevice cd, final int error) { cameraOpenCloseLock.release(); cd.close(); cameraDevice = null; final Activity activity = getActivity(); if (null != activity) { activity.finish(); } } }; /** * {@link TextureView.SurfaceTextureListener} handles several lifecycle events on a {@link * TextureView}. */ private final TextureView.SurfaceTextureListener surfaceTextureListener = new TextureView.SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable( final SurfaceTexture texture, final int width, final int height) { openCamera(width, height); } @Override public void onSurfaceTextureSizeChanged( final SurfaceTexture texture, final int width, final int height) { configureTransform(width, height); } @Override public boolean onSurfaceTextureDestroyed(final SurfaceTexture texture) { return true; } @Override public void onSurfaceTextureUpdated(final SurfaceTexture texture) {} }; private CameraConnectionFragment( final ConnectionCallback connectionCallback, final OnImageAvailableListener imageListener, final int layout, final Size inputSize) { this.cameraConnectionCallback = connectionCallback; this.imageListener = imageListener; this.layout = layout; this.inputSize = inputSize; } /** * Given {@code choices} of {@code Size}s supported by a camera, chooses the smallest one whose * width and height are at least as large as the minimum of both, or an exact match if possible. * * @param choices The list of sizes that the camera supports for the intended output class * @param width The minimum desired width * @param height The minimum desired height * @return The optimal {@code Size}, or an arbitrary one if none were big enough */ protected static Size chooseOptimalSize(final Size[] choices, final int width, final int height) { final int minSize = Math.max(Math.min(width, height), MINIMUM_PREVIEW_SIZE); final Size desiredSize = new Size(width, height); // Collect the supported resolutions that are at least as big as the preview Surface boolean exactSizeFound = false; final List bigEnough = new ArrayList(); final List tooSmall = new ArrayList(); for (final Size option : choices) { if (option.equals(desiredSize)) { // Set the size but don't return yet so that remaining sizes will still be logged. exactSizeFound = true; } if (option.getHeight() >= minSize && option.getWidth() >= minSize) { bigEnough.add(option); } else { tooSmall.add(option); } } LOGGER.i("Desired size: " + desiredSize + ", min size: " + minSize + "x" + minSize); LOGGER.i("Valid preview sizes: [" + TextUtils.join(", ", bigEnough) + "]"); LOGGER.i("Rejected preview sizes: [" + TextUtils.join(", ", tooSmall) + "]"); if (exactSizeFound) { LOGGER.i("Exact size match found."); return desiredSize; } // Pick the smallest of those, assuming we found any if (bigEnough.size() > 0) { final Size chosenSize = Collections.min(bigEnough, new CompareSizesByArea()); LOGGER.i("Chosen size: " + chosenSize.getWidth() + "x" + chosenSize.getHeight()); return chosenSize; } else { LOGGER.e("Couldn't find any suitable preview size"); return choices[0]; } } public static CameraConnectionFragment newInstance( final ConnectionCallback callback, final OnImageAvailableListener imageListener, final int layout, final Size inputSize) { return new CameraConnectionFragment(callback, imageListener, layout, inputSize); } /** * Shows a {@link Toast} on the UI thread. * * @param text The message to show */ private void showToast(final String text) { final Activity activity = getActivity(); if (activity != null) { activity.runOnUiThread( new Runnable() { @Override public void run() { Toast.makeText(activity, text, Toast.LENGTH_SHORT).show(); } }); } } @Override public View onCreateView( final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { return inflater.inflate(layout, container, false); } @Override public void onViewCreated(final View view, final Bundle savedInstanceState) { textureView = (AutoFitTextureView) view.findViewById(R.id.texture); } @Override public void onActivityCreated(final Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onResume() { super.onResume(); startBackgroundThread(); // When the screen is turned off and turned back on, the SurfaceTexture is already // available, and "onSurfaceTextureAvailable" will not be called. In that case, we can open // a camera and start preview from here (otherwise, we wait until the surface is ready in // the SurfaceTextureListener). if (textureView.isAvailable()) { openCamera(textureView.getWidth(), textureView.getHeight()); } else { textureView.setSurfaceTextureListener(surfaceTextureListener); } } @Override public void onPause() { closeCamera(); stopBackgroundThread(); super.onPause(); } public void setCamera(String cameraId) { this.cameraId = cameraId; } /** Sets up member variables related to camera. */ private void setUpCameraOutputs() { final Activity activity = getActivity(); final CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { final CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); final StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); // Danger, W.R.! Attempting to use too large a preview size could exceed the camera // bus' bandwidth limitation, resulting in gorgeous previews but the storage of // garbage capture data. previewSize = chooseOptimalSize( map.getOutputSizes(SurfaceTexture.class), inputSize.getWidth(), inputSize.getHeight()); // We fit the aspect ratio of TextureView to the size of preview we picked. final int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_LANDSCAPE) { textureView.setAspectRatio(previewSize.getWidth(), previewSize.getHeight()); } else { textureView.setAspectRatio(previewSize.getHeight(), previewSize.getWidth()); } } catch (final CameraAccessException e) { LOGGER.e(e, "Exception!"); } catch (final NullPointerException e) { // Currently an NPE is thrown when the Camera2API is used but not supported on the // device this code runs. ErrorDialog.newInstance(getString(R.string.tfe_od_camera_error)) .show(getChildFragmentManager(), FRAGMENT_DIALOG); throw new IllegalStateException(getString(R.string.tfe_od_camera_error)); } cameraConnectionCallback.onPreviewSizeChosen(previewSize, sensorOrientation); } /** Opens the camera specified by {@link CameraConnectionFragment#cameraId}. */ private void openCamera(final int width, final int height) { setUpCameraOutputs(); configureTransform(width, height); final Activity activity = getActivity(); final CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { if (!cameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) { throw new RuntimeException("Time out waiting to lock camera opening."); } manager.openCamera(cameraId, stateCallback, backgroundHandler); } catch (final CameraAccessException e) { LOGGER.e(e, "Exception!"); } catch (final InterruptedException e) { throw new RuntimeException("Interrupted while trying to lock camera opening.", e); } } /** Closes the current {@link CameraDevice}. */ private void closeCamera() { try { cameraOpenCloseLock.acquire(); if (null != captureSession) { captureSession.close(); captureSession = null; } if (null != cameraDevice) { cameraDevice.close(); cameraDevice = null; } if (null != previewReader) { previewReader.close(); previewReader = null; } } catch (final InterruptedException e) { throw new RuntimeException("Interrupted while trying to lock camera closing.", e); } finally { cameraOpenCloseLock.release(); } } /** Starts a background thread and its {@link Handler}. */ private void startBackgroundThread() { backgroundThread = new HandlerThread("ImageListener"); backgroundThread.start(); backgroundHandler = new Handler(backgroundThread.getLooper()); } /** Stops the background thread and its {@link Handler}. */ private void stopBackgroundThread() { backgroundThread.quitSafely(); try { backgroundThread.join(); backgroundThread = null; backgroundHandler = null; } catch (final InterruptedException e) { LOGGER.e(e, "Exception!"); } } /** Creates a new {@link CameraCaptureSession} for camera preview. */ private void createCameraPreviewSession() { try { final SurfaceTexture texture = textureView.getSurfaceTexture(); assert texture != null; // We configure the size of default buffer to be the size of camera preview we want. texture.setDefaultBufferSize(previewSize.getWidth(), previewSize.getHeight()); // This is the output Surface we need to start preview. final Surface surface = new Surface(texture); // We set up a CaptureRequest.Builder with the output Surface. previewRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); previewRequestBuilder.addTarget(surface); LOGGER.i("Opening camera preview: " + previewSize.getWidth() + "x" + previewSize.getHeight()); // Create the reader for the preview frames. previewReader = ImageReader.newInstance( previewSize.getWidth(), previewSize.getHeight(), ImageFormat.YUV_420_888, 2); previewReader.setOnImageAvailableListener(imageListener, backgroundHandler); previewRequestBuilder.addTarget(previewReader.getSurface()); // Here, we create a CameraCaptureSession for camera preview. cameraDevice.createCaptureSession( Arrays.asList(surface, previewReader.getSurface()), new CameraCaptureSession.StateCallback() { @Override public void onConfigured(final CameraCaptureSession cameraCaptureSession) { // The camera is already closed if (null == cameraDevice) { return; } // When the session is ready, we start displaying the preview. captureSession = cameraCaptureSession; try { // Auto focus should be continuous for camera preview. previewRequestBuilder.set( CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE); // Flash is automatically enabled when necessary. previewRequestBuilder.set( CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH); // Finally, we start displaying the camera preview. previewRequest = previewRequestBuilder.build(); captureSession.setRepeatingRequest( previewRequest, captureCallback, backgroundHandler); } catch (final CameraAccessException e) { LOGGER.e(e, "Exception!"); } } @Override public void onConfigureFailed(final CameraCaptureSession cameraCaptureSession) { showToast("Failed"); } }, null); } catch (final CameraAccessException e) { LOGGER.e(e, "Exception!"); } } /** * Configures the necessary {@link Matrix} transformation to `mTextureView`. This method should be * called after the camera preview size is determined in setUpCameraOutputs and also the size of * `mTextureView` is fixed. * * @param viewWidth The width of `mTextureView` * @param viewHeight The height of `mTextureView` */ private void configureTransform(final int viewWidth, final int viewHeight) { final Activity activity = getActivity(); if (null == textureView || null == previewSize || null == activity) { return; } final int rotation = activity.getWindowManager().getDefaultDisplay().getRotation(); final Matrix matrix = new Matrix(); final RectF viewRect = new RectF(0, 0, viewWidth, viewHeight); final RectF bufferRect = new RectF(0, 0, previewSize.getHeight(), previewSize.getWidth()); final float centerX = viewRect.centerX(); final float centerY = viewRect.centerY(); if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) { bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY()); matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL); final float scale = Math.max( (float) viewHeight / previewSize.getHeight(), (float) viewWidth / previewSize.getWidth()); matrix.postScale(scale, scale, centerX, centerY); matrix.postRotate(90 * (rotation - 2), centerX, centerY); } else if (Surface.ROTATION_180 == rotation) { matrix.postRotate(180, centerX, centerY); } textureView.setTransform(matrix); } /** * Callback for Activities to use to initialize their data once the selected preview size is * known. */ public interface ConnectionCallback { void onPreviewSizeChosen(Size size, int cameraRotation); } /** Compares two {@code Size}s based on their areas. */ static class CompareSizesByArea implements Comparator { @Override public int compare(final Size lhs, final Size rhs) { // We cast here to ensure the multiplications won't overflow return Long.signum( (long) lhs.getWidth() * lhs.getHeight() - (long) rhs.getWidth() * rhs.getHeight()); } } /** Shows an error message dialog. */ public static class ErrorDialog extends DialogFragment { private static final String ARG_MESSAGE = "message"; public static ErrorDialog newInstance(final String message) { final ErrorDialog dialog = new ErrorDialog(); final Bundle args = new Bundle(); args.putString(ARG_MESSAGE, message); dialog.setArguments(args); return dialog; } @Override public Dialog onCreateDialog(final Bundle savedInstanceState) { final Activity activity = getActivity(); return new AlertDialog.Builder(activity) .setMessage(getArguments().getString(ARG_MESSAGE)) .setPositiveButton( android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialogInterface, final int i) { activity.finish(); } }) .create(); } } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/detection/DetectorActivity.java ================================================ /* * Copyright 2019 The TensorFlow Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helloworld.goodpoint.detection; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.RectF; import android.graphics.Typeface; import android.media.ImageReader.OnImageAvailableListener; import android.os.Bundle; import android.os.SystemClock; import android.util.Size; import android.util.TypedValue; import android.widget.Toast; import androidx.camera.core.ImageAnalysis; import androidx.camera.core.ImageProxy; import com.example.lib_task_api.Detector; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.ml.vision.common.FirebaseVisionImage; import com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata; import com.google.mlkit.vision.common.InputImage; import com.google.mlkit.vision.face.Face; import com.google.mlkit.vision.face.FaceDetection; import com.google.mlkit.vision.face.FaceDetector; import com.google.mlkit.vision.face.FaceDetectorOptions; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.detection.customview.OverlayView; import com.helloworld.goodpoint.detection.customview.OverlayView.DrawCallback; import com.helloworld.goodpoint.detection.env.BorderedText; import com.helloworld.goodpoint.detection.env.ImageUtils; import com.helloworld.goodpoint.detection.env.Logger; import com.example.lib_task_api.TFLiteObjectDetectionAPIModel; import com.helloworld.goodpoint.detection.tracking.MultiBoxTracker; import com.helloworld.goodpoint.ui.GlobalVar; import java.io.IOException; import java.util.LinkedList; import java.util.List; /** * An activity that uses a TensorFlowMultiBoxDetector and ObjectTracker to detect and then track * objects. */ public class DetectorActivity extends CameraActivity implements OnImageAvailableListener { private static final Logger LOGGER = new Logger(); // Configuration values for the prepackaged SSD model. // AgeGenModel private static final int TF_OD_API_INPUT_SIZE = 80; private static final boolean TF_OD_API_IS_QUANTIZED = false; private static final String TF_OD_API_MODEL_FILE = "face_model_v5.tflite"; private static final String TF_OD_API_LABELS_FILE = "labelmap.txt"; private static final DetectorMode MODE = DetectorMode.TF_OD_API; // Minimum detection confidence to track a detection. private static final float MINIMUM_CONFIDENCE_TF_OD_API = 0.5f; private static final boolean MAINTAIN_ASPECT = false; private static final Size DESIRED_PREVIEW_SIZE = new Size(640, 480); private static final boolean SAVE_PREVIEW_BITMAP = false; private static final float TEXT_SIZE_DIP = 10; OverlayView trackingOverlay; private Integer sensorOrientation; private Detector detector; private long lastProcessingTimeMs; private Bitmap rgbFrameBitmap = null; private Bitmap portraitBmp = null; private Bitmap faceBmp = null; private Bitmap croppedBitmap = null; private Bitmap cropCopyBitmap = null; private boolean computingDetection = false; private long timestamp = 0; private Matrix frameToCropTransform; private Matrix cropToFrameTransform; private MultiBoxTracker tracker; private BorderedText borderedText; // Face detector FaceDetector faceDetector; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Real-time contour detection of multiple faces FaceDetectorOptions options = new FaceDetectorOptions.Builder() .setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_FAST) .setContourMode(FaceDetectorOptions.LANDMARK_MODE_NONE) .setClassificationMode(FaceDetectorOptions.CLASSIFICATION_MODE_NONE) .build(); FaceDetector detector = FaceDetection.getClient(options); faceDetector = detector; } @Override public void onPreviewSizeChosen(final Size size, final int rotation) { final float textSizePx = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, TEXT_SIZE_DIP, getResources().getDisplayMetrics()); borderedText = new BorderedText(textSizePx); borderedText.setTypeface(Typeface.MONOSPACE); tracker = new MultiBoxTracker(this); try { detector = TFLiteObjectDetectionAPIModel.create( this, TF_OD_API_MODEL_FILE, TF_OD_API_LABELS_FILE, TF_OD_API_INPUT_SIZE, TF_OD_API_IS_QUANTIZED); //cropSize = TF_OD_API_INPUT_SIZE; } catch (final IOException e) { e.printStackTrace(); LOGGER.e(e, "Exception initializing classifier!"); Toast toast = Toast.makeText( getApplicationContext(), "Classifier could not be initialized", Toast.LENGTH_SHORT); toast.show(); finish(); } previewWidth = size.getWidth(); previewHeight = size.getHeight(); sensorOrientation = rotation - getScreenOrientation(); LOGGER.i("Camera orientation relative to screen canvas: %d", sensorOrientation); LOGGER.i("Initializing at size %dx%d", previewWidth, previewHeight); rgbFrameBitmap = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888); int targetW, targetH; if (sensorOrientation == 90 || sensorOrientation == 270) { targetH = previewWidth; targetW = previewHeight; } else { targetW = previewWidth; targetH = previewHeight; } int cropW = (int) (targetW / 2.0); int cropH = (int) (targetH / 2.0); LOGGER.i("CropW, cropH"+cropW+" "+cropH); croppedBitmap = Bitmap.createBitmap(cropW, cropH, Config.ARGB_8888); GlobalVar.realcameraImage = croppedBitmap; portraitBmp = Bitmap.createBitmap(targetW, targetH, Config.ARGB_8888); faceBmp = Bitmap.createBitmap(TF_OD_API_INPUT_SIZE, TF_OD_API_INPUT_SIZE, Config.ARGB_8888); frameToCropTransform = ImageUtils.getTransformationMatrix( previewWidth, previewHeight, cropW, cropH, sensorOrientation, MAINTAIN_ASPECT); cropToFrameTransform = new Matrix(); frameToCropTransform.invert(cropToFrameTransform); Matrix frameToPortraitTransform = ImageUtils.getTransformationMatrix( previewWidth, previewHeight, targetW, targetH, sensorOrientation, MAINTAIN_ASPECT); trackingOverlay = (OverlayView) findViewById(R.id.tracking_overlay); trackingOverlay.addCallback( new DrawCallback() { @Override public void drawCallback(final Canvas canvas) { tracker.draw(canvas); if (isDebug()) { tracker.drawDebug(canvas); } } }); tracker.setFrameConfiguration(previewWidth, previewHeight, sensorOrientation); } @Override protected void processImage() { ++timestamp; final long currTimestamp = timestamp; trackingOverlay.postInvalidate(); // No mutex needed as this method is not reentrant. if (computingDetection) { readyForNextImage(); return; } computingDetection = true; LOGGER.i("Preparing image " + currTimestamp + " for detection in bg thread."); //CODE that gets the pixels from the camera rgbFrameBitmap.setPixels(getRgbBytes(), 0, previewWidth, 0, 0, previewWidth, previewHeight); readyForNextImage(); final Canvas canvas = new Canvas(croppedBitmap); canvas.drawBitmap(rgbFrameBitmap, frameToCropTransform, null); // For examining the actual TF input. if (SAVE_PREVIEW_BITMAP) { ImageUtils.saveBitmap(croppedBitmap); } InputImage image = InputImage.fromBitmap(croppedBitmap, 0); faceDetector .process(image) .addOnSuccessListener(new OnSuccessListener>() { @Override public void onSuccess(List faces) { if (faces.size() == 0) { updateResults(currTimestamp, new LinkedList<>()); return; } runInBackground( new Runnable() { @Override public void run() { onFacesDetected(currTimestamp, faces); } }); } }); } // Face Processing private Matrix createTransform( final int srcWidth, final int srcHeight, final int dstWidth, final int dstHeight, final int applyRotation) { Matrix matrix = new Matrix(); if (applyRotation != 0) { if (applyRotation % 90 != 0) { LOGGER.w("Rotation of %d % 90 != 0", applyRotation); } // Translate so center of image is at origin. matrix.postTranslate(-srcWidth / 2.0f, -srcHeight / 2.0f); // Rotate around origin. matrix.postRotate(applyRotation); } if (applyRotation != 0) { // Translate back from origin centered reference to destination frame. matrix.postTranslate(dstWidth / 2.0f, dstHeight / 2.0f); } return matrix; } private void onFacesDetected(long currTimestamp, List faces) { cropCopyBitmap = Bitmap.createBitmap(croppedBitmap); final Paint paint = new Paint(); paint.setColor(Color.RED); paint.setStyle(Style.STROKE); paint.setStrokeWidth(2.0f); final List mappedRecognitions = new LinkedList(); //final List results = new ArrayList<>(); // Note this can be done only once int sourceW = rgbFrameBitmap.getWidth(); int sourceH = rgbFrameBitmap.getHeight(); int targetW = portraitBmp.getWidth(); int targetH = portraitBmp.getHeight(); Matrix transform = createTransform( sourceW, sourceH, targetW, targetH, sensorOrientation); final Canvas cv = new Canvas(portraitBmp); // draws the original image in portrait mode. cv.drawBitmap(rgbFrameBitmap, transform, null); final Canvas cvFace = new Canvas(faceBmp); for (Face face : faces) { LOGGER.i("FACE" + face.toString()); LOGGER.i("Running detection on face " + currTimestamp); //results = detector.recognizeImage(croppedBitmap); final RectF boundingBox = new RectF(face.getBoundingBox()); //final boolean goodConfidence = result.getConfidence() >= minimumConfidence; final boolean goodConfidence = true; //face.get; if (boundingBox != null && goodConfidence) { // maps crop coordinates to original cropToFrameTransform.mapRect(boundingBox); // maps original coordinates to portrait coordinates RectF faceBB = new RectF(boundingBox); transform.mapRect(faceBB); // translates portrait to origin and scales to fit input inference size //cv.drawRect(faceBB, paint); float sx = ((float) TF_OD_API_INPUT_SIZE) / faceBB.width(); float sy = ((float) TF_OD_API_INPUT_SIZE) / faceBB.height(); Matrix matrix = new Matrix(); matrix.postTranslate(-faceBB.left, -faceBB.top); matrix.postScale(sx, sy); cvFace.drawBitmap(portraitBmp, matrix, null); float confidence = -1f; Bitmap crop = null; if ((int)faceBB.left > 0 && (int)faceBB.top > 0 && ((int)faceBB.left + (int)faceBB.width()) < portraitBmp.getWidth() && ((int)faceBB.top + (int)faceBB.height()) < portraitBmp.getHeight() ) { crop = Bitmap.createBitmap(portraitBmp, //prev portraitBmp (int) faceBB.left, (int) faceBB.top, (int) faceBB.width(), (int) faceBB.height()); //} crop = Bitmap.createScaledBitmap(crop, TF_OD_API_INPUT_SIZE, TF_OD_API_INPUT_SIZE, true); final long startTime = SystemClock.uptimeMillis(); // Passing the bitmap image into the TensorFlow Lite Object Detection API recognize image function final String resultLabel = detector.recognizeImage(crop); //prev faceBmp lastProcessingTimeMs = SystemClock.uptimeMillis() - startTime; final Detector.Recognition result = new Detector.Recognition( "0", resultLabel, confidence, boundingBox); result.setLocation(boundingBox); mappedRecognitions.add(result); } } } updateResults(currTimestamp, mappedRecognitions); } private void updateResults(long currTimestamp, final List mappedRecognitions) { tracker.trackResults(mappedRecognitions, currTimestamp); trackingOverlay.postInvalidate(); computingDetection = false; } @Override protected int getLayoutId() { return R.layout.tfe_od_camera_connection_fragment_tracking; } @Override protected Size getDesiredPreviewFrameSize() { return DESIRED_PREVIEW_SIZE; } // Which detection model to use: by default uses Tensorflow Object Detection API frozen // checkpoints. private enum DetectorMode { TF_OD_API; } @Override protected void setUseNNAPI(final boolean isChecked) { runInBackground( () -> { try { detector.setUseNNAPI(isChecked); } catch (UnsupportedOperationException e) { LOGGER.e(e, "Failed to set \"Use NNAPI\"."); runOnUiThread( () -> { Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show(); }); } }); } @Override protected void setNumThreads(final int numThreads) { runInBackground(() -> detector.setNumThreads(numThreads)); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/detection/LegacyCameraConnectionFragment.java ================================================ package com.helloworld.goodpoint.detection; /* * Copyright 2019 The TensorFlow Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.annotation.SuppressLint; import android.app.Fragment; import android.graphics.SurfaceTexture; import android.hardware.Camera; import android.hardware.Camera.CameraInfo; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.util.Size; import android.util.SparseIntArray; import android.view.LayoutInflater; import android.view.Surface; import android.view.TextureView; import android.view.View; import android.view.ViewGroup; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.detection.customview.AutoFitTextureView; import com.helloworld.goodpoint.detection.env.ImageUtils; import com.helloworld.goodpoint.detection.env.Logger; import java.io.IOException; import java.util.List; @SuppressLint("ValidFragment") public class LegacyCameraConnectionFragment extends Fragment { private static final Logger LOGGER = new Logger(); /** Conversion from screen rotation to JPEG orientation. */ private static final SparseIntArray ORIENTATIONS = new SparseIntArray(); static { ORIENTATIONS.append(Surface.ROTATION_0, 90); ORIENTATIONS.append(Surface.ROTATION_90, 0); ORIENTATIONS.append(Surface.ROTATION_180, 270); ORIENTATIONS.append(Surface.ROTATION_270, 180); } private Camera camera; private Camera.PreviewCallback imageListener; private Size desiredSize; /** The layout identifier to inflate for this Fragment. */ private int layout; /** An {@link AutoFitTextureView} for camera preview. */ private AutoFitTextureView textureView; private SurfaceTexture availableSurfaceTexture = null; /** * {@link TextureView.SurfaceTextureListener} handles several lifecycle events on a {@link * TextureView}. */ private final TextureView.SurfaceTextureListener surfaceTextureListener = new TextureView.SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable( final SurfaceTexture texture, final int width, final int height) { availableSurfaceTexture = texture; startCamera(); } @Override public void onSurfaceTextureSizeChanged( final SurfaceTexture texture, final int width, final int height) {} @Override public boolean onSurfaceTextureDestroyed(final SurfaceTexture texture) { return true; } @Override public void onSurfaceTextureUpdated(final SurfaceTexture texture) {} }; /** An additional thread for running tasks that shouldn't block the UI. */ private HandlerThread backgroundThread; public LegacyCameraConnectionFragment( final Camera.PreviewCallback imageListener, final int layout, final Size desiredSize) { this.imageListener = imageListener; this.layout = layout; this.desiredSize = desiredSize; } @Override public View onCreateView( final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { return inflater.inflate(layout, container, false); } @Override public void onViewCreated(final View view, final Bundle savedInstanceState) { textureView = (AutoFitTextureView) view.findViewById(R.id.texture); } @Override public void onActivityCreated(final Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onResume() { super.onResume(); startBackgroundThread(); // When the screen is turned off and turned back on, the SurfaceTexture is already // available, and "onSurfaceTextureAvailable" will not be called. In that case, we can open // a camera and start preview from here (otherwise, we wait until the surface is ready in // the SurfaceTextureListener). if (textureView.isAvailable()) { startCamera(); } else { textureView.setSurfaceTextureListener(surfaceTextureListener); } } @Override public void onPause() { stopCamera(); stopBackgroundThread(); super.onPause(); } /** Starts a background thread and its {@link Handler}. */ private void startBackgroundThread() { backgroundThread = new HandlerThread("CameraBackground"); backgroundThread.start(); } /** Stops the background thread and its {@link Handler}. */ private void stopBackgroundThread() { backgroundThread.quitSafely(); try { backgroundThread.join(); backgroundThread = null; } catch (final InterruptedException e) { LOGGER.e(e, "Exception!"); } } private void startCamera() { int index = getCameraId(); camera = Camera.open(index); try { Camera.Parameters parameters = camera.getParameters(); List focusModes = parameters.getSupportedFocusModes(); if (focusModes != null && focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) { parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); } List cameraSizes = parameters.getSupportedPreviewSizes(); Size[] sizes = new Size[cameraSizes.size()]; int i = 0; for (Camera.Size size : cameraSizes) { sizes[i++] = new Size(size.width, size.height); } Size previewSize = CameraConnectionFragment.chooseOptimalSize( sizes, desiredSize.getWidth(), desiredSize.getHeight()); parameters.setPreviewSize(previewSize.getWidth(), previewSize.getHeight()); camera.setDisplayOrientation(90); camera.setParameters(parameters); camera.setPreviewTexture(availableSurfaceTexture); } catch (IOException exception) { camera.release(); } camera.setPreviewCallbackWithBuffer(imageListener); Camera.Size s = camera.getParameters().getPreviewSize(); camera.addCallbackBuffer(new byte[ImageUtils.getYUVByteSize(s.height, s.width)]); textureView.setAspectRatio(s.height, s.width); camera.startPreview(); } protected void stopCamera() { if (camera != null) { camera.stopPreview(); camera.setPreviewCallback(null); camera.release(); camera = null; } } private int getCameraId() { CameraInfo ci = new CameraInfo(); for (int i = 0; i < Camera.getNumberOfCameras(); i++) { Camera.getCameraInfo(i, ci); if (ci.facing == CameraInfo.CAMERA_FACING_BACK) return i; } return -1; // No camera found } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/detection/customview/AutoFitTextureView.java ================================================ /* * Copyright 2019 The TensorFlow Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helloworld.goodpoint.detection.customview; import android.content.Context; import android.util.AttributeSet; import android.view.TextureView; /** A {@link TextureView} that can be adjusted to a specified aspect ratio. */ public class AutoFitTextureView extends TextureView { private int ratioWidth = 0; private int ratioHeight = 0; public AutoFitTextureView(final Context context) { this(context, null); } public AutoFitTextureView(final Context context, final AttributeSet attrs) { this(context, attrs, 0); } public AutoFitTextureView(final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); } /** * Sets the aspect ratio for this view. The size of the view will be measured based on the ratio * calculated from the parameters. Note that the actual sizes of parameters don't matter, that is, * calling setAspectRatio(2, 3) and setAspectRatio(4, 6) make the same result. * * @param width Relative horizontal size * @param height Relative vertical size */ public void setAspectRatio(final int width, final int height) { if (width < 0 || height < 0) { throw new IllegalArgumentException("Size cannot be negative."); } ratioWidth = width; ratioHeight = height; requestLayout(); } @Override protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); final int width = MeasureSpec.getSize(widthMeasureSpec); final int height = MeasureSpec.getSize(heightMeasureSpec); if (0 == ratioWidth || 0 == ratioHeight) { setMeasuredDimension(width, height); } else { if (width < height * ratioWidth / ratioHeight) { setMeasuredDimension(width, width * ratioHeight / ratioWidth); } else { setMeasuredDimension(height * ratioWidth / ratioHeight, height); } } } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/detection/customview/OverlayView.java ================================================ /* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ package com.helloworld.goodpoint.detection.customview; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.View; import java.util.LinkedList; import java.util.List; /** A simple View providing a render callback to other classes. */ public class OverlayView extends View { private final List callbacks = new LinkedList(); public OverlayView(final Context context, final AttributeSet attrs) { super(context, attrs); } public void addCallback(final DrawCallback callback) { callbacks.add(callback); } @Override public synchronized void draw(final Canvas canvas) { super.draw(canvas); for (final DrawCallback callback : callbacks) { callback.drawCallback(canvas); } } /** Interface defining the callback for client classes. */ public interface DrawCallback { public void drawCallback(final Canvas canvas); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/detection/customview/RecognitionScoreView.java ================================================ /* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ package com.helloworld.goodpoint.detection.customview; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import java.util.List; import com.example.lib_task_api.Detector.Recognition; public class RecognitionScoreView extends View implements ResultsView { private static final float TEXT_SIZE_DIP = 5; private final float textSizePx; private final Paint fgPaint; private final Paint bgPaint; private List results; public RecognitionScoreView(final Context context, final AttributeSet set) { super(context, set); textSizePx = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, TEXT_SIZE_DIP, getResources().getDisplayMetrics()); fgPaint = new Paint(); fgPaint.setTextSize(textSizePx); bgPaint = new Paint(); bgPaint.setColor(0xcc4285f4); } @Override public void setResults(final List results) { this.results = results; postInvalidate(); } @Override public void onDraw(final Canvas canvas) { final int x = 10; int y = (int) (fgPaint.getTextSize() * 1.5f); canvas.drawPaint(bgPaint); if (results != null) { for (final Recognition recog : results) { canvas.drawText(recog.getTitle() + ":" + recog.getConfidence(), x, y, fgPaint); y += (int) (fgPaint.getTextSize() * 1.5f); } } } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/detection/customview/ResultsView.java ================================================ /* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ package com.helloworld.goodpoint.detection.customview; import com.example.lib_task_api.Detector.Recognition; import java.util.List; public interface ResultsView { public void setResults(final List results); } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/detection/env/BorderedText.java ================================================ /* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ package com.helloworld.goodpoint.detection.env; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.Rect; import android.graphics.Typeface; import java.util.Vector; /** A class that encapsulates the tedious bits of rendering legible, bordered text onto a canvas. */ public class BorderedText { private final Paint interiorPaint; private final Paint exteriorPaint; private final float textSize; /** * Creates a left-aligned bordered text object with a white interior, and a black exterior with * the specified text size. * * @param textSize text size in pixels */ public BorderedText(final float textSize) { this(Color.WHITE, Color.BLACK, textSize); } /** * Create a bordered text object with the specified interior and exterior colors, text size and * alignment. * */ public BorderedText(final int interiorColor, final int exteriorColor, final float textSize) { interiorPaint = new Paint(); interiorPaint.setTextSize(textSize); interiorPaint.setColor(interiorColor); interiorPaint.setStyle(Style.FILL); interiorPaint.setAntiAlias(false); interiorPaint.setAlpha(255); exteriorPaint = new Paint(); exteriorPaint.setTextSize(textSize); exteriorPaint.setColor(exteriorColor); exteriorPaint.setStyle(Style.FILL_AND_STROKE); exteriorPaint.setStrokeWidth(textSize / 8); exteriorPaint.setAntiAlias(false); exteriorPaint.setAlpha(255); this.textSize = textSize; } public void setTypeface(Typeface typeface) { interiorPaint.setTypeface(typeface); exteriorPaint.setTypeface(typeface); } public void drawText(final Canvas canvas, final float posX, final float posY, final String text) { canvas.drawText(text, posX, posY, exteriorPaint); canvas.drawText(text, posX, posY, interiorPaint); } public void drawText( final Canvas canvas, final float posX, final float posY, final String text, Paint bgPaint) { float width = exteriorPaint.measureText(text); float textSize = exteriorPaint.getTextSize(); Paint paint = new Paint(bgPaint); paint.setStyle(Style.FILL); paint.setAlpha(160); canvas.drawRect(posX, (posY + (int) (textSize)), (posX + (int) (width)), posY, paint); canvas.drawText(text, posX, (posY + textSize), interiorPaint); } public float getTextSize() { return textSize; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/detection/env/ImageUtils.java ================================================ /* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ package com.helloworld.goodpoint.detection.env; import android.graphics.Bitmap; import android.graphics.Matrix; import android.os.Environment; import java.io.File; import java.io.FileOutputStream; /** Utility class for manipulating images. */ public class ImageUtils { // This value is 2 ^ 18 - 1, and is used to clamp the RGB values before their ranges // are normalized to eight bits. static final int kMaxChannelValue = 262143; @SuppressWarnings("unused") private static final Logger LOGGER = new Logger(); /** * Utility method to compute the allocated size in bytes of a YUV420SP image of the given * dimensions. */ public static int getYUVByteSize(final int width, final int height) { // The luminance plane requires 1 byte per pixel. final int ySize = width * height; // The UV plane works on 2x2 blocks, so dimensions with odd size must be rounded up. // Each 2x2 block takes 2 bytes to encode, one each for U and V. final int uvSize = ((width + 1) / 2) * ((height + 1) / 2) * 2; return ySize + uvSize; } /** * Saves a Bitmap object to disk for analysis. * * @param bitmap The bitmap to save. */ public static void saveBitmap(final Bitmap bitmap) { saveBitmap(bitmap, "preview.png"); } /** * Saves a Bitmap object to disk for analysis. * * @param bitmap The bitmap to save. * @param filename The location to save the bitmap to. */ public static void saveBitmap(final Bitmap bitmap, final String filename) { final String root = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "tensorflow"; LOGGER.i("Saving %dx%d bitmap to %s.", bitmap.getWidth(), bitmap.getHeight(), root); final File myDir = new File(root); if (!myDir.mkdirs()) { LOGGER.i("Make dir failed"); } final String fname = filename; final File file = new File(myDir, fname); if (file.exists()) { file.delete(); } try { final FileOutputStream out = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.PNG, 99, out); out.flush(); out.close(); } catch (final Exception e) { LOGGER.e(e, "Exception!"); } } public static void convertYUV420SPToARGB8888(byte[] input, int width, int height, int[] output) { final int frameSize = width * height; for (int j = 0, yp = 0; j < height; j++) { int uvp = frameSize + (j >> 1) * width; int u = 0; int v = 0; for (int i = 0; i < width; i++, yp++) { int y = 0xff & input[yp]; if ((i & 1) == 0) { v = 0xff & input[uvp++]; u = 0xff & input[uvp++]; } output[yp] = YUV2RGB(y, u, v); } } } private static int YUV2RGB(int y, int u, int v) { // Adjust and check YUV values y = (y - 16) < 0 ? 0 : (y - 16); u -= 128; v -= 128; // This is the floating point equivalent. We do the conversion in integer // because some Android devices do not have floating point in hardware. // nR = (int)(1.164 * nY + 2.018 * nU); // nG = (int)(1.164 * nY - 0.813 * nV - 0.391 * nU); // nB = (int)(1.164 * nY + 1.596 * nV); int y1192 = 1192 * y; int r = (y1192 + 1634 * v); int g = (y1192 - 833 * v - 400 * u); int b = (y1192 + 2066 * u); // Clipping RGB values to be inside boundaries [ 0 , kMaxChannelValue ] r = r > kMaxChannelValue ? kMaxChannelValue : (r < 0 ? 0 : r); g = g > kMaxChannelValue ? kMaxChannelValue : (g < 0 ? 0 : g); b = b > kMaxChannelValue ? kMaxChannelValue : (b < 0 ? 0 : b); return 0xff000000 | ((r << 6) & 0xff0000) | ((g >> 2) & 0xff00) | ((b >> 10) & 0xff); } public static void convertYUV420ToARGB8888( byte[] yData, byte[] uData, byte[] vData, int width, int height, int yRowStride, int uvRowStride, int uvPixelStride, int[] out) { int yp = 0; for (int j = 0; j < height; j++) { int pY = yRowStride * j; int pUV = uvRowStride * (j >> 1); for (int i = 0; i < width; i++) { int uv_offset = pUV + (i >> 1) * uvPixelStride; out[yp++] = YUV2RGB(0xff & yData[pY + i], 0xff & uData[uv_offset], 0xff & vData[uv_offset]); } } } /** * Returns a transformation matrix from one reference frame into another. Handles cropping (if * maintaining aspect ratio is desired) and rotation. * * @param srcWidth Width of source frame. * @param srcHeight Height of source frame. * @param dstWidth Width of destination frame. * @param dstHeight Height of destination frame. * @param applyRotation Amount of rotation to apply from one frame to another. Must be a multiple * of 90. * @param maintainAspectRatio If true, will ensure that scaling in x and y remains constant, * cropping the image if necessary. * @return The transformation fulfilling the desired requirements. */ public static Matrix getTransformationMatrix( final int srcWidth, final int srcHeight, final int dstWidth, final int dstHeight, final int applyRotation, final boolean maintainAspectRatio) { final Matrix matrix = new Matrix(); if (applyRotation != 0) { if (applyRotation % 90 != 0) { LOGGER.w("Rotation of %d % 90 != 0", applyRotation); } // Translate so center of image is at origin. matrix.postTranslate(-srcWidth / 2.0f, -srcHeight / 2.0f); // Rotate around origin. matrix.postRotate(applyRotation); } // Account for the already applied rotation, if any, and then determine how // much scaling is needed for each axis. final boolean transpose = (Math.abs(applyRotation) + 90) % 180 == 0; final int inWidth = transpose ? srcHeight : srcWidth; final int inHeight = transpose ? srcWidth : srcHeight; // Apply scaling if necessary. if (inWidth != dstWidth || inHeight != dstHeight) { final float scaleFactorX = dstWidth / (float) inWidth; final float scaleFactorY = dstHeight / (float) inHeight; if (maintainAspectRatio) { // Scale by minimum factor so that dst is filled completely while // maintaining the aspect ratio. Some image may fall off the edge. final float scaleFactor = Math.max(scaleFactorX, scaleFactorY); matrix.postScale(scaleFactor, scaleFactor); } else { // Scale exactly to fill dst from src. matrix.postScale(scaleFactorX, scaleFactorY); } } if (applyRotation != 0) { // Translate back from origin centered reference to destination frame. matrix.postTranslate(dstWidth / 2.0f, dstHeight / 2.0f); } return matrix; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/detection/env/Logger.java ================================================ /* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ package com.helloworld.goodpoint.detection.env; import android.util.Log; import java.util.HashSet; import java.util.Set; /** Wrapper for the platform log function, allows convenient message prefixing and log disabling. */ public final class Logger { private static final String DEFAULT_TAG = "tensorflow"; private static final int DEFAULT_MIN_LOG_LEVEL = Log.DEBUG; // Classes to be ignored when examining the stack trace private static final Set IGNORED_CLASS_NAMES; static { IGNORED_CLASS_NAMES = new HashSet(3); IGNORED_CLASS_NAMES.add("dalvik.system.VMStack"); IGNORED_CLASS_NAMES.add("java.lang.Thread"); IGNORED_CLASS_NAMES.add(Logger.class.getCanonicalName()); } private final String tag; private final String messagePrefix; private int minLogLevel = DEFAULT_MIN_LOG_LEVEL; /** * Creates a Logger using the class name as the message prefix. * * @param clazz the simple name of this class is used as the message prefix. */ public Logger(final Class clazz) { this(clazz.getSimpleName()); } /** * Creates a Logger using the specified message prefix. * * @param messagePrefix is prepended to the text of every message. */ public Logger(final String messagePrefix) { this(DEFAULT_TAG, messagePrefix); } /** * Creates a Logger with a custom tag and a custom message prefix. If the message prefix is set to * *
null
* * , the caller's class name is used as the prefix. * * @param tag identifies the source of a log message. * @param messagePrefix prepended to every message if non-null. If null, the name of the caller is * being used */ public Logger(final String tag, final String messagePrefix) { this.tag = tag; final String prefix = messagePrefix == null ? getCallerSimpleName() : messagePrefix; this.messagePrefix = (prefix.length() > 0) ? prefix + ": " : prefix; } /** Creates a Logger using the caller's class name as the message prefix. */ public Logger() { this(DEFAULT_TAG, null); } /** Creates a Logger using the caller's class name as the message prefix. */ public Logger(final int minLogLevel) { this(DEFAULT_TAG, null); this.minLogLevel = minLogLevel; } /** * Return caller's simple name. * *

Android getStackTrace() returns an array that looks like this: stackTrace[0]: * dalvik.system.VMStack stackTrace[1]: java.lang.Thread stackTrace[2]: * com.google.android.apps.unveil.env.UnveilLogger stackTrace[3]: * com.google.android.apps.unveil.BaseApplication * *

This function returns the simple version of the first non-filtered name. * * @return caller's simple name */ private static String getCallerSimpleName() { // Get the current callstack so we can pull the class of the caller off of it. final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); for (final StackTraceElement elem : stackTrace) { final String className = elem.getClassName(); if (!IGNORED_CLASS_NAMES.contains(className)) { // We're only interested in the simple name of the class, not the complete package. final String[] classParts = className.split("\\."); return classParts[classParts.length - 1]; } } return Logger.class.getSimpleName(); } public void setMinLogLevel(final int minLogLevel) { this.minLogLevel = minLogLevel; } public boolean isLoggable(final int logLevel) { return logLevel >= minLogLevel || Log.isLoggable(tag, logLevel); } private String toMessage(final String format, final Object... args) { return messagePrefix + (args.length > 0 ? String.format(format, args) : format); } public void v(final String format, final Object... args) { if (isLoggable(Log.VERBOSE)) { Log.v(tag, toMessage(format, args)); } } public void v(final Throwable t, final String format, final Object... args) { if (isLoggable(Log.VERBOSE)) { Log.v(tag, toMessage(format, args), t); } } public void d(final String format, final Object... args) { if (isLoggable(Log.DEBUG)) { Log.d(tag, toMessage(format, args)); } } public void d(final Throwable t, final String format, final Object... args) { if (isLoggable(Log.DEBUG)) { Log.d(tag, toMessage(format, args), t); } } public void i(final String format, final Object... args) { if (isLoggable(Log.INFO)) { Log.i(tag, toMessage(format, args)); } } public void i(final Throwable t, final String format, final Object... args) { if (isLoggable(Log.INFO)) { Log.i(tag, toMessage(format, args), t); } } public void w(final String format, final Object... args) { if (isLoggable(Log.WARN)) { Log.w(tag, toMessage(format, args)); } } public void w(final Throwable t, final String format, final Object... args) { if (isLoggable(Log.WARN)) { Log.w(tag, toMessage(format, args), t); } } public void e(final String format, final Object... args) { if (isLoggable(Log.ERROR)) { Log.e(tag, toMessage(format, args)); } } public void e(final Throwable t, final String format, final Object... args) { if (isLoggable(Log.ERROR)) { Log.e(tag, toMessage(format, args), t); } } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/detection/env/Size.java ================================================ /* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ package com.helloworld.goodpoint.detection.env; import android.graphics.Bitmap; import android.text.TextUtils; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** Size class independent of a Camera object. */ public class Size implements Comparable, Serializable { // 1.4 went out with this UID so we'll need to maintain it to preserve pending queries when // upgrading. public static final long serialVersionUID = 7689808733290872361L; public final int width; public final int height; public Size(final int width, final int height) { this.width = width; this.height = height; } public Size(final Bitmap bmp) { this.width = bmp.getWidth(); this.height = bmp.getHeight(); } /** * Rotate a size by the given number of degrees. * * @param size Size to rotate. * @param rotation Degrees {0, 90, 180, 270} to rotate the size. * @return Rotated size. */ public static Size getRotatedSize(final Size size, final int rotation) { if (rotation % 180 != 0) { // The phone is portrait, therefore the camera is sideways and frame should be rotated. return new Size(size.height, size.width); } return size; } public static Size parseFromString(String sizeString) { if (TextUtils.isEmpty(sizeString)) { return null; } sizeString = sizeString.trim(); // The expected format is "x". final String[] components = sizeString.split("x"); if (components.length == 2) { try { final int width = Integer.parseInt(components[0]); final int height = Integer.parseInt(components[1]); return new Size(width, height); } catch (final NumberFormatException e) { return null; } } else { return null; } } public static List sizeStringToList(final String sizes) { final List sizeList = new ArrayList(); if (sizes != null) { final String[] pairs = sizes.split(","); for (final String pair : pairs) { final Size size = Size.parseFromString(pair); if (size != null) { sizeList.add(size); } } } return sizeList; } public static String sizeListToString(final List sizes) { String sizesString = ""; if (sizes != null && sizes.size() > 0) { sizesString = sizes.get(0).toString(); for (int i = 1; i < sizes.size(); i++) { sizesString += "," + sizes.get(i).toString(); } } return sizesString; } public static final String dimensionsAsString(final int width, final int height) { return width + "x" + height; } public final float aspectRatio() { return (float) width / (float) height; } @Override public int compareTo(final Size other) { return width * height - other.width * other.height; } @Override public boolean equals(final Object other) { if (other == null) { return false; } if (!(other instanceof Size)) { return false; } final Size otherSize = (Size) other; return (width == otherSize.width && height == otherSize.height); } @Override public int hashCode() { return width * 32713 + height; } @Override public String toString() { return dimensionsAsString(width, height); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/detection/tracking/MultiBoxTracker.java ================================================ /* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ package com.helloworld.goodpoint.detection.tracking; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Paint.Cap; import android.graphics.Paint.Join; import android.graphics.Paint.Style; import android.graphics.RectF; import android.text.TextUtils; import android.util.Pair; import android.util.TypedValue; import com.example.lib_task_api.Detector.Recognition; import com.helloworld.goodpoint.detection.env.BorderedText; import com.helloworld.goodpoint.detection.env.ImageUtils; import com.helloworld.goodpoint.detection.env.Logger; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** A tracker that handles non-max suppression and matches existing objects to new detections. */ public class MultiBoxTracker { private static final float TEXT_SIZE_DIP = 10; private static final float MIN_SIZE = 16.0f; private static final int[] COLORS = { Color.BLUE, Color.RED, Color.GREEN, Color.YELLOW, Color.CYAN, Color.MAGENTA, Color.WHITE, Color.parseColor("#55FF55"), Color.parseColor("#FFA500"), Color.parseColor("#FF8888"), Color.parseColor("#AAAAFF"), Color.parseColor("#FFFFAA"), Color.parseColor("#55AAAA"), Color.parseColor("#AA33AA"), Color.parseColor("#0D0068") }; final List> screenRects = new LinkedList>(); private final Logger logger = new Logger(); private final Queue availableColors = new LinkedList(); private final List trackedObjects = new LinkedList(); private final Paint boxPaint = new Paint(); private final float textSizePx; private final BorderedText borderedText; private Matrix frameToCanvasMatrix; private int frameWidth; private int frameHeight; private int sensorOrientation; public MultiBoxTracker(final Context context) { for (final int color : COLORS) { availableColors.add(color); } boxPaint.setColor(Color.RED); boxPaint.setStyle(Style.STROKE); boxPaint.setStrokeWidth(10.0f); boxPaint.setStrokeCap(Cap.ROUND); boxPaint.setStrokeJoin(Join.ROUND); boxPaint.setStrokeMiter(100); textSizePx = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, TEXT_SIZE_DIP, context.getResources().getDisplayMetrics()); borderedText = new BorderedText(textSizePx); } public synchronized void setFrameConfiguration( final int width, final int height, final int sensorOrientation) { frameWidth = width; frameHeight = height; this.sensorOrientation = sensorOrientation; } public synchronized void drawDebug(final Canvas canvas) { final Paint textPaint = new Paint(); textPaint.setColor(Color.WHITE); textPaint.setTextSize(60.0f); final Paint boxPaint = new Paint(); boxPaint.setColor(Color.RED); boxPaint.setAlpha(200); boxPaint.setStyle(Style.STROKE); for (final Pair detection : screenRects) { final RectF rect = detection.second; canvas.drawRect(rect, boxPaint); canvas.drawText("" + detection.first, rect.left, rect.top, textPaint); borderedText.drawText(canvas, rect.centerX(), rect.centerY(), "" + detection.first); } } public synchronized void trackResults(final List results, final long timestamp) { logger.i("Processing %d results from %d", results.size(), timestamp); processResults(results); } private Matrix getFrameToCanvasMatrix() { return frameToCanvasMatrix; } public synchronized void draw(final Canvas canvas) { final boolean rotated = sensorOrientation % 180 == 90; final float multiplier = Math.min( canvas.getHeight() / (float) (rotated ? frameWidth : frameHeight), canvas.getWidth() / (float) (rotated ? frameHeight : frameWidth)); frameToCanvasMatrix = ImageUtils.getTransformationMatrix( frameWidth, frameHeight, (int) (multiplier * (rotated ? frameHeight : frameWidth)), (int) (multiplier * (rotated ? frameWidth : frameHeight)), sensorOrientation, false); for (final TrackedRecognition recognition : trackedObjects) { final RectF trackedPos = new RectF(recognition.location); getFrameToCanvasMatrix().mapRect(trackedPos); boxPaint.setColor(recognition.color); float cornerSize = Math.min(trackedPos.width(), trackedPos.height()) / 8.0f; canvas.drawRoundRect(trackedPos, cornerSize, cornerSize, boxPaint); // final String labelString = // !TextUtils.isEmpty(recognition.title) // ? String.format("%s %.2f", recognition.title, (100 * recognition.detectionConfidence)) // : String.format("%.2f", (100 * recognition.detectionConfidence)); final String labelString = !TextUtils.isEmpty(recognition.title) ? String.format("%s %s", recognition.title,"" ) : ""; // borderedText.drawText(canvas, trackedPos.left + cornerSize, trackedPos.top, // labelString); borderedText.drawText( canvas, trackedPos.left + cornerSize, trackedPos.top, labelString, boxPaint); } } private void processResults(final List results) { final List> rectsToTrack = new LinkedList>(); screenRects.clear(); final Matrix rgbFrameToScreen = new Matrix(getFrameToCanvasMatrix()); for (final Recognition result : results) { if (result.getLocation() == null) { continue; } final RectF detectionFrameRect = new RectF(result.getLocation()); final RectF detectionScreenRect = new RectF(); rgbFrameToScreen.mapRect(detectionScreenRect, detectionFrameRect); logger.v( "Result! Frame: " + result.getLocation() + " mapped to screen:" + detectionScreenRect); screenRects.add(new Pair(result.getConfidence(), detectionScreenRect)); if (detectionFrameRect.width() < MIN_SIZE || detectionFrameRect.height() < MIN_SIZE) { logger.w("Degenerate rectangle! " + detectionFrameRect); continue; } rectsToTrack.add(new Pair(result.getConfidence(), result)); } trackedObjects.clear(); if (rectsToTrack.isEmpty()) { logger.v("Nothing to track, aborting."); return; } for (final Pair potential : rectsToTrack) { final TrackedRecognition trackedRecognition = new TrackedRecognition(); trackedRecognition.detectionConfidence = potential.first; trackedRecognition.location = new RectF(potential.second.getLocation()); trackedRecognition.title = potential.second.getTitle(); trackedRecognition.color = COLORS[trackedObjects.size()]; trackedObjects.add(trackedRecognition); if (trackedObjects.size() >= COLORS.length) { break; } } } private static class TrackedRecognition { RectF location; float detectionConfidence; int color; String title; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/pojo/FoundItem.java ================================================ package com.helloworld.goodpoint.pojo; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class FoundItem { public FoundItem(String type, String serial_number, String brand, String color) { this.type = type; this.serial_number = serial_number; this.brand = brand; this.color = color; } @SerializedName("user_id") @Expose private String user_id; @SerializedName("id") @Expose private String id; @SerializedName("date") @Expose private String date; @SerializedName("city") @Expose private String city; @SerializedName("type") @Expose private String type; @SerializedName("serial_number") @Expose private String serial_number; @Expose @SerializedName("brand") private String brand; @SerializedName("color") @Expose private String color; @SerializedName("description") @Expose private String description; /* public FoundItem(int user_id, int id, String date, String city, String type, String serial_number, String brand, String color, String description) { this.id = id; this.user_id = user_id; this.date = date; this.city = city; this.type = type; this.serial_number = serial_number; this.brand = brand; this.color = color; this.description = description; }*/ private static FoundItem FoundItem; public static FoundItem getFoundItem() { if (FoundItem == null) { FoundItem = new FoundItem(); } return FoundItem; } private FoundItem() { } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public String getId() { return id; } public void setId(String id) { this.id = id; } public void setDate(String date) { this.date = date; } public String getDate() { return date; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getSerial_number() { return serial_number; } public void setSerial_number(String serial_number) { this.serial_number = serial_number; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/pojo/FoundPerson.java ================================================ package com.helloworld.goodpoint.pojo; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class FoundPerson { @SerializedName("id") @Expose private String id; @SerializedName("name") @Expose private String name; private double longitude; private double latitude; private String date; private String city; public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } private static FoundPerson FoundPerson; public static FoundPerson getFoundPerson() { if (FoundPerson == null) { FoundPerson = new FoundPerson(); } return FoundPerson; } private FoundPerson() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/pojo/LostItem.java ================================================ package com.helloworld.goodpoint.pojo; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class LostItem { public LostItem(String type, String serial_number, String brand, String color, String description) { this.type = type; this.serial_number = serial_number; this.brand = brand; this.color = color; this.description = description; } public LostItem(String type, String serial_number, String brand, String color) { this.type = type; this.serial_number = serial_number; this.brand = brand; this.color = color; } @SerializedName("user_id") @Expose private String user_id; @SerializedName("id") @Expose private String id; @SerializedName("date") @Expose private String date; @SerializedName("city") @Expose private String city; @SerializedName("type") @Expose private String type; @SerializedName("serial_number") @Expose private String serial_number; @Expose @SerializedName("brand") private String brand; @SerializedName("color") @Expose private String color; @SerializedName("description") @Expose private String description; /* public LostItem(int user_id, int id, String date, String city, String type, String serial_number, String brand, String color, String description) { this.id = id; this.user_id = user_id; this.date = date; this.city = city; this.type = type; this.serial_number = serial_number; this.brand = brand; this.color = color; this.description = description; }*/ private static LostItem lostItem; public static LostItem getLostItem() { if (lostItem == null) { lostItem = new LostItem(); } return lostItem; } private LostItem() { } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public String getId() { return id; } public void setId(String id) { this.id = id; } public void setDate(String date) { this.date = date; } public String getDate() { return date; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getSerial_number() { return serial_number; } public void setSerial_number(String serial_number) { this.serial_number = serial_number; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/pojo/LostObject.java ================================================ package com.helloworld.goodpoint.pojo; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class LostObject { @SerializedName("id") @Expose private int id; @SerializedName("user_id") @Expose private String user_id; public int getId() { return id; } public void setId(int id) { this.id = id; } @SerializedName("date") @Expose private String date; @SerializedName("city") @Expose private String city; public LostObject(String user_id, String date, String city) { this.user_id = user_id; this.date = date; this.city = city; } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/pojo/LostPerson.java ================================================ package com.helloworld.goodpoint.pojo; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class LostPerson { @SerializedName("id") @Expose private String id; @SerializedName("name") @Expose private String name; private String date; private String city; public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } private static LostPerson lostPerson; public static LostPerson getLostPerson() { if (lostPerson == null) { lostPerson = new LostPerson(); } return lostPerson; } private LostPerson() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/pojo/NotificationItem.java ================================================ package com.helloworld.goodpoint.pojo; import android.content.Intent; import android.graphics.Bitmap; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.Date; public class NotificationItem { @SerializedName("id") @Expose String id; @SerializedName("title") @Expose String title; @SerializedName("description") @Expose String description; @SerializedName("type") @Expose int type; @SerializedName("date_time") @Expose Date date; @SerializedName("is_sent") @Expose boolean sent; @SerializedName("is_read") @Expose boolean read; @SerializedName("user_id") @Expose int userId; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getType() { return type; } public void setType(int type) { this.type = type; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public boolean isRead() { return read; } public void setRead(boolean read) { this.read = read; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public boolean isSent() { return sent; } public void setSent(boolean sent) { this.sent = sent; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/pojo/ObjectLocation.java ================================================ package com.helloworld.goodpoint.pojo; import com.google.android.gms.maps.model.LatLng; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class ObjectLocation { @SerializedName("longitude") @Expose double longitude; @SerializedName("latitude") @Expose double latitude; @SerializedName("user_id") @Expose int userId; public ObjectLocation(double longitude, double latitude, int userId) { this.userId = userId; this.longitude = longitude; this.latitude = latitude; } public int getUserId() { return userId; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/pojo/RegUser.java ================================================ package com.helloworld.goodpoint.pojo; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class RegUser { @SerializedName("username") @Expose private String username; @SerializedName("password") @Expose private String password; @SerializedName("first_name") @Expose private String first_name; @SerializedName("phone") @Expose private String phone; @SerializedName("city") @Expose private String city; @SerializedName("birthdate") @Expose private String birthdate; @SerializedName("profile_pic") @Expose private String profile_pic; public RegUser(String username, String password, String first_name, String phone, String city, String birthdate, String profile_pic) { this.username = username; this.password = password; this.first_name = first_name; this.phone = phone; this.city = city; this.birthdate = birthdate; this.profile_pic = profile_pic; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getBirthdate() { return birthdate; } public void setBirthdate(String birthdate) { this.birthdate = birthdate; } /*public String getProfile_pic() { return profile_pic; } public void setProfile_pic(String profile_pic) { this.profile_pic = profile_pic; }*/ } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/pojo/Token.java ================================================ package com.helloworld.goodpoint.pojo; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Token { @SerializedName("refresh") @Expose private String refresh; @SerializedName("access") @Expose private String access; private static Token token; public static Token getToken(){ if(token == null){ token = new Token(); } return token; } public Token( String refresh, String access) { this.refresh = refresh; this.access = access; } public Token() { } public String getRefresh() { return refresh; } public void setRefresh(String refresh) { this.refresh = refresh; } public String getAccess() { return access; } public void setAccess(String access) { this.access = access; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/pojo/User.java ================================================ package com.helloworld.goodpoint.pojo; import android.graphics.Bitmap; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; public class User { @SerializedName("id") @Expose private String id; @SerializedName("username") @Expose private String username; @SerializedName("email") @Expose private String email; @SerializedName("phone") @Expose private String phone; @SerializedName("city") @Expose private String city; @SerializedName("birthdate") @Expose private String birthdate; @SerializedName("profile_pic") @Expose private String profile_pic; @SerializedName("id_card_pic") @Expose private String id_card_pic; @SerializedName("losts") @Expose Listlosts; @SerializedName("founds") @Expose Listfounds; private Bitmap profile_bitmap; List foundItem; private static User user; public static User getUser() { if (user == null) { user = new User(); user.losts = new ArrayList<>(); user.founds = new ArrayList<>(); user.foundItem = new ArrayList<>(); } return user; } public static void userLogout(){ user = null; } public List getLosts() { return losts; } public List getFounds() { return founds; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getBirthdate() { return birthdate; } public void setBirthdate(String birthdate) { this.birthdate = birthdate; } public String getProfile_pic() { return profile_pic; } public void setProfile_pic(String profile_pic) { this.profile_pic = profile_pic; } public Bitmap getProfile_bitmap() { return profile_bitmap; } public void setProfile_bitmap(Bitmap profile_bitmap) { this.profile_bitmap = profile_bitmap; } public String getId_card_pic() { return id_card_pic; } public void setId_card_pic(String id_card_pic) { this.id_card_pic = id_card_pic; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/pojo/UserMap.java ================================================ package com.helloworld.goodpoint.pojo; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class UserMap { @SerializedName("name") @Expose private String name; @SerializedName("email") @Expose private String email; @SerializedName("phone") @Expose private String phone; public UserMap(String name, String email, String phone) { this.name = name; this.email = email; this.phone = phone; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/retrofit/ApiClient.java ================================================ package com.helloworld.goodpoint.retrofit; import android.util.Log; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.converter.scalars.ScalarsConverterFactory; public class ApiClient { //base url private static String BASE_URL ; private static Retrofit retrofit = null; //Create Builder ... public static Retrofit getApiClient(String link) { BASE_URL = link; if (retrofit == null) { retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/retrofit/ApiInterface.java ================================================ package com.helloworld.goodpoint.retrofit; import com.google.gson.JsonObject; import com.helloworld.goodpoint.pojo.FoundItem; import com.helloworld.goodpoint.pojo.FoundPerson; import com.helloworld.goodpoint.pojo.LostItem; import com.helloworld.goodpoint.pojo.LostObject; import com.helloworld.goodpoint.pojo.LostPerson; import com.helloworld.goodpoint.pojo.NotificationItem; import com.helloworld.goodpoint.pojo.ObjectLocation; import com.helloworld.goodpoint.pojo.RegUser; import com.helloworld.goodpoint.pojo.Token; import com.helloworld.goodpoint.pojo.UserMap; import java.util.List; import okhttp3.MultipartBody; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Multipart; import retrofit2.http.PATCH; import retrofit2.http.POST; import retrofit2.http.Part; import retrofit2.http.Path; import retrofit2.http.Query; public interface ApiInterface { @FormUrlEncoded @POST("auth/signup/") Call storePost(@Field("username") String emailInput , @Field("password") String passwordInput, @Field("first_name") String usernameInput , @Field("phone") String pInput, @Field("city") String cityInput , @Field("birthdate") String Datee); @Multipart @POST("auth/signup/") Call storePost(@Part("username") String emailInput , @Part("password") String passwordInput, @Part("first_name") String usernameInput , @Part("phone") String pInput, @Part("city") String cityInput , @Part("birthdate") String Datee, @Part MultipartBody.Part profile_pic); @FormUrlEncoded @POST("api/token/") Call getToken(@Field("username") String emailInput, @Field("password") String passwordInput); @FormUrlEncoded @POST("api/token/refresh/") Call refresh(@Field("refresh") String refresh); @POST("auth/signin/") Call getData(@Header("Authorization") String token); @Multipart @PATCH("auth/setidcard/") Call setIdCard(@Header("Authorization") String token, @Part MultipartBody.Part image); //---------------------------------------------------------------------------------------------- @FormUrlEncoded @POST("losts/lostobject/") Call storeLostObj(@Field("user_id") String id, @Field("date") String Datee, @Field("city") String cityInput); @FormUrlEncoded @POST("losts/lostitem/") Call storeLostItem(@Field("id") String obj_id, @Field("type") String Type, @Field("serial_number") String Serial , @Field("brand") String brand, @Field("color") String ObjectColor , @Field("description") String textArea_information); @Multipart @POST("losts/lostitem/") Call storeLostItem(@Part("id") String obj_id, @Part("type") String Type, @Part("serial_number") String Serial , @Part("brand") String brand, @Part("color") String ObjectColor , @Part("description") String textArea_information, @Part MultipartBody.Part image); @Multipart @POST("losts/lostperson/") Call storeLostPerson(@Part("date") String Date, @Part("city") String city, @Part("user_id") String user_id , @Part("name") String name, @Part MultipartBody.Part images); //---------------------------------------------------------------------------------------------- @FormUrlEncoded @POST("losts/foundobject/") Call storeFoundObj(@Field("user_id") String id, @Field("date") String Datee, @Field("city") String cityInput , @Field("longitude") double longitude, @Field("latitude") double latitude); @FormUrlEncoded @POST("losts/founditem/") Call storeFoundItem(@Field("id") String obj_id, @Field("type") String Type, @Field("serial_number") String Serial , @Field("brand") String brand, @Field("color") String ObjectColor , @Field("description") String textArea_information); @Multipart @POST("losts/foundperson/") Call storeFoundPerson(@Part("user_id") String user_id, @Part("date") String Date, @Part("city") String city , @Part("longitude") double longitude, @Part("latitude") double latitude, @Part("name") String name, @Part MultipartBody.Part pimage); //---------------------------------------------------------------------------------------------- @GET("losts/map/") Call> getPoint(); @GET("losts/founder/{id}") Call getUserMap(@Path("id") int id); //--------------------------------------------------------------------------------------------- @GET("losts/lostobject/{id}") Call getObject(@Path("id") String id); @GET("losts/LostItemFilter/") Call> getLItem(@Query("type")String type); @GET("losts/LostItemFilter/") Call> getLostItem(@Query("id") int id); @GET("losts/lost_person/id={id}/") Call getLostPerson(@Path("id") int id); @GET("losts/found_person/id={id}/") Call getFoundPerson(@Path("id") int id); @GET("losts/FoundItemFilter/") Call> getFoundItem(@Query("id") int id); //------------------------------------------------------------------------------------ @FormUrlEncoded @POST("notification/") Call storeNotification(@Field("user_id") String id, @Field("title") String title , @Field("description") String description , @Field("type") int type); @GET("notification/user_id={id}/") Call> getNotification(@Path("id") String user_id); @FormUrlEncoded @PATCH("notification/read/{id}/") Call updateRead(@Path("id") String id, @Field("is_read") Boolean read); @FormUrlEncoded @PATCH("notification/sent/{id}/") Call updateSent(@Path("id") String id, @Field("is_sent") Boolean sent); @GET("notification/new/{user_id}/") Call> getNewNotification(@Path("user_id") String user_id); } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/retrofit/Decode.java ================================================ package com.helloworld.goodpoint.retrofit; import android.util.Base64; import android.util.Log; import java.io.UnsupportedEncodingException; public class Decode { private static String[] split; public static String decoded(String JWTEncoded) throws Exception { split = JWTEncoded.split("\\."); Log.d("JWT_DECODED", "Header: " + getJson(split[0])); Log.d("JWT_DECODED", "Body: " + getJson(split[1])); Log.d("JWT_DECODED", "Signiture: " + getJson(split[2])); return getJson(split[1]); } private static String getJson(String strEncoded) throws UnsupportedEncodingException { byte[] decodedBytes = Base64.decode(strEncoded, Base64.URL_SAFE); return new String(decodedBytes, "UTF-8"); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/ActionActivity.java ================================================ package com.helloworld.goodpoint.ui; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.ui.lostFoundObject.LostObjectDetailsActivity; public class ActionActivity extends AppCompatActivity { Button lost; Button found; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lost = (Button) findViewById(R.id.button_lost); found = (Button) findViewById(R.id.button_found); } public void lost_btn(View v){ startActivity(new Intent(ActionActivity.this, LostObjectDetailsActivity.class)); } public void found_btn(View v){ startActivity(new Intent(ActionActivity.this, LostObjectDetailsActivity.class)); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/AdapterOfMatchFragment.java ================================================ package com.helloworld.goodpoint.ui; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.helloworld.goodpoint.R; public class AdapterOfMatchFragment extends ArrayAdapter { private Context context; private String Rtitle[]; private String Rstatus[]; private int Rimg[]; //String ObjStat[] ={},ObjDetails; String status[]={"Has found" ,"Its owner has been found","Has found" ,"Its owner has been found", "Has found" ,"Its owner has been found","Has found" ,"Its owner has been found" } ; public AdapterOfMatchFragment(@NonNull Context context, String[] Rstatus) { super(context, R.layout.row,Rstatus); this.context = context; //this.Rtitle = Rtitle; this.Rstatus = Rstatus; // this.Rimg = Rimg; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { View r = convertView; viewHolder viewholder =null; if(r == null){ LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE); r = layoutInflater.inflate(R.layout.row,null,true); viewholder = new viewHolder(r); r.setTag(viewholder); } else{ viewholder = (viewHolder) r.getTag(); } viewholder.imageView.setImageResource(R.drawable.ic_baseline_gallery_24); viewholder.stat.setText(status[position]); viewholder.details.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { context.startActivity(new Intent(context, DetailsActivity.class)); } }); return r; } class viewHolder{ private ImageView imageView; private TextView stat, details; viewHolder(View v){ imageView = v.findViewById(R.id.obj); stat = v.findViewById(R.id.status); details = v.findViewById(R.id.details); } } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/Alert.java ================================================ package com.helloworld.goodpoint.ui; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.ui.select_multiple_faces.Selection; public class Alert extends AppCompatActivity { private Button next_btn; private TextView text; int i; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.alert); next_btn = (Button) findViewById(R.id.login_btn); text=(TextView)findViewById(R.id.text); i=GlobalVar.ImgThatHaveMoreThanOneFace.size(); text.setText("There are ("+ i+ ") images that have multiple faces so press next to select only face "); next_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Alert.this, Selection.class)); finish(); } }); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/DetailsActivity.java ================================================ package com.helloworld.goodpoint.ui; import android.Manifest; import android.content.ActivityNotFoundException; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.util.TypedValue; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import com.helloworld.goodpoint.R; public class DetailsActivity extends AppCompatActivity implements View.OnClickListener { private static final int CALL_CODE = 1; TextView main,sub,name,brand,color,addr,dlost,dfound,mname,mail,phone; LinearLayout subLayout,nameLayout,brandLayout,colorLayout,addrLayout,matchLayout; ImageView img; Button call,sendMail; private int id; private int type; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details); marginOrientation(); init(); // updateTable(); sendMail.setOnClickListener(this); subLayout.setVisibility(View.GONE); colorLayout.setVisibility(View.GONE); brandLayout.setVisibility(View.GONE); call.setOnClickListener(this); } private void updateTable() { switch (type){ case 1: subLayout.setVisibility(View.GONE); brandLayout.setVisibility(View.GONE); colorLayout.setVisibility(View.GONE); break; case 2: break; case 3: break; case 4: break; default: } } private void init() { main = findViewById(R.id.main_cat); sub = findViewById(R.id.item_cat); name = findViewById(R.id.lost_name); brand = findViewById(R.id.brand_name); color = findViewById(R.id.color_item); addr = findViewById(R.id.address); dlost = findViewById(R.id.date_of_lost); dfound = findViewById(R.id.date_of_found); mname = findViewById(R.id.name_of_matching); mail = findViewById(R.id.mail_of_matching); phone = findViewById(R.id.phone_of_matching); subLayout = findViewById(R.id.sub_cat); nameLayout = findViewById(R.id.person_name); brandLayout = findViewById(R.id.brand_detail); colorLayout = findViewById(R.id.color_detail); addrLayout = findViewById(R.id.addr_loc); matchLayout = findViewById(R.id.matched_detail); img = findViewById(R.id.img_detail); call = findViewById(R.id.call_btn); sendMail = findViewById(R.id.mail_btn); // id = getIntent().getIntExtra("id",0); // type = getIntent().getIntExtra("type",0); } private void marginOrientation() { int orientation = getResources().getConfiguration().orientation; if(orientation == Configuration.ORIENTATION_LANDSCAPE){ LinearLayout layout = findViewById(R.id.parent_table_details); LinearLayout.MarginLayoutParams layoutParams = (LinearLayout.MarginLayoutParams) layout.getLayoutParams(); float ver = getResources().getDimension(R.dimen._5sdp); float hor = getResources().getDimension(R.dimen._15sdp); int marginVer = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,ver,getResources().getDisplayMetrics()); int marginHor = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,hor,getResources().getDisplayMetrics()); layoutParams.setMargins(marginHor,marginVer,marginHor,marginVer); layout.requestLayout(); } } @Override public void onClick(View view) { switch(view.getId()){ case R.id.call_btn: callHim(); break; case R.id.mail_btn: sendEmail(); break; } } private void callHim() { Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse("tel:"+phone.getText().toString())); if(ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)!= PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CALL_PHONE},CALL_CODE); return; } startActivity(callIntent); } private void sendEmail() { Intent emailIntent = new Intent(Intent.ACTION_SENDTO); emailIntent.setData(Uri.parse("mailto:?subject=Matching item&to="+mail.getText().toString())); try { startActivity(Intent.createChooser(emailIntent,"Send mail...")); }catch (ActivityNotFoundException e){ Log.e("MY_TAG",e.getMessage()); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode){ case CALL_CODE: if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) callHim(); else Toast.makeText(this, "You should allow to access call", Toast.LENGTH_SHORT).show(); break; } } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/ExternalActivity.java ================================================ package com.helloworld.goodpoint.ui; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.helloworld.goodpoint.R; public class ExternalActivity extends AppCompatActivity { EditText et; Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_external); et = findViewById(R.id.ngrok_link); btn = findViewById(R.id.submit_btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { PrefManager p = new PrefManager(ExternalActivity.this); p.setNGROKLink("https://"+et.getText().toString()+".ngrok.io"); } }); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/FoundMapFragment.java ================================================ package com.helloworld.goodpoint.ui; import android.Manifest; import android.annotation.SuppressLint; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.os.Bundle; import android.os.Looper; import android.provider.Settings; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.core.app.ActivityCompat; import androidx.fragment.app.Fragment; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationCallback; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationResult; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.pojo.ObjectLocation; import com.helloworld.goodpoint.pojo.RegUser; import com.helloworld.goodpoint.pojo.User; import com.helloworld.goodpoint.pojo.UserMap; import com.helloworld.goodpoint.retrofit.ApiClient; import com.helloworld.goodpoint.retrofit.ApiInterface; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import static android.graphics.Color.BLUE; public class FoundMapFragment extends Fragment implements GoogleMap.OnMarkerClickListener, View.OnClickListener { private static final int MAP_CODE = 1; private static final int CALL_CODE = 2; private static final int CHECK_LOCATION_ENABLED_CODE = 3; SupportMapFragment mapFragment; FusedLocationProviderClient client; Location curLocation; String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}; List list; Mapmarker_id; AlertDialog.Builder dialog; TextView name,email,phone; Button call,mail; String emailAddress; private OnMapReadyCallback callback = new OnMapReadyCallback() { @SuppressLint("MissingPermission") @Override public void onMapReady(GoogleMap googleMap) { LatLng curLatLng = new LatLng(curLocation.getLatitude(), curLocation.getLongitude()); googleMap.setMyLocationEnabled(true); googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(curLatLng, 15)); //list = getLocations(); for(ObjectLocation object: list) { Marker marker = googleMap.addMarker(new MarkerOptions().position(new LatLng(object.getLatitude(), object.getLongitude()))); marker.setIcon(BitmapDescriptorFactory.defaultMarker(30)); marker_id.put(marker,object.getUserId()); } googleMap.setOnMarkerClickListener(FoundMapFragment.this); } }; /* private List getLocations() { Listret = new ArrayList<>(); Random random = new Random(); for(int i=0;i<100;i++) ret.add(new ObjectLocation(25+random.nextDouble()*10,22+random.nextDouble()*10,i)); return ret; } */ @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_map, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); getPoints(); } public boolean locationEnable() { final LocationManager manager = (LocationManager) getContext().getSystemService(getContext().LOCATION_SERVICE); return manager.isProviderEnabled(LocationManager.GPS_PROVIDER) || manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } private void buildAlertMessageNoGps() { final AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setMessage("Your GPS seems to be disabled, do you want to enable it?") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, final int id) { startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),CHECK_LOCATION_ENABLED_CODE); //startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, final int id) { dialog.cancel(); } }); final AlertDialog alert = builder.create(); alert.show(); } private void runGoogleMap() { if (ActivityCompat.checkSelfPermission(getContext(), permissions[0]) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), permissions[1]) != PackageManager.PERMISSION_GRANTED) { requestPermissions(permissions, MAP_CODE); }else if(!locationEnable()){ buildAlertMessageNoGps(); }else { init(); client.getLastLocation()/*.addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(@NonNull Location location) { curLocation = location; if (mapFragment != null) { mapFragment.getMapAsync(callback); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } })*/.addOnCompleteListener(new OnCompleteListener() { @SuppressLint("MissingPermission") @Override public void onComplete(@NonNull Task task) { Location location = task.getResult(); if(location != null) { curLocation = location; if (mapFragment != null) { mapFragment.getMapAsync(callback); } }else{ LocationRequest locationRequest = new LocationRequest() .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) .setInterval(10000) .setFastestInterval(1000) .setNumUpdates(1); LocationCallback locationCallback = new LocationCallback(){ @Override public void onLocationResult(LocationResult locationResult) { Location location = locationResult.getLastLocation(); curLocation = location; if (mapFragment != null) { mapFragment.getMapAsync(callback); } } }; client.requestLocationUpdates(locationRequest,locationCallback, Looper.myLooper()); } } }); } } private void init() { mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map); client = LocationServices.getFusedLocationProviderClient(getContext()); marker_id = new HashMap<>(); dialog = new AlertDialog.Builder(getContext()); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch(requestCode){ case MAP_CODE: if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ runGoogleMap(); }else { Toast.makeText(getContext(), "You should allow to access location", Toast.LENGTH_SHORT).show(); } break; case CALL_CODE: if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ callHim(); }else { Toast.makeText(getContext(), "You should allow to access call", Toast.LENGTH_SHORT).show(); } break; } } @Override public boolean onMarkerClick(Marker marker) { int id = marker_id.get(marker); getUserMap(id); Log.e("MYTAG",id+""); return false; } @Override public void onClick(View view) { switch (view.getId()){ case R.id.call_button: callHim(); break; case R.id.mail_button: sendEmail(); break; } } private void callHim() { Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse("tel:"+phone.getText().toString())); if(ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.CALL_PHONE)!= PackageManager.PERMISSION_GRANTED){ requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, CALL_CODE); return; } startActivity(callIntent); } private void sendEmail() { Intent emailIntent = new Intent(Intent.ACTION_SENDTO); emailIntent.setData(Uri.parse("mailto:?subject=Lost object&to="+emailAddress)); try { startActivity(Intent.createChooser(emailIntent,"Send mail...")); }catch (ActivityNotFoundException e){ Log.e("MY_TAG",e.getMessage()); } } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case CHECK_LOCATION_ENABLED_CODE: runGoogleMap(); break; } } public void getPoints() { ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getContext()).getNGROKLink()).create(ApiInterface.class); Call> call = apiInterface.getPoint(); call.enqueue(new Callback>() { @Override public void onResponse(Call> call, Response> response) { list = response.body(); runGoogleMap(); // Toast.makeText(getContext(), ""+response.body().get(0).getLatitude(), Toast.LENGTH_SHORT).show(); } @Override public void onFailure(Call> call, Throwable t) { } }); } public void getUserMap(int id) { ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getContext()).getNGROKLink()).create(ApiInterface.class); Call call2 = apiInterface.getUserMap(id); call2.enqueue(new Callback() { @Override public void onResponse(Call call2, Response response) { LayoutInflater inflater = LayoutInflater.from(getContext()); View v = inflater.inflate(R.layout.custom_map_dialog,null); name = v.findViewById(R.id.name_of_founder); name.setText(response.body().getName()); email = v.findViewById(R.id.mail_of_founder); email.setText(response.body().getEmail()); emailAddress = email.getText().toString(); phone = v.findViewById(R.id.phone_of_founder); phone.setText(response.body().getPhone()); call = v.findViewById(R.id.call_button); call.setOnClickListener(FoundMapFragment.this); mail = v.findViewById(R.id.mail_button); mail.setOnClickListener(FoundMapFragment.this); dialog.setView(v); dialog.setCancelable(true); dialog.create().show(); // Toast.makeText(getContext(), response.body().getName(), Toast.LENGTH_SHORT).show(); } @Override public void onFailure(Call call, Throwable t) { } }); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/GlobalVar.java ================================================ package com.helloworld.goodpoint.ui; import android.graphics.Bitmap; import com.helloworld.goodpoint.pojo.LostItem; import com.helloworld.goodpoint.ui.candidate.SubItem; import com.helloworld.goodpoint.ui.select_multiple_faces.SubItemList; import java.util.ArrayList; import java.util.List; public class GlobalVar { public static List> allFaces = new ArrayList<>(); public static Bitmap realcameraImage ; public static Bitmap realcameraIdCard ; public static List ImgThatHaveMoreThanOneFace = new ArrayList<>(); public static List FinialFacesThatWillGoToDataBase = new ArrayList<>(); public static int flag; public static List slist; public static List sublist; public static int position; public static int p; public static List losts; public static List founds; public static List lostList; public static List percentList; public static String type; } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/HomeActivity.java ================================================ package com.helloworld.goodpoint.ui; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.PorterDuff; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.fragment.app.Fragment; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.bottomsheet.BottomSheetDialog; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.navigation.NavigationView; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.pojo.FoundItem; import com.helloworld.goodpoint.pojo.FoundPerson; import com.helloworld.goodpoint.pojo.LostItem; import com.helloworld.goodpoint.pojo.LostObject; import com.helloworld.goodpoint.pojo.LostPerson; import com.helloworld.goodpoint.pojo.User; import com.helloworld.goodpoint.retrofit.ApiClient; import com.helloworld.goodpoint.retrofit.ApiInterface; import com.helloworld.goodpoint.ui.lostFoundObject.FoundObjectActivity; import com.helloworld.goodpoint.ui.lostFoundObject.LostObjectDetailsActivity; import java.util.ArrayList; import java.util.List; import de.hdodenhof.circleimageview.CircleImageView; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { DrawerLayout drawerLayout; NavigationView navigationView; Toolbar toolbar; AlertDialog.Builder dialog; BottomNavigationView bottomNavigationView; FloatingActionButton fab; TextView namenavigator; TextView mailnavigator; CircleImageView imgnavigator; Fragment selectedFragment; List listObj; List list1; FoundPerson list3; LostPerson list2; List list; boolean isGetLostItems=false, isGetFoundItems=false, isGetLostPersons=false, isGetFoundPersons=false; SwipeRefreshLayout refreshLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getHomeLosts(); getHomeFounds(); setContentView(R.layout.activity_home); /*refreshLayout = findViewById(R.id.swipe); refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { selectedFragment = new HomeFragment(); getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit(); refreshLayout.setRefreshing(false); } });*/ init(); setToolBarAndDrawer(); setBottomNavigator(); /*if (savedInstanceState == null) { //To make first fragment is home when opening the app getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fhome).commit(); }*/ selectedFragment = new HomeFragment(); getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit(); } private void setBottomNavigator() { bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView); fab = (FloatingActionButton) findViewById(R.id.fab); //To Disable item under Fab Menu menuNav = bottomNavigationView.getMenu(); MenuItem nav_item2 = menuNav.findItem(R.id.placeholder); nav_item2.setEnabled(false); bottomNavigationView.setBackgroundColor(0); //To hide the color of nav view bottomNavigationView.setOnNavigationItemSelectedListener(navListner); } private void setToolBarAndDrawer() { setSupportActionBar(toolbar); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.nav_drawer_open, R.string.nav_drawer_close); toggle.getDrawerArrowDrawable().setColor(getResources().getColor(android.R.color.white)); drawerLayout.addDrawerListener(toggle); toggle.syncState(); navigationView.setNavigationItemSelectedListener(this); } private void init() { drawerLayout = findViewById(R.id.drawer_layout); toolbar = findViewById(R.id.toolbar); navigationView = findViewById(R.id.nv); navigationView.bringToFront(); View view = navigationView.getHeaderView(0); namenavigator = (TextView) view.findViewById(R.id.namenav); mailnavigator = (TextView) view.findViewById(R.id.mailnav); imgnavigator = view.findViewById(R.id.circuler_profile_img); namenavigator.setText(User.getUser().getUsername()); mailnavigator.setText(User.getUser().getEmail()); if (User.getUser().getProfile_bitmap() != null) imgnavigator.setImageBitmap(User.getUser().getProfile_bitmap()); } @Override protected void onRestart() { super.onRestart(); getHomeLosts(); getHomeFounds(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.home_menu, menu); menu.getItem(0).getIcon().mutate().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == R.id.notification){ Intent intent = new Intent(this, NotificationActivity.class); intent.putExtra("ID",User.getUser().getId()); startActivity(intent); } return super.onOptionsItemSelected(item); } @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.drawer_share: break; case R.id.drawer_rate: break; case R.id.drawer_feedback: break; case R.id.drawer_about_us: break; case R.id.drawer_setting: break; case R.id.drawer_logout: dialog = createDialog("Logout", R.drawable.ic_baseline_exit_to_app_24); dialog.create().show(); break; default: return false; } drawerLayout.closeDrawer(GravityCompat.START); return false; } private AlertDialog.Builder createDialog(String title, int icon) { return new AlertDialog.Builder(this) .setTitle(title) .setMessage("Are you sure?") .setIcon(icon) .setNegativeButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { PrefManager prefManager = new PrefManager(getApplicationContext()); prefManager.setLogout(); User.userLogout(); startActivity(new Intent(HomeActivity.this, SigninActivity.class)); finish(); } }).setPositiveButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).setCancelable(false); } @Override public void onBackPressed() { if (drawerLayout.isDrawerOpen(GravityCompat.START)) drawerLayout.closeDrawer(GravityCompat.START); else super.onBackPressed(); } public void showPopup(View v) { //Fab Action final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(HomeActivity.this, R.style.BottomSheetTheme); View bottomSheetView = LayoutInflater.from(getApplicationContext()) .inflate(R.layout.bottom_sheet_dialog, (LinearLayout) findViewById(R.id.bottom_sheet)); bottomSheetView.findViewById(R.id.hide_sheet).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bottomSheetDialog.dismiss(); } }); bottomSheetView.findViewById(R.id.ilost).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(HomeActivity.this, LostObjectDetailsActivity.class)); bottomSheetDialog.dismiss(); } }); bottomSheetView.findViewById(R.id.ifound).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(HomeActivity.this, FoundObjectActivity.class)); bottomSheetDialog.dismiss(); } }); bottomSheetDialog.setContentView(bottomSheetView); bottomSheetDialog.show(); } private BottomNavigationView.OnNavigationItemSelectedListener navListner = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { selectedFragment = getSupportFragmentManager().getFragments().get(0); switch (item.getItemId()) { case R.id.miHome: selectedFragment = new HomeFragment(); break; case R.id.miMatch: selectedFragment = new MatchFragment(); break; case R.id.miProfile: selectedFragment = new ProfileFragment(); break; case R.id.miLocation: selectedFragment = new FoundMapFragment(); break; } getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit(); return true; } }; public void getHomeLosts() { List losts = new ArrayList<>(); losts = User.getUser().getLosts(); ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class); GlobalVar.losts = new ArrayList(); if (losts != null) { for (int i = 0; i < losts.size(); i++) { Call> call2 = apiInterface.getLostItem(losts.get(i)); call2.enqueue(new Callback>() { @Override public void onResponse(Call> call, Response> response) { list1 = response.body(); if (response.body()!=null&&list1.size()!=0) { String t = list1.get(0).getType() + " " + list1.get(0).getBrand() + ""; GlobalVar.losts.add(t); } isGetLostItems=true; dataIsReady(); } @Override public void onFailure(Call> call, Throwable t) { Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show(); isGetLostItems=true; dataIsReady(); } }); Call call3 = apiInterface.getLostPerson(losts.get(i)); call3.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { list2 = response.body(); Log.e("TAG", "onResponse: "+response.body()); if (response.body()!=null) { String t = list2.getName() + " is Missing"; GlobalVar.losts.add(t); } isGetLostPersons=true; dataIsReady(); } @Override public void onFailure(Call call, Throwable t) { Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show(); isGetLostPersons=true; dataIsReady(); } }); } } else Log.e("lost", "There is no objects of Losses."); //Toast.makeText(getApplicationContext(), "There is no objects of Losses", Toast.LENGTH_LONG).show(); } private void dataIsReady() { if(isGetFoundItems && isGetFoundPersons && isGetLostItems && isGetLostPersons) getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit(); } public void getHomeFounds() { List founds = new ArrayList<>(); founds = User.getUser().getFounds(); GlobalVar.founds = new ArrayList(); if (!founds.isEmpty()) { for (int i = 0; i < founds.size(); i++) { ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class); Call> call2 = apiInterface.getFoundItem(founds.get(i)); call2.enqueue(new Callback>() { @Override public void onResponse(Call> call, Response> response) { list = response.body(); if (response.body()!=null&& list.size() !=0) { String t = list.get(0).getType() + " " + list.get(0).getBrand() + ""; GlobalVar.founds.add(t); } isGetFoundItems=true; dataIsReady(); } @Override public void onFailure(Call> call, Throwable t) { Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show(); isGetFoundItems=true; dataIsReady(); } }); Call call3 = apiInterface.getFoundPerson(founds.get(i)); call3.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { list3 = response.body(); Log.e("TAG", "onResponse: "+response.body()); if (response.body() != null) { String t = list3.getName() + " is Founds"; GlobalVar.founds.add(t); } isGetFoundPersons=true; dataIsReady(); } @Override public void onFailure(Call call, Throwable t) { Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show(); isGetFoundPersons=true; dataIsReady(); } }); } } else Log.e("found", "There is no objects of Founds."); //Toast.makeText(getApplicationContext(), "There is no objects of Founds.", Toast.LENGTH_LONG).show(); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/HomeFragment.java ================================================ package com.helloworld.goodpoint.ui; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.TextView; import androidx.fragment.app.Fragment; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.adapter.MyExpandableListAdapter; import com.helloworld.goodpoint.pojo.LostItem; import com.helloworld.goodpoint.pojo.LostObject; import com.helloworld.goodpoint.pojo.User; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; public class HomeFragment extends Fragment { List groupList; List childList; Map> objects; //To link group list with child list ExpandableListView expandableListView; ExpandableListAdapter expandableListAdapter; TextView Daily_msg; TextView Hi_msg; List listObj; LostItem list1; String LossesObjects[]; // String FindingsItems[]; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_home, container, false); Daily_msg = v.findViewById(R.id.daily_message); Calendar c = Calendar.getInstance(); int timeOfDay = c.get(Calendar.HOUR_OF_DAY); if (timeOfDay >= 0 && timeOfDay < 12) { Daily_msg.setText("Good Morning"); } else if (timeOfDay >= 12 && timeOfDay < 16) { Daily_msg.setText("Good Afternoon"); } else if (timeOfDay >= 16 && timeOfDay < 21) { Daily_msg.setText("Good Evening"); } else if (timeOfDay >= 21 && timeOfDay < 24) { Daily_msg.setText("Good Night"); } Hi_msg = v.findViewById(R.id.hi_message); Hi_msg.setText("Hi, " + User.getUser().getUsername()); // Inflate the layout for this fragment createGroupList(); createObjects(GlobalVar.losts,GlobalVar.founds); expandableListView = v.findViewById(R.id.expanded_menu); expandableListAdapter = new MyExpandableListAdapter(getActivity(), groupList, objects); //getActivity expandableListView.setAdapter(expandableListAdapter); expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int i, int i1, long l) { String selected = expandableListAdapter.getChild(i, i1).toString(); return true; } }); return v; } private void createObjects(List itemsL,List itemsF) { objects = new HashMap>(); for (String group : groupList) { if (group.equals(getString(R.string.Losses))) { loadChild(itemsL); } else if (group.equals(getString(R.string.Founds))) loadChild(itemsF); objects.put(group, childList); } } private void loadChild(List AllObjects) { childList = new ArrayList<>(); if (AllObjects != null) { for (int i = 0; i < AllObjects.size(); i++) childList.add(AllObjects.get(i)); } else childList.add("b"); } private void createGroupList() { groupList = new ArrayList<>(); groupList.add(getString(R.string.Losses)); groupList.add(getString(R.string.Founds)); } /* public String[] getHomeFounds() { ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getContext()).getNGROKLink()).create(ApiInterface.class); Call> call = apiInterface.getHomeFounds_i(User.getUser().getId()); call.enqueue(new Callback>() { @Override public void onResponse(Call> call, Response> response) { try { JSONObject jsonObject = new JSONObject(response.body().toString()); String id = jsonObject.getString("id"); Call> call2 = apiInterface.getFItem(id); call2.enqueue(new Callback>() { @Override public void onResponse(Call> call, Response> response) { } @Override public void onFailure(Call> call, Throwable t) { Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_LONG).show(); } }); } catch (JSONException e) { Toast.makeText(getContext(), ""+e.getMessage(), Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call> call, Throwable t) { Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_LONG).show(); } }); Log.d("e", "message=" + FindingsItems); return FindingsItems; } */ } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/ID_cardDetection.java ================================================ package com.helloworld.goodpoint.ui; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.camera.core.CameraSelector; import androidx.camera.core.ImageAnalysis; import androidx.camera.core.ImageProxy; import androidx.camera.core.Preview; import androidx.camera.lifecycle.ProcessCameraProvider; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.lifecycle.LifecycleOwner; import android.Manifest; import android.annotation.SuppressLint; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.ImageFormat; import android.graphics.Rect; import android.graphics.YuvImage; import android.media.Image; import android.os.Bundle; import android.util.Log; import android.util.Size; import android.view.TextureView; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Toast; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.common.util.concurrent.ListenableFuture; import com.google.mlkit.common.MlKitException; import com.google.mlkit.common.model.LocalModel; import com.google.mlkit.vision.common.InputImage; import com.google.mlkit.vision.common.internal.ImageConvertUtils; import com.google.mlkit.vision.objects.DetectedObject; import com.google.mlkit.vision.objects.ObjectDetection; import com.google.mlkit.vision.objects.ObjectDetector; import com.google.mlkit.vision.objects.custom.CustomObjectDetectorOptions; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.utils.Draw; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.List; import java.util.concurrent.ExecutionException; public class ID_cardDetection extends AppCompatActivity { private ObjectDetector objectDetector; private ListenableFuture cameraProviderFuture; private androidx.camera.view.PreviewView previewView; private RelativeLayout relativeLayout; private ImageButton IDCard; private boolean flag = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_i_d_card_detection); if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) { ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.CAMERA},20); } previewView = findViewById(R.id.PV); relativeLayout = findViewById(R.id.ParentLayout); IDCard = findViewById(R.id.IDCard); cameraProviderFuture = ProcessCameraProvider.getInstance(this); cameraProviderFuture.addListener(() -> { try { ProcessCameraProvider cameraProvider = cameraProviderFuture.get(); bindPreview(cameraProvider); } catch (ExecutionException | InterruptedException e) { Log.e("ESRAA", "ExecutionException: "+e.getMessage()); } }, ContextCompat.getMainExecutor(this)); LocalModel localModel = new LocalModel.Builder() .setAssetFilePath("objectDetection.tflite").build(); CustomObjectDetectorOptions customObjectDetectorOptions = new CustomObjectDetectorOptions.Builder(localModel) .setDetectorMode(CustomObjectDetectorOptions.STREAM_MODE) .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(1) .build(); objectDetector = ObjectDetection.getClient(customObjectDetectorOptions); } private void bindPreview(@NonNull ProcessCameraProvider cameraProvider) { Log.e("ESRAA", "IamHERE"); Preview preview = new Preview.Builder().build(); TextureView mTextureView = new TextureView(this); CameraSelector cameraSelector = new CameraSelector.Builder() .requireLensFacing(CameraSelector.LENS_FACING_BACK) .build(); preview.setSurfaceProvider(previewView.getSurfaceProvider()); ImageAnalysis imageAnalysis = new ImageAnalysis.Builder() .setTargetResolution(new Size(480,480)) .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST).build(); imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(this), image -> { int rotationDegrees = image.getImageInfo().getRotationDegrees(); @SuppressLint("UnsafeOptInUsageError") Image im= image.getImage(); if(im != null) { InputImage processImage= InputImage.fromMediaImage(im,rotationDegrees); InputImage i = InputImage.fromMediaImage(im, image.getImageInfo().getRotationDegrees()); try { GlobalVar.realcameraIdCard = ImageConvertUtils.getInstance().getUpRightBitmap(i); } catch (MlKitException e) { e.printStackTrace(); } objectDetector.process(processImage) .addOnSuccessListener(detectedObjects -> { if(detectedObjects.size() == 0) { if (relativeLayout.getChildCount() > 1) relativeLayout.removeViewAt(1); String text ="There's no card found"; Draw D = new Draw(ID_cardDetection.this,text); D.init(2); relativeLayout.addView(D); IDCard.setImageResource(R.drawable.ic_baseline_photo_camera_24); flag = false; } else { for (DetectedObject detectedObject : detectedObjects) { String text; detectedObject.getLabels().contains("Driver's license"); for (DetectedObject.Label label : detectedObject.getLabels()) { if (relativeLayout.getChildCount() > 1) relativeLayout.removeViewAt(1); if (label.getText().equals("Driver's license")) { text = "There's card found"; Draw D = new Draw(ID_cardDetection.this, text); D.init(1); relativeLayout.addView(D); Log.e("ESRAA", "Object detected: " + text + "; "); IDCard.setImageResource(R.drawable.ic_realcam); flag = true; } else { text = "There's no card found"; Draw D = new Draw(ID_cardDetection.this, text); D.init(2); relativeLayout.addView(D); IDCard.setImageResource(R.drawable.ic_baseline_photo_camera_24); flag = false; } } } } image.close(); }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.e("ESRAA", "onFailure: "+e.getMessage()); image.close(); } }); } } ); cameraProvider.bindToLifecycle((LifecycleOwner)this, cameraSelector,imageAnalysis, preview); } public void check_there(View view) { if(flag) { Intent My = new Intent(); setResult(RESULT_OK,My); finish(); } else { Toast.makeText(this,"There's no card found",Toast.LENGTH_SHORT).show(); } } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/IdCard.java ================================================ package com.helloworld.goodpoint.ui; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import com.helloworld.goodpoint.R; public class IdCard extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.alert_id_card); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/MainActivity.java ================================================ package com.helloworld.goodpoint.ui; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.google.gson.JsonObject; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.pojo.Token; import com.helloworld.goodpoint.pojo.User; import com.helloworld.goodpoint.retrofit.ApiClient; import com.helloworld.goodpoint.retrofit.ApiInterface; import org.json.JSONArray; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MainActivity extends AppCompatActivity { PrefManager prefManager; ImageView splash; Thread t; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); if (prefManager.isFirstTimeLaunch()) { prefManager.setFirstTimeLaunch(true); startActivity(new Intent(MainActivity.this, WelcomeActivity.class)); finish(); }else if(!prefManager.isLoginned().isEmpty()) { rotateSplash(); t = startApp(); }else { startActivity(new Intent(this,SigninActivity.class)); finish(); } } @Override protected void onResume() { super.onResume(); t.start(); } @Override protected void onPause() { t.interrupt(); super.onPause(); } private void init() { prefManager = new PrefManager(getApplicationContext()); splash = findViewById(R.id.splash_icon); } private void rotateSplash() { Animation animation = AnimationUtils.loadAnimation(this,R.anim.rotate_splash); splash.startAnimation(animation); } private Thread startApp() { return new Thread(new Runnable() { @Override public void run() { //try { //Thread.sleep(3000); ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class); Call call = apiInterface.refresh(new PrefManager(getApplicationContext()).isLoginned()); Token.getToken().setRefresh(new PrefManager(getApplicationContext()).isLoginned()); call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { if(response.isSuccessful()) { String token = response.body().getAccess(); Call call2 = apiInterface.getData("Bearer " + token); call2.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { try { Log.d("e","res="+response.body().toString()); JSONObject jsonObject = new JSONObject(response.body().toString()).getJSONObject("user"); String id = jsonObject.getString("id"); String name = jsonObject.getString("username"); String email = jsonObject.getString("email"); String phone = jsonObject.getString("phone"); String city = jsonObject.getString("city"); String birthdate = jsonObject.getString("birthdate"); String Userimage = jsonObject.getString("profile_pic"); String idcardimage = jsonObject.getString("id_card_pic"); JSONArray jsonArray = jsonObject.getJSONArray("losts"); Log.e("blabla", jsonArray.length() + ""); for(int i=0;i call, Throwable t) { Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_LONG).show(); startActivity(new Intent(MainActivity.this, SigninActivity.class)); finish(); } }); }else{ startActivity(new Intent(MainActivity.this, SigninActivity.class)); finish(); } } @Override public void onFailure(Call call, Throwable t) { Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_LONG).show(); startActivity(new Intent(MainActivity.this, SigninActivity.class)); finish(); } }); //} catch (InterruptedException e) { // Log.e("InterruptedException: ", e.getMessage()); //} } }); } class DownloadProfilePic extends AsyncTask { private Bitmap download(String urlLink) throws IOException { Bitmap bitmap = null; URL url = null; HttpURLConnection httpConn; InputStream is = null; Log.e("ProfilePic", urlLink); try { url = new URL(urlLink); httpConn = (HttpURLConnection) url.openConnection(); httpConn.connect(); is = httpConn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); }catch (MalformedURLException e){ Log.e("DownloadProfilePic", "download: "+e.getMessage()); } return bitmap; } @Override protected Bitmap doInBackground(String... urls) { try { return download(urls[0]); } catch (IOException e) { Log.e("TAG", "doInBackground: "+e.getMessage()); } return null; } @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); if(bitmap!=null) User.getUser().setProfile_bitmap(bitmap); Intent intent = new Intent(MainActivity.this, HomeActivity.class); startActivity(intent); finish(); } } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/MatchFragment.java ================================================ package com.helloworld.goodpoint.ui; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.TextView; import com.helloworld.goodpoint.R; /** * A simple {@link Fragment} subclass. * Use the {@link MatchFragment#newInstance} factory method to * create an instance of this fragment. */ public class MatchFragment extends Fragment { ListView listView; TextView details; //String ObjStat[] ={},ObjDetails; String status[]={"Has found" ,"Its owner has been found","Has found" ,"Its owner has been found", "Has found" ,"Its owner has been found","Has found" ,"Its owner has been found" } ; // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; public MatchFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment MatchFragment. */ // TODO: Rename and change types and number of parameters public static MatchFragment newInstance(String param1, String param2) { MatchFragment fragment = new MatchFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_match, container, false); listView = (ListView) view.findViewById(R.id.lisView); AdapterOfMatchFragment myAdapter = new AdapterOfMatchFragment(getActivity(),status); listView.setAdapter(myAdapter); return view; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/NotificationActivity.java ================================================ package com.helloworld.goodpoint.ui; import android.Manifest; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.util.SparseArray; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.PopupMenu; import androidx.core.app.ActivityCompat; import androidx.loader.content.CursorLoader; import com.google.android.gms.vision.Frame; import com.google.android.gms.vision.face.Face; import com.google.android.gms.vision.face.FaceDetector; import com.google.android.gms.vision.text.TextBlock; import com.google.android.gms.vision.text.TextRecognizer; import com.google.gson.JsonObject; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.adapter.NotificationListAdapter; import com.helloworld.goodpoint.pojo.NotificationItem; import com.helloworld.goodpoint.pojo.Token; import com.helloworld.goodpoint.pojo.User; import com.helloworld.goodpoint.retrofit.ApiClient; import com.helloworld.goodpoint.retrofit.ApiInterface; import com.helloworld.goodpoint.ui.candidate.CandidatePage; import com.shashank.sony.fancytoastlib.FancyToast; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class NotificationActivity extends AppCompatActivity { List list; ListView listView; TextView noNotification; Bitmap img; AlertDialog dialog; AlertDialog.Builder builder; View view; Uri photoFromGallery; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notification); init(); createList(); } private void createList() { ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class); Call>call = apiInterface.getNotification(User.getUser().getId()); call.enqueue(new Callback>() { @Override public void onResponse(Call> call, Response> response) { list = response.body(); if(list == null) list = new ArrayList<>(); showView(); } @Override public void onFailure(Call> call, Throwable t) { Log.e("TAG", "onFailure: "+t.getMessage()); } }); } private void showView() { if(list.isEmpty()){ noNotification.setVisibility(View.VISIBLE); listView.setVisibility(View.GONE); }else { listView.setAdapter(new NotificationListAdapter(this, 0, list)); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView adapterView, View v, int i, long l) { int pos = list.size()-i-1; NotificationListAdapter adapter = (NotificationListAdapter)listView.getAdapter(); adapter.getItem(pos).setRead(true); adapter.notifyDataSetChanged(); ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class); Callcall = apiInterface.updateRead(list.get(pos).getId(), true); call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { if(response.isSuccessful()) { Log.e("TAG", "onResponse: "+response.body().toString()); } else { try { Log.e("TAG", "onFailure2: "+response.errorBody().string()); } catch (IOException e) { e.printStackTrace(); } } } @Override public void onFailure(Call call, Throwable t) { Log.e("TAG", "onFailure: "+t.getMessage()); } }); if(list.get(pos).getType()==3){ //intent to candidate startActivity(new Intent(NotificationActivity.this, CandidatePage.class)); return; } else if(list.get(pos).getType() == 1 || list.get(pos).getType() == 4){ //lost person and lost item if(User.getUser().getId_card_pic().isEmpty()){ view = getLayoutInflater().inflate(R.layout.alert_id_card, null); Button Choose = view.findViewById(R.id.Id_card); Choose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(NotificationActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 11); } else{ Intent I = new Intent(NotificationActivity.this,ID_cardDetection.class); startActivityForResult(I, 10); /* PopupMenu popupMenu = new PopupMenu(NotificationActivity.this, view); popupMenu.getMenuInflater().inflate(R.menu.choose_photo, popupMenu.getMenu()); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.TakePhoto: Intent I = new Intent(NotificationActivity.this,ID_cardDetection.class); startActivityForResult(I, 10); break; case R.id.Gallery: Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI); startActivityForResult(gallery, 11); break; } return true; } }); popupMenu.show();*/ } } }); builder = new AlertDialog.Builder(NotificationActivity.this); builder.setMessage("Please , Upload an image of your id_card"); builder.setView(view); dialog = builder.create(); dialog.show(); return; } } Intent intent = new Intent(NotificationActivity.this,DetailsActivity.class); intent.putExtra("id",list.get(pos).getId()); intent.putExtra("type",list.get(pos).getType()); startActivity(intent); } }); } } public Uri getImageUri(Bitmap bitmap_Image) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bitmap_Image.compress(Bitmap.CompressFormat.JPEG, 100, bytes); String path = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap_Image, "id card", null); return Uri.parse(path); } private String getRealPathFromURI(Uri imageUri) { String[] proj = {MediaStore.Images.Media.DATA}; CursorLoader loader = new CursorLoader(this, imageUri, proj, null, null, null); Cursor cursor = loader.loadInBackground(); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String result = cursor.getString(column_index); cursor.close(); return result; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode==RESULT_OK&&data!=null) { switch(requestCode) { case 10: { img =(Bitmap) GlobalVar.realcameraIdCard; photoFromGallery = getImageUri(img); } break; /*case 11: photoFromGallery = data.getData(); try { img = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoFromGallery); } catch (IOException e) { e.printStackTrace(); } break;*/ } checkVaildIdcard(); } } private void checkVaildIdcard() { TextView messageforuser = view.findViewById(R.id.messageforuser); boolean flag_not_idCard = false; FaceDetector faceDetector = new FaceDetector.Builder(this) .setTrackingEnabled(false) .setLandmarkType(FaceDetector.ALL_LANDMARKS) .setMode(FaceDetector.FAST_MODE).build(); if (!faceDetector.isOperational()) { Toast.makeText(this, "Face Detection can't be setup", Toast.LENGTH_SHORT).show(); } else { Frame frame = new Frame.Builder().setBitmap(img).build(); SparseArray sparseArray = faceDetector.detect(frame); if(sparseArray.size() != 1) { flag_not_idCard = true; } TextRecognizer textRecognizer = new TextRecognizer.Builder(this).build(); if(!textRecognizer.isOperational()) Toast.makeText(this, "textRecognizer can't be setup", Toast.LENGTH_SHORT).show(); else { Frame frametext = new Frame.Builder().setBitmap(img).build(); SparseArray sparseArraytext = textRecognizer.detect(frame); TextBlock item; if(sparseArraytext.size()>4 || sparseArraytext.size()<1) { flag_not_idCard = true; } else if(sparseArraytext.size()>=1) { item = sparseArraytext.valueAt(sparseArraytext.size() - 1); if(item.getValue().length() != 9) flag_not_idCard = true; } Log.e("img", "num of img : "+sparseArray.size()+" num of text " +sparseArraytext.size()); } if(flag_not_idCard) { messageforuser.setTextColor(0xFFB80D0D); messageforuser.setText("Error, The card picture cannot be recognized\nplease upload your id card"); } else{ dialog.dismiss(); builder = new AlertDialog.Builder(NotificationActivity.this); builder.setMessage("Your id_card has been successfully taken").setNegativeButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class); Call call = apiInterface.refresh(Token.getToken().getRefresh()); call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { File file = new File(getRealPathFromURI(photoFromGallery)); RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file); MultipartBody.Part Pimage = MultipartBody.Part.createFormData("id_card_pic", file.getName(), requestBody); CallidcardCall = apiInterface.setIdCard(response.body().getAccess(), Pimage); idcardCall.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { Log.d("TAG", "onResponse: Success"); } @Override public void onFailure(Call call, Throwable t) { Log.e("TAG", "onFailure: "+t.getMessage()); } }); } @Override public void onFailure(Call call, Throwable t) { Log.e("TAG", "onFailure: "+t.getMessage()); } }); }}); dialog = builder.create(); dialog.show(); } } } private void init() { list = new ArrayList<>(); listView = findViewById(R.id.notification_listview); noNotification = findViewById(R.id.no_notification); if(User.getUser().getId() == null || User.getUser().getId().isEmpty()) User.getUser().setId(getIntent().getExtras().getString("ID")); if(Token.getToken().getRefresh() == null || Token.getToken().getRefresh().isEmpty()) Token.getToken().setRefresh(new PrefManager(this).isLoginned()); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/PrefManager.java ================================================ package com.helloworld.goodpoint.ui; import android.content.Context; import android.content.SharedPreferences; public class PrefManager { SharedPreferences pref; SharedPreferences.Editor editor; Context _context; // shared pref mode int PRIVATE_MODE = 0; // Shared preferences file name private static final String PREF_NAME = "androidhive-welcome"; private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch"; private static final String IS_LOGINNED = "Token"; private static final String LINK = "ngrok"; public PrefManager(Context context) { this._context = context; pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE); editor = pref.edit(); } public void setFirstTimeLaunch(boolean isFirstTime) { editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime); editor.commit(); } public boolean isFirstTimeLaunch() { return pref.getBoolean(IS_FIRST_TIME_LAUNCH,true); } public void setLogin(String token){ editor.putString(IS_LOGINNED, token); editor.commit(); } public void setLogout(){ editor.putString(IS_LOGINNED, ""); editor.commit(); } public String isLoginned() { return pref.getString(IS_LOGINNED,""); } public void setNGROKLink(String link){ editor.putString(LINK, link); editor.commit(); } public String getNGROKLink() { return pref.getString(LINK,"http://127.0.0.1:8000/"); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/ProfileFragment.java ================================================ package com.helloworld.goodpoint.ui; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.pojo.LostItem; import com.helloworld.goodpoint.pojo.Token; import com.helloworld.goodpoint.pojo.User; import com.helloworld.goodpoint.retrofit.ApiClient; import com.helloworld.goodpoint.retrofit.ApiInterface; import de.hdodenhof.circleimageview.CircleImageView; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class ProfileFragment extends Fragment { TextView name_above,email_above,name,email,phone,city,date,losts,founds; CircleImageView pic; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_profile, container, false); name_above = v.findViewById(R.id.above_name); email_above = v.findViewById(R.id.above_mail); name = v.findViewById(R.id.username_p); email = v.findViewById(R.id.e_mail); phone = v.findViewById(R.id.phone_p); city = v.findViewById(R.id.city_p); date = v.findViewById(R.id.birth_date); pic = v.findViewById(R.id.profile_pic); losts = v.findViewById(R.id.lost_no); founds = v.findViewById(R.id.found_no); name_above.setText(User.getUser().getUsername()); email_above.setText(User.getUser().getEmail()); losts.setText(User.getUser().getLosts().size() + ""); founds.setText(User.getUser().getFounds().size() + ""); name.setText(User.getUser().getUsername()); email.setText(User.getUser().getEmail()); phone.setText(User.getUser().getPhone()); city.setText(User.getUser().getCity()); date.setText(User.getUser().getBirthdate()); if(User.getUser().getProfile_bitmap() != null) pic.setImageBitmap(User.getUser().getProfile_bitmap()); return v; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/SigninActivity.java ================================================ package com.helloworld.goodpoint.ui; import android.app.AlertDialog; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.util.Patterns; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.textfield.TextInputLayout; import com.google.gson.JsonObject; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.pojo.Token; import com.helloworld.goodpoint.pojo.User; import com.helloworld.goodpoint.retrofit.ApiClient; import com.helloworld.goodpoint.retrofit.ApiInterface; import com.helloworld.goodpoint.ui.forgetPasswordScreens.MakeSelection; import org.json.JSONArray; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.regex.Pattern; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class SigninActivity extends AppCompatActivity implements View.OnClickListener { private EditText Email, Pass; private TextInputLayout tilUserName, tilEmail, tilPassword, tilCity, tilPhone; private TextView ForgetPass; private CheckBox RememberMe; private Button Sigin, CreateNewAccount; private static final Pattern PASSWORD_PATTERN = Pattern.compile("^" + "(?=.*[0-9])" + //at least 1 digit "(?=.*[a-z])" + //at least 1 lower case letter "(?=.*[A-Z])" + //at least 1 upper case letter // "(?=.*[a-zA-Z])" + //any letter // "(?=.*[@#$%^&+=])" + //at least 1 special character // "(?=\\S+$)" + //no white spaces ".{8,}" + //at least 8 characters "$"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); //getActionBar().hide(); setContentView(R.layout.activity_signin); inti(); String f; } protected void inti() { Email = findViewById(R.id.email); Pass = findViewById(R.id.pass); tilPassword = findViewById(R.id.tilPass); ForgetPass = findViewById(R.id.forgetPass); Sigin = findViewById(R.id.signin); CreateNewAccount = findViewById(R.id.NewAccount); RememberMe = findViewById(R.id.checkbox); Sigin.setOnClickListener(this); CreateNewAccount.setOnClickListener(this); ForgetPass.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent myIntent = new Intent(view.getContext(), MakeSelection.class); startActivityForResult(myIntent, 0); } }); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.signin: if (validAccount() && validatePassword()) { loginUser(RememberMe.isChecked()); //startActivity(new Intent(SigninActivity.this, HomeActivity.class)); } else Toast.makeText(this, "Invalid account", Toast.LENGTH_SHORT).show(); //startActivity(new Intent(SigninActivity.this, HomeActivity.class)); break; case R.id.NewAccount: startActivity(new Intent(this, SignupActivity.class)); break; } } private boolean validatePassword() { String passwordInput = Pass.getText().toString().trim(); if (passwordInput.isEmpty()) { tilPassword.setError("Field can't be empty"); return false; } else if (!PASSWORD_PATTERN.matcher(passwordInput).matches()) { tilPassword.setError("Must contains digits, lower&upper case letters and length > 8"); /*if(!passwordInput.matches("[0-9]+")) Pass.setError("must contain at least 1 digit"); else if(!passwordInput.matches("[a-z]+")) Pass.setError("must contain at least 1 lower case letter"); else if(!passwordInput.matches("[A-Z]+")) Pass.setError("must contain at least 1 upper case letter"); else Pass.setError("must contain at least 8 characters");*/ return false; } else { tilPassword.setError(null); return true; } } private boolean validateEmail() { String emailInput = Email.getText().toString().trim(); if (emailInput.isEmpty()) { Email.setError("Field can't be empty"); return false; } else if (!Patterns.EMAIL_ADDRESS.matcher(emailInput).matches()) { Email.setError("Please enter a valid email address"); return false; } else { Email.setError(null); return true; } } private boolean validAccount() { //check validation if (validateEmail()) return true; else return false; } public void loginUser(boolean Remember) { String emailInput = Email.getText().toString().trim(); String passwordInput = Pass.getText().toString().trim(); ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class); Call call = apiInterface.getToken(emailInput, passwordInput); call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { if (response.isSuccessful()) { String token = response.body().getAccess(); Token.getToken().setAccess(response.body().getAccess()); Token.getToken().setRefresh(response.body().getRefresh()); if (Remember) { new PrefManager(getApplicationContext()).setLogin(response.body().getRefresh()); } Call call2 = apiInterface.getData("Bearer " + token); call2.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { try { Log.d("e","res="+response.body().toString()); JSONObject jsonObject = new JSONObject(response.body().toString()).getJSONObject("user"); String id = jsonObject.getString("id"); String name = jsonObject.getString("username"); String email = jsonObject.getString("email"); String phone = jsonObject.getString("phone"); String city = jsonObject.getString("city"); String birthdate = jsonObject.getString("birthdate"); String Userimage = jsonObject.getString("profile_pic"); String idcardimage = jsonObject.getString("id_card_pic"); JSONArray jsonArray = jsonObject.getJSONArray("losts"); Log.e("blabla", jsonArray.length() + ""); for(int i=0;i call, Throwable t) { Toast.makeText(SigninActivity.this, t.getMessage(), Toast.LENGTH_LONG).show(); } }); } else Toast.makeText(SigninActivity.this, "Invalid account.", Toast.LENGTH_SHORT).show(); } @Override public void onFailure(Call call, Throwable t) { Toast.makeText(SigninActivity.this, t.getMessage(), Toast.LENGTH_LONG).show(); } }); } class DownloadProfilePic extends AsyncTask { AlertDialog.Builder builder; AlertDialog dialog; @Override protected void onPreExecute() { super.onPreExecute(); builder = new AlertDialog.Builder(SigninActivity.this); builder.setCancelable(false); View view = getLayoutInflater().inflate(R.layout.progress_bar_alert, null); builder.setView(view); dialog = builder.create(); dialog.show(); } private Bitmap download(String urlLink) throws IOException { Bitmap bitmap = null; URL url = null; HttpURLConnection httpConn; InputStream is = null; Log.e("ProfilePic", urlLink); try { url = new URL(urlLink); httpConn = (HttpURLConnection) url.openConnection(); httpConn.connect(); is = httpConn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); }catch (MalformedURLException e){ Log.e("DownloadProfilePic", "download: "+e.getMessage()); } return bitmap; } @Override protected Bitmap doInBackground(String... urls) { try { return download(urls[0]); } catch (IOException e) { Log.e("TAG", "doInBackground: "+e.getMessage()); } return null; } @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); dialog.dismiss(); if(bitmap!=null) User.getUser().setProfile_bitmap(bitmap); Intent intent = new Intent(SigninActivity.this, HomeActivity.class); startActivity(intent); finish(); } } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/SignupActivity.java ================================================ package com.helloworld.goodpoint.ui; import android.Manifest; import android.app.DatePickerDialog; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.util.Patterns; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.loader.content.CursorLoader; import com.google.android.material.textfield.TextInputLayout; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.pojo.RegUser; import com.helloworld.goodpoint.retrofit.ApiClient; import com.helloworld.goodpoint.retrofit.ApiInterface; import com.shashank.sony.fancytoastlib.FancyToast; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.regex.Pattern; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class SignupActivity extends AppCompatActivity { private TextView DateT; private TextInputLayout tilUserName, tilEmail, tilPassword, tilCity, tilPhone; private EditText UserName, Email, Password, Phone; AutoCompleteTextView city; private DatePickerDialog.OnDateSetListener DateSet; private int year, month, Day; private ImageView image; Button CreateAccount; List list; Bitmap Bitmap_Image ; Uri imageUri; private static final Pattern PASSWORD_PATTERN = Pattern.compile("^" + "(?=.*[0-9])" + //at least 1 digit "(?=.*[a-z])" + //at least 1 lower case letter "(?=.*[A-Z])" + //at least 1 upper case letter //"(?=.*[a-zA-Z])" + //any letter //"(?=.*[@#$%^&+=])" + //at least 1 special character //"(?=\\S+$)" + //no white spaces ".{8,}" + //at least 4 characters "$"); public SignupActivity() { } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_signup); //getSupportActionBar().setTitle("Sing up"); inti(); if(savedInstanceState != null ) { Bitmap_Image = savedInstanceState.getParcelable("BitmapImage"); if(Bitmap_Image != null){ image.setImageBitmap(Bitmap_Image); } } DateT.setOnClickListener(new View.OnClickListener() { // @RequiresApi(api = Build.VERSION_CODES.N) @Override public void onClick(View view) { DatePickerDialog dialog = new DatePickerDialog( SignupActivity.this, android.R.style.Theme_Holo_Light_Dialog_MinWidth, DateSet, year, month, Day ); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.show(); } }); DateSet = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int y, int m, int d) { m++; if (y > year || (y == year && m - 1 > month)|| (y == year && m - 1 == month && d > Day) ) { String Date = y + "-" + m + "-" + d; //String Date = d + "/" + m + "/" + y; String todayDate = year + "-" + (month + 1) + "-" + Day; //String todayDate = Day + "/" + (month + 1) + "/" + year; DateT.setText(todayDate); FancyToast.makeText(SignupActivity.this,"Invalid date",FancyToast.LENGTH_LONG, FancyToast.ERROR,false).show(); } else { String Date = y + "-" + m + "-" + d; //String Date = d + "/" + m + "/" + y; DateT.setText(Date); } } }; CreateAccount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(!confirmInput(view) ){ registerUser(); //startActivity(new Intent(SignupActivity.this,check_registration.class)); } } }); } protected void inti() { UserName = findViewById(R.id.edName); Email = findViewById(R.id.edEmail); Password = findViewById(R.id.edPass); city = findViewById(R.id.edCity); Phone =findViewById(R.id.edPhone); tilUserName = findViewById(R.id.tilName); tilEmail = findViewById(R.id.tilEmail); tilPassword = findViewById(R.id.tilPass); tilCity = findViewById(R.id.tilcity); tilPhone =findViewById(R.id.tilPhone); DateT = findViewById(R.id.Date); image = findViewById(R.id.im); registerForContextMenu(image); CreateAccount = findViewById(R.id.createAccount); Calendar cal = Calendar.getInstance();//To get today's date year = cal.get(Calendar.YEAR); month = cal.get(Calendar.MONTH); Day = cal.get(Calendar.DAY_OF_MONTH); String TodayDate = year + "-" + (month + 1) + "-" + Day; //String TodayDate = Day + "/" + (month + 1) + "/" + year; DateT.setText(TodayDate);/**/ prepareList List = new prepareList(); list = List.prepareList(this); ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list); city.setThreshold(1); city.setAdapter(adapter); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); getMenuInflater().inflate(R.menu.menu_main, menu); Toast.makeText(this, "onCreateContextMenu", Toast.LENGTH_SHORT); //menu.getItem(2).setEnabled(false); menu.findItem(R.id.Delete).setVisible(false); } @Override public boolean onContextItemSelected(@NonNull MenuItem item) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},11); } else { switch (item.getItemId()) { case R.id.action_capture: Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (cameraIntent.resolveActivity(getPackageManager()) != null) { startActivityForResult(cameraIntent, 10); } break; case R.id.action_choose: //Toast.makeText(this,"Hello",Toast.LENGTH_SHORT).show(); Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI); startActivityForResult(gallery, 11); break; } } return super.onContextItemSelected(item); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 10 && resultCode == RESULT_OK) { Bitmap_Image = (Bitmap) data.getExtras().get("data"); imageUri = getImageUri(Bitmap_Image); image.setImageBitmap(Bitmap_Image); } if (requestCode == 11 && resultCode == RESULT_OK) { imageUri = data.getData(); try { Bitmap_Image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri); } catch (IOException e) { Toast.makeText(this,"Dina",Toast.LENGTH_SHORT).show(); e.printStackTrace(); } image.setImageURI(imageUri); } } private boolean validateEmail() { String emailInput = Email.getText().toString().trim(); if (emailInput.isEmpty()) { Email.setError("Field can't be empty"); return false; } else if (!Patterns.EMAIL_ADDRESS.matcher(emailInput).matches()) { Email.setError("Please enter a valid email address"); return false; } else { Email.setError(null); return true; } } public boolean isAlpha(String name) { char[] chars = name.toCharArray(); for (char c : chars) { if(!Character.isLetter(c) | c !=' ' ) { return false; } } return true; }/**/ private boolean validateUsername() { String usernameInput = UserName.getText().toString().trim(); if (usernameInput.isEmpty()) { UserName.setError("Field can't be empty"); return false; } else if (usernameInput.length() > 15) { UserName.setError("Username too long"); return false; } else if (usernameInput.length() < 2) { UserName.setError("Username too short"); return false; }else if (isAlpha(usernameInput)) { UserName.setError("Using only Letters"); return false; } else { UserName.setError(null); return true; } } private boolean find_Digit(String s){ String n ; for(int i = 1; i < s.length(); i++){ n = s.substring(i-1,i); if(n.matches("[0-9]")) return true; } return false; } private boolean validatePassword() { String passwordInput = Password.getText().toString().trim(); if (passwordInput.isEmpty()) { tilPassword.setError("Field can't be empty"); return false; } else if (!PASSWORD_PATTERN.matcher(passwordInput).matches()) { /*if(!find_Digit(passwordInput) ) tilPassword.setError("must contain at least 1 digit"); else if(!passwordInput.matches("[a-z]")) tilPassword.setError("must contain at least 1 lower case letter"); else if(!passwordInput.matches("[A-Z]")) tilPassword.setError("must contain at least 1 upper case letter"); else*/ tilPassword.setError("Must contains digits, lower&upper case letters and length > 8"); return false; } else { tilPassword.setError(null); return true; } } private boolean validateCity() { String cityInput = city.getText().toString().trim(); if (cityInput.isEmpty()) { city.setError("Field can't be empty"); return false; } else if (!list.contains(cityInput)) { city.setError("Please Enter valid city!"); return false; } else { city.setError(null); return true; } }// private boolean validatePhone() { String pInput = Phone.getText().toString().trim(); if (pInput.isEmpty()) { Phone.setError("Field can't be empty"); return false; } else if (pInput.length() != 11) { Phone.setError("Please enter a valid phone number"); return false; } else { /*try{ int i = Integer.parseInt(pInput); tilPhone.setError("Please enter a valid phone number"); } catch (Exception e){ tilPhone.setError(null); }*/ Phone.setError(null); return true; } }//| !validatePhone() public boolean confirmInput(View v) { if (!validateEmail() | !validateUsername() | !validatePassword() | !validatePhone() |!validateCity()) { return true; } /*String input = "Email: " + Email.getText().toString(); input += "\n"; input += "Username: " + UserName.getText().toString(); input += "\n"; input += "Password: " + Password.getText().toString(); Toast.makeText(this, input, Toast.LENGTH_SHORT).show();*/ return false; }/**/ protected void prepareList() { list = new ArrayList<>(); list.add(getString(R.string.Cairo)); list.add(getString(R.string.Alexandria)); list.add(getString(R.string.ShubraElKheima)); list.add(getString(R.string.Giza)); list.add(getString(R.string.PortSaid)); list.add(getString(R.string.Suez)); list.add(getString(R.string.ElMahallaElKubra)); list.add(getString(R.string.Luxor)); list.add(getString(R.string.Mansoura)); list.add(getString(R.string.Tanta)); list.add(getString(R.string.Asyut)); list.add(getString(R.string.Ismailia)); list.add(getString(R.string.Faiyum)); list.add(getString(R.string.Zagazig)); list.add(getString(R.string.Damietta)); list.add(getString(R.string.Aswan)); list.add(getString(R.string.Minya)); list.add(getString(R.string.BeniSuef)); list.add(getString(R.string.Hurghada)); list.add(getString(R.string.Qena)); list.add(getString(R.string.Sohag)); list.add(getString(R.string.ShibinElKom)); list.add(getString(R.string.Banha)); list.add(getString(R.string.Arish)); } public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable("BitmapImage",Bitmap_Image); } public Uri getImageUri(Bitmap bitmap_Image) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bitmap_Image.compress(Bitmap.CompressFormat.JPEG, 100, bytes); String path = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap_Image, "Profile", null); return Uri.parse(path); } private String getRealPathFromURI(Uri imageUri) { String[] proj = {MediaStore.Images.Media.DATA}; CursorLoader loader = new CursorLoader(this, imageUri, proj, null, null, null); Cursor cursor = loader.loadInBackground(); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String result = cursor.getString(column_index); cursor.close(); return result; } public void registerUser() { String emailInput = Email.getText().toString().trim(); String passwordInput = Password.getText().toString().trim(); String usernameInput = UserName.getText().toString().trim(); String pInput = Phone.getText().toString().trim(); String cityInput = city.getText().toString().trim(); String Datee = DateT.getText().toString().trim(); ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class); Call call; if(imageUri != null) { File file = new File(getRealPathFromURI(imageUri)); RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file); MultipartBody.Part image = MultipartBody.Part.createFormData("profile_pic", file.getName(), requestBody); call = apiInterface.storePost(emailInput,passwordInput,usernameInput,pInput,cityInput,Datee,image); } else call = apiInterface.storePost(emailInput,passwordInput,usernameInput,pInput,cityInput,Datee); call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { if(response.isSuccessful()) { startActivity(new Intent(SignupActivity.this,check_registration.class)); finish(); } else { try { //Log.e("TAG", "onResponse: "+ response.errorBody().string()); JSONObject jsonObject = new JSONObject(response.errorBody().string()).getJSONObject("error"); String mail = jsonObject.getString("username"); String phone = jsonObject.getString("phone"); if(!mail.isEmpty() && !phone.isEmpty()) { Email.setError(mail); Phone.setError(phone); } else if(!mail.isEmpty()) Email.setError(mail); else Phone.setError(phone); } catch (IOException | JSONException e) { Toast.makeText(SignupActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } } } @Override public void onFailure(Call call, Throwable t) { Toast.makeText(SignupActivity.this, t.getMessage(), Toast.LENGTH_LONG).show(); } }); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/SlideAdapter.java ================================================ package com.helloworld.goodpoint.ui; import android.view.FrameStats; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; import java.util.List; public class SlideAdapter extends FragmentStatePagerAdapter { private List fragmentList; public SlideAdapter(FragmentManager fm ,List fragmentList){ super(fm); this.fragmentList= fragmentList; } @Override public Fragment getItem(int position) { return fragmentList.get(position); } @Override public int getCount() { return fragmentList.size(); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/WelcomeActivity.java ================================================ package com.helloworld.goodpoint.ui; import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.viewpager.widget.ViewPager; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.helloworld.goodpoint.R; import java.util.ArrayList; import java.util.List; import fragments.PageFragment1; import fragments.PageFragment2; import fragments.PageFragment3; public class WelcomeActivity extends AppCompatActivity { private ViewPager pager; private SlideAdapter slideAdapter; private LinearLayout Dots_layout; private ImageView[] dots; private int[] layouts = {R.layout.slider_page1, R.layout.slider_page2, R.layout.slider_page3}; private TextView Next, Skip, Start; private ImageView arrow; private PrefManager prefManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); prefManager = new PrefManager(this); if (!prefManager.isFirstTimeLaunch()) { launchHomeScreen(); finish(); } setContentView(R.layout.activity_welcome); List list = new ArrayList<>(); list.add(new PageFragment1()); list.add(new PageFragment2()); list.add(new PageFragment3()); pager = findViewById(R.id.viewpager); slideAdapter = new SlideAdapter(getSupportFragmentManager(), list); pager.setAdapter(slideAdapter); Dots_layout = (LinearLayout) findViewById(R.id.dotsLayout); Skip = (TextView) findViewById(R.id.Skip); Next = (TextView) findViewById(R.id.Nextt); createDots(0); pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { createDots(position); // changing the next button text 'NEXT' / 'START ' if (position == layouts.length - 1) { // last page. make button text to START Next.setText(getString(R.string.start)); Skip.setVisibility(View.GONE); } else { // still pages are left Next.setText(getString(R.string.next)); Skip.setVisibility(View.VISIBLE); } } @Override public void onPageScrollStateChanged(int state) { } }); Skip.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { launchHomeScreen(); } }); Next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // checking for last page // if last page home screen will be launched int current = getItem(+1); if (current < layouts.length) { // move to next screen pager.setCurrentItem(current); } else { launchHomeScreen(); } } }); Skip.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { launchHomeScreen(); } }); } private void launchHomeScreen (){ prefManager.setFirstTimeLaunch(false); startActivity(new Intent(WelcomeActivity.this, MainActivity.class)); finish(); } private int getItem(int i) { return pager.getCurrentItem() + i; } private void createDots(int current_position) { if (Dots_layout != null) Dots_layout.removeAllViews(); dots = new ImageView[layouts.length]; for (int i = 0; i < layouts.length; i++) { dots[i] = new ImageView(this); if (i == current_position) { dots[i].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.active_dot)); } else { dots[i].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.default_dot)); } LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT , ViewGroup.LayoutParams.WRAP_CONTENT); params.setMargins(4, 0, 4, 0); Dots_layout.addView(dots[i], params); } } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/candidate/CandidatePage.java ================================================ package com.helloworld.goodpoint.ui.candidate; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.RadioButton; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.pojo.LostItem; import com.helloworld.goodpoint.pojo.LostObject; import com.helloworld.goodpoint.pojo.NotificationItem; import com.helloworld.goodpoint.retrofit.ApiClient; import com.helloworld.goodpoint.retrofit.ApiInterface; import com.helloworld.goodpoint.ui.GlobalVar; import com.helloworld.goodpoint.ui.PrefManager; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class CandidatePage extends AppCompatActivity implements AdapterView.OnItemClickListener { private static final String TAG = "CandidatePage"; //vars private ArrayList mNames = new ArrayList<>(); private ArrayList mImageUrls = new ArrayList<>(); RadioButton rb; Button Done_btn; SubItemAdapter recyclerViewAdapter; TextView type; List items; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_candidate_page); type = findViewById(R.id.tv_item_title1); Done_btn = findViewById(R.id.d_btn); RecyclerView rvItem = findViewById(R.id.rv_sub_item1); LostItem item = new LostItem("Phone", "123456788", "Lenovo", "White", "details"); if (GlobalVar.lostList == null && GlobalVar.percentList == null) { GlobalVar.lostList = new ArrayList<>(); GlobalVar.percentList = new ArrayList<>(); GlobalVar.lostList.add(item); GlobalVar.lostList.add(item); GlobalVar.lostList.add(item); GlobalVar.percentList.add("60%"); GlobalVar.percentList.add("50%"); GlobalVar.percentList.add("40%"); GlobalVar.type="Phone"; } type.setText(GlobalVar.type); LinearLayoutManager layoutManager = new LinearLayoutManager( rvItem.getContext(), LinearLayoutManager.VERTICAL, false ); recyclerViewAdapter = new SubItemAdapter(buildSubItemList(GlobalVar.lostList), this); recyclerViewAdapter.setOnItemClickListener(this); rvItem.setAdapter(recyclerViewAdapter); rvItem.setLayoutManager(layoutManager); Done_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SubItem list = GlobalVar.sublist.get(GlobalVar.p); storeCandidatesNotifictation(list); finish(); } }); } private List buildSubItemList(List items) { List subItemList = new ArrayList<>(); for (int i = 0; i < items.size(); i++) { com.helloworld.goodpoint.ui.candidate.SubItem subItem = new com.helloworld.goodpoint.ui.candidate.SubItem(items.get(i).getType(), items.get(i).getDescription(), GlobalVar.percentList.get(i), i, items.get(i).getId()); subItemList.add(subItem); } GlobalVar.sublist = subItemList; return subItemList; } @Override public void onItemClick(AdapterView parent, View view, int position, long id) { SubItem list = GlobalVar.sublist.get(position); int i = list.getPos(); i += 1; GlobalVar.p = position; Toast.makeText(this, "Item (" + i + ") is selected", Toast.LENGTH_SHORT).show(); } public void storeCandidatesNotifictation(SubItem item) { ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class); Call call = apiInterface.getObject(item.getId()); call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { LostObject obj = response.body(); if(response.body()!=null) { Call call2 = apiInterface.storeNotification(obj.getUser_id(), "Item matched", "Your " + item.getSubItemTitle() + " is Found ", 4); call2.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { if (response.isSuccessful()) { Toast.makeText(CandidatePage.this, "Notification is posted.", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(CandidatePage.this, "The Notification is not posted.", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call call, Throwable t) { Toast.makeText(CandidatePage.this, t.getMessage(), Toast.LENGTH_LONG).show(); } }); } } @Override public void onFailure(Call call, Throwable t) { Toast.makeText(CandidatePage.this, t.getMessage(), Toast.LENGTH_LONG).show(); } }); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/candidate/Item.java ================================================ package com.helloworld.goodpoint.ui.candidate; import java.util.List; public class Item { private String itemTitle; private List subItem; public String getItemTitle() { return itemTitle; } public void setItemTitle(String itemTitle) { this.itemTitle = itemTitle; } public List getSubItem() { return subItem; } public void setSubItem(List subItem) { this.subItem = subItem; } public Item(String itemTitle, List subItem) { this.itemTitle = itemTitle; this.subItem = subItem; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/candidate/ItemAdapter.java ================================================ package com.helloworld.goodpoint.ui.candidate; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.helloworld.goodpoint.R; import java.util.List; public class ItemAdapter extends RecyclerView.Adapter { private RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool(); private List itemlist; private Context cxt; ItemAdapter(List item,Context cxt) { this.itemlist= item; this.cxt=cxt; } @NonNull @Override public ItemAdapter.ItemViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.activity_candidate_page, viewGroup, false); return new ItemAdapter.ItemViewHolder(view); } @Override public void onBindViewHolder(@NonNull ItemAdapter.ItemViewHolder itemViewHolder, int i) { com.helloworld.goodpoint.ui.candidate.Item item = itemlist.get(i); itemViewHolder.tvItem.setText(item.getItemTitle()); // Create layout manager with initial prefetch item count LinearLayoutManager layoutManager = new LinearLayoutManager( itemViewHolder.rvSubItem.getContext(), LinearLayoutManager.HORIZONTAL, false ); layoutManager.setInitialPrefetchItemCount(item.getSubItem().size()); // Create sub item view adapter com.helloworld.goodpoint.ui.candidate.SubItemAdapter subItemAdapter = new com.helloworld.goodpoint.ui.candidate.SubItemAdapter(item.getSubItem(),cxt); itemViewHolder.rvSubItem.setLayoutManager(layoutManager); itemViewHolder.rvSubItem.setAdapter(subItemAdapter); itemViewHolder.rvSubItem.setRecycledViewPool(viewPool); } @Override public int getItemCount() { return itemlist.size(); } class ItemViewHolder extends RecyclerView.ViewHolder { private TextView tvItem; private RecyclerView rvSubItem; ItemViewHolder(View itemView) { super(itemView); tvItem = itemView.findViewById(R.id.tv_item_title1); rvSubItem = itemView.findViewById(R.id.rv_sub_item1); } } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/candidate/SubItem.java ================================================ package com.helloworld.goodpoint.ui.candidate; public class SubItem { private String subItemTitle; private String subItemDes; private String persent; private int pos; private String id; public SubItem(String subItemTitle, String subItemDes, String persent, int pos, String id) { this.subItemTitle = subItemTitle; this.subItemDes = subItemDes; this.persent = persent; this.pos = pos; this.id = id; } public String getSubItemTitle() { return subItemTitle; } public void setSubItemTitle(String subItemTitle) { this.subItemTitle = subItemTitle; } public String getSubItemDes() { return subItemDes; } public void setSubItemDes(String subItemDes) { this.subItemDes = subItemDes; } public String getPersent() { return persent; } public void setPersent(String persent) { this.persent = persent; } public int getPos() { return pos; } public void setPos(int pos) { this.pos = pos; } public String getId() { return id; } public void setId(String id) { this.id = id; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/candidate/SubItemAdapter.java ================================================ package com.helloworld.goodpoint.ui.candidate; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.RadioButton; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.helloworld.goodpoint.R; import java.util.List; public class SubItemAdapter extends RecyclerView.Adapter { private List subItemList; private int lastSelectedPosition = -1; private Context context; private AdapterView.OnItemClickListener onItemClickListener; SubItemAdapter(List subItem, Context ctx) { this.subItemList = subItem; context = ctx; } @NonNull @Override public SubItemAdapter.SubItemViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_sub_item, viewGroup, false); return new SubItemAdapter.SubItemViewHolder(view,this); } @Override public void onBindViewHolder(@NonNull SubItemAdapter.SubItemViewHolder subItemViewHolder, int i) { com.helloworld.goodpoint.ui.candidate.SubItem subItem = subItemList.get(i); subItemViewHolder.tvItemType.setText(subItem.getSubItemTitle()); subItemViewHolder.tvItemDes.setText(subItem.getSubItemDes()); subItemViewHolder.tvItemPercent.setText(subItem.getPersent()); try { subItemViewHolder.bindData(subItem, i); subItem.setPos(i); } catch (Exception e) { e.printStackTrace(); } //Toast.makeText(cxt, "size="+item.getSubItemList().size(),Toast.LENGTH_LONG).show(); } public void setOnItemClickListener(AdapterView.OnItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } public void onItemHolderClick(SubItemAdapter.SubItemViewHolder holder) { if (onItemClickListener != null) onItemClickListener.onItemClick(null, holder.itemView, holder.getAdapterPosition(), holder.getItemId()); } @Override public int getItemCount() { return subItemList.size(); } class SubItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private SubItemAdapter mAdapter; private TextView tvItemType; private TextView tvItemDes; private TextView tvItemPercent; private RadioButton rb; public SubItemViewHolder(View itemView, final SubItemAdapter mAdapter) { super(itemView); this.mAdapter=mAdapter; tvItemType = itemView.findViewById(R.id.tv_sub_item_title); tvItemDes=itemView.findViewById(R.id.tv_sub_item_des); tvItemPercent=itemView.findViewById(R.id.tv_sub_item_percent); rb = itemView.findViewById(R.id.radioButtonn); itemView.setOnClickListener(this); rb.setOnClickListener( this); } public void bindData(SubItem list, int position) { rb.setChecked(position==lastSelectedPosition); } public void onClick(View v){ lastSelectedPosition = getAdapterPosition(); notifyItemRangeChanged(0,subItemList.size()); mAdapter.onItemHolderClick(SubItemAdapter.SubItemViewHolder.this); } } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/candidate/lostitem.java ================================================ package com.helloworld.goodpoint.ui.candidate; public class lostitem { String type,descriotion; public lostitem(String type, String descriotion) { this.type = type; this.descriotion = descriotion; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDescriotion() { return descriotion; } public void setDescriotion(String descriotion) { this.descriotion = descriotion; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/check_registration.java ================================================ package com.helloworld.goodpoint.ui; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat; import android.content.Intent; import android.graphics.drawable.AnimatedVectorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.helloworld.goodpoint.R; public class check_registration extends AppCompatActivity { ImageView done; Button gotoLogin; AnimatedVectorDrawableCompat avd; AnimatedVectorDrawable avd2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_check_registration); gotoLogin = findViewById(R.id.goto_login); done = findViewById(R.id.done); Drawable drawable = done.getDrawable(); if(drawable instanceof AnimatedVectorDrawableCompat){ avd =(AnimatedVectorDrawableCompat) drawable; avd.start(); } else if(drawable instanceof AnimatedVectorDrawable){ avd2 = (AnimatedVectorDrawable) drawable; avd2.start(); } gotoLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //startActivity(new Intent(check_registration.this,SigninActivity.class));//update it finish(); } }); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/forgetPasswordScreens/ForgetPassSuccessMessage.java ================================================ package com.helloworld.goodpoint.ui.forgetPasswordScreens; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.ui.MainActivity; import com.helloworld.goodpoint.ui.SigninActivity; public class ForgetPassSuccessMessage extends AppCompatActivity { private Button login_btn; private ImageView back_btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_forget_pass_success_message); login_btn = (Button) findViewById(R.id.login_btn); back_btn = (ImageView) findViewById(R.id.back_btn); login_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), SigninActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); } }); back_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/forgetPasswordScreens/ForgetPasswordWithEmail.java ================================================ package com.helloworld.goodpoint.ui.forgetPasswordScreens; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import com.helloworld.goodpoint.R; public class ForgetPasswordWithEmail extends AppCompatActivity { private Button next_btn; private EditText email; private ImageView back_btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_forget_password); next_btn = (Button) findViewById(R.id.Next_btn); back_btn = (ImageView) findViewById(R.id.back_btn); email = (EditText) findViewById(R.id.Email); next_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String emailInput = email.getText().toString().trim(); if (emailInput.isEmpty()) { email.setError("Field can't be empty"); email.requestFocus(); } else if (!Patterns.EMAIL_ADDRESS.matcher(emailInput).matches()) { email.setError("Please enter a valid email address"); email.requestFocus(); } else { startActivity(new Intent(ForgetPasswordWithEmail.this, VerifiyCode.class)); } } }); back_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/forgetPasswordScreens/ForgetPasswordWithPhone.java ================================================ package com.helloworld.goodpoint.ui.forgetPasswordScreens; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import com.helloworld.goodpoint.R; public class ForgetPasswordWithPhone extends AppCompatActivity { private Button next_btn; private ImageView back_btn; private EditText phone; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_forget_password_with_phone); next_btn = (Button) findViewById(R.id.Next_btn); back_btn = (ImageView) findViewById(R.id.back_btn); phone = (EditText) findViewById(R.id.Phone); next_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String phoneInput = phone.getText().toString().trim(); if (phoneInput.isEmpty()) { phone.setError("Field can't be empty"); phone.requestFocus(); } else if (phone.length() < 11) { phone.setError("Please enter a valid phone number"); phone.requestFocus(); } else { startActivity(new Intent(ForgetPasswordWithPhone.this, VerifiyCode.class)); } } }); back_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/forgetPasswordScreens/MakeSelection.java ================================================ package com.helloworld.goodpoint.ui.forgetPasswordScreens; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.helloworld.goodpoint.R; public class MakeSelection extends AppCompatActivity { private Button sms_btn, email_btn; private ImageView back_btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_make_selection); sms_btn = (Button) findViewById(R.id.sms_btn); email_btn = (Button) findViewById(R.id.email_btn); back_btn = (ImageView) findViewById(R.id.back_btn); sms_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MakeSelection.this, ForgetPasswordWithPhone.class)); } }); email_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MakeSelection.this, ForgetPasswordWithEmail.class)); } }); back_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/forgetPasswordScreens/SetNewPassword.java ================================================ package com.helloworld.goodpoint.ui.forgetPasswordScreens; import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.textfield.TextInputLayout; import com.helloworld.goodpoint.R; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.text.method.HideReturnsTransformationMethod; import android.text.method.PasswordTransformationMethod; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.util.regex.Pattern; public class SetNewPassword extends AppCompatActivity { private Button ok_btn; private ImageView back_btn; private EditText pass1, pass2; private TextInputLayout errorPass,errorConfirm; boolean isEmailValid, isPasswordValid, isPasswordVisible; private static final Pattern PASSWORD_PATTERN = Pattern.compile("^" + "(?=.*[0-9])" + //at least 1 digit "(?=.*[a-z])" + //at least 1 lower case letter "(?=.*[A-Z])" + //at least 1 upper case letter // "(?=.*[a-zA-Z])" + //any letter // "(?=.*[@#$%^&+=])" + //at least 1 special character // "(?=\\S+$)" + //no white spaces ".{8,}" + //at least 8 characters "$"); @SuppressLint("ClickableViewAccessibility") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_set_new_password); ok_btn = (Button) findViewById(R.id.ok_btn); back_btn = (ImageView) findViewById(R.id.back_btn); pass1 = (EditText) findViewById(R.id.pass1); pass2 = (EditText) findViewById(R.id.pass2); errorPass = (TextInputLayout) findViewById(R.id.errorPass); errorConfirm = (TextInputLayout) findViewById(R.id.errorConfirm); ok_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String password = pass1.getText().toString().trim(); String confirm = pass2.getText().toString().trim(); errorPass.setError(null); errorConfirm.setError(null); if (password.isEmpty()) { errorPass.setError("Please enter Password"); errorPass.setErrorIconDrawable(null); } if (confirm.isEmpty()) { errorConfirm.setError("Please confirm Password"); errorConfirm.setErrorIconDrawable(null); } else if (password.length() < 6) { errorPass.setError("Password must contain 6 characters"); errorPass.setErrorIconDrawable(null); } else if (!PASSWORD_PATTERN.matcher(password).matches()) { errorPass.setError("password to weak!"); errorPass.setErrorIconDrawable(null); } else if (!password.equals(confirm)) { errorConfirm.setError("Password Not matching"); errorConfirm.setErrorIconDrawable(null); } else { startActivity(new Intent(SetNewPassword.this, ForgetPassSuccessMessage.class)); finish(); } } }); back_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/forgetPasswordScreens/VerifiyCode.java ================================================ package com.helloworld.goodpoint.ui.forgetPasswordScreens; import androidx.appcompat.app.AppCompatActivity; import com.chaos.view.PinView; import com.helloworld.goodpoint.R; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; public class VerifiyCode extends AppCompatActivity { private Button verify_btn; private ImageView back_btn; private PinView code; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_verifiy_code); verify_btn=(Button)findViewById(R.id.verify_btn); back_btn=(ImageView)findViewById(R.id.back_btn); code= (PinView)findViewById(R.id.otp_view); verify_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String Code = code.getText().toString().trim(); if (Code.isEmpty()) { code.setError("Please enter the code"); code.requestFocus(); Toast.makeText(VerifiyCode.this, "Invalid Code", Toast.LENGTH_SHORT).show(); } else if (Code.length()<6){ code.setError("Complete the code"); code.requestFocus(); Toast.makeText(VerifiyCode.this, "Invalid Code", Toast.LENGTH_SHORT).show(); } else { startActivity(new Intent(VerifiyCode.this, SetNewPassword.class)); finish(); } } }); back_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/lostFoundObject/FoundObjectActivity.java ================================================ package com.helloworld.goodpoint.ui.lostFoundObject; import android.Manifest; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.net.wifi.WifiManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.Looper; import android.provider.MediaStore; import android.provider.Settings; import android.util.Log; import android.util.SparseArray; import android.view.MenuItem; import android.view.View; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.PopupMenu; import androidx.core.app.ActivityCompat; import androidx.loader.content.CursorLoader; import com.google.android.gms.common.GooglePlayServicesNotAvailableException; import com.google.android.gms.common.GooglePlayServicesRepairableException; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationCallback; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationResult; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.places.Place; import com.google.android.gms.location.places.ui.PlacePicker; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.android.gms.vision.Frame; import com.google.android.gms.vision.face.Face; import com.google.android.gms.vision.face.FaceDetector; import com.google.gson.JsonObject; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.pojo.FoundItem; import com.helloworld.goodpoint.pojo.FoundPerson; import com.helloworld.goodpoint.pojo.LostItem; import com.helloworld.goodpoint.pojo.NotificationItem; import com.helloworld.goodpoint.pojo.User; import com.helloworld.goodpoint.retrofit.ApiClient; import com.helloworld.goodpoint.retrofit.ApiInterface; import com.helloworld.goodpoint.ui.Alert; import com.helloworld.goodpoint.ui.GlobalVar; import com.helloworld.goodpoint.ui.PrefManager; import com.helloworld.goodpoint.ui.prepareList; import com.shashank.sony.fancytoastlib.FancyToast; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Locale; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class FoundObjectActivity extends AppCompatActivity implements View.OnClickListener, objectDataType { private TextView DateFound; private EditText Location; private DatePickerDialog.OnDateSetListener DateSet; private int year, month, Day; private Button Person; private Button Object; private Button MatchFound; private prepareList List; private List listColor; private Fragment PersonF, ObjectF; private String location, City; private String ObjectColor, Serial, brand, textArea_information, Type; private String PName; private ProgressBar progressbar; private WifiManager wifiManager; private final static int PLACE_PICKER_REQUEST = 999; private List Person_Images; double Latitude; double Longitude; private FaceDetector faceDetector; FusedLocationProviderClient fusedLocationProviderClient; private boolean flagPerson, flagObject; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_found_object); Calendar cal = Calendar.getInstance();//To get today's date inti(); if (savedInstanceState != null) { year = savedInstanceState.getInt("year"); month = savedInstanceState.getInt("month"); Day = savedInstanceState.getInt("Day"); flagPerson = savedInstanceState.getBoolean("flagPerson"); flagObject = savedInstanceState.getBoolean("flagObject"); if (flagPerson == true) { Person.setTextColor(0xFFF38E3A); Object.setTextColor(Color.BLACK); } else if (flagObject == true) { Object.setTextColor(0xFFF38E3A); Person.setTextColor(Color.BLACK); } } else { year = cal.get(Calendar.YEAR); month = cal.get(Calendar.MONTH); Day = cal.get(Calendar.DAY_OF_MONTH); } //String todayDate = year + "/" + (month + 1) + "/" + Day; String todayDate = year + "-" + (month + 1) + "-" + Day; DateFound.setText(todayDate); DateSet = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int y, int m, int d) { m++; if (y > year || (m - 1 > month && y >= year) || (d > Day && m - 1 >= month && y >= year)) { FancyToast.makeText(FoundObjectActivity.this, "Invalid date", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show(); //String todayDate = year + "/" + (month + 1) + "/" + Day; String todayDate = year + "-" + (month + 1) + "-" + Day; DateFound.setText(todayDate); } else { year = y; month = m - 1; Day = d; //String Date = y + "/" + m + "/" + d; String Date = y + "-" + m + "-" + d; DateFound.setText(Date); } } }; } @Override protected void onStart() { super.onStart(); fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(FoundObjectActivity.this); if (ActivityCompat.checkSelfPermission(FoundObjectActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(FoundObjectActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(FoundObjectActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 12); } else { getCurrentLocation(); } } @Override public void onClick(View view) { FragmentManager FM = getFragmentManager(); FragmentTransaction FT = FM.beginTransaction(); switch (view.getId()) { case R.id.DateFound: DatePickerDialog dialog = new DatePickerDialog( FoundObjectActivity.this, android.R.style.Theme_Holo_Light_Dialog_MinWidth, DateSet, year, month, Day ); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.show(); break; case R.id.FoundLocatin: PopupMenu popupMenu = new PopupMenu(this, view); popupMenu.getMenuInflater().inflate(R.menu.choose_location, popupMenu.getMenu()); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { if (ActivityCompat.checkSelfPermission(FoundObjectActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(FoundObjectActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(FoundObjectActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 12); } else { switch (item.getItemId()) { case R.id.TakeCurrLocation: isInternetAvailable Available = new isInternetAvailable(); Available.execute(); CurrentLocation Locate = new CurrentLocation(); Locate.execute(); break; case R.id.DeteLocation: boolean flag = false; wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); if (wifiManager.isWifiEnabled()) wifiManager.setWifiEnabled(false); else { flag = true; } PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder(); try { Intent intent = builder.build(FoundObjectActivity.this); startActivityForResult(intent, PLACE_PICKER_REQUEST); if (!flag) wifiManager.setWifiEnabled(true); } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) { Toast.makeText(FoundObjectActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(FoundObjectActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show(); } break; } } return true; } }); popupMenu.show(); break; case R.id.PersonFound: flagPerson = true; flagObject = false; FT.replace(R.id.FragmentFoundID, PersonF, null); Person.setTextColor(0xFFF38E3A); Object.setTextColor(Color.BLACK); FT.commit(); break; case R.id.ObjectFound: flagObject = true; flagPerson = false; FT.replace(R.id.FragmentFoundID, ObjectF, null); Object.setTextColor(0xFFF38E3A); Person.setTextColor(Color.BLACK); FT.commit(); break; case R.id.MatchFound: GlobalVar.allFaces.clear(); if (!flagObject && !flagPerson) { FancyToast.makeText(this, "Specify the type of the missing object", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show(); } else if (flagObject && CheckMatchObject()) { FoundItems(); FoundItem item =new FoundItem(Type,Serial,brand,ObjectColor); getItems(item,getApplicationContext()); FancyToast.makeText(this, "The data has been saved successfully", FancyToast.LENGTH_LONG, FancyToast.SUCCESS, false).show(); //finish(); } else if (flagPerson && CheckMatchPerson()) { faceDetector = new FaceDetector.Builder(this) .setTrackingEnabled(false) .setLandmarkType(FaceDetector.ALL_LANDMARKS) .setMode(FaceDetector.FAST_MODE).build(); if (!faceDetector.isOperational()) { Toast.makeText(this, "Face Detection can't be setup", Toast.LENGTH_SHORT).show(); } checkFaces N = new checkFaces(this); N.execute(); } //FoundItem item=new FoundItem(Type,Serial,brand,ObjectColor); //getItems(item,this); break; } } private boolean CheckMatchPerson() { EditText PersonName = PersonF.getView().findViewById(R.id.PersonName); PName = PersonName.getText().toString(); location = Location.getText().toString(); if (location.isEmpty()) { FancyToast.makeText(this, "Specify where you found this object", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show(); return false; } else if (Person_Images.size() == 0) { FancyToast.makeText(this, "You must put at least one picture!", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show(); return false; } return true; } class checkFaces extends AsyncTask { AlertDialog.Builder builder; AlertDialog dialog; Context context; private checkFaces(Context context) { this.context = context.getApplicationContext(); builder = new AlertDialog.Builder(FoundObjectActivity.this); } @Override protected void onPreExecute() { super.onPreExecute(); builder.setCancelable(false); View view = getLayoutInflater().inflate(R.layout.progress_bar_alert, null); builder.setView(view); dialog = builder.create(); dialog.show(); } @Override protected void onPostExecute(Void a) { super.onPostExecute(a); Log.e("img", "onPostExecute: " + GlobalVar.ImgThatHaveMoreThanOneFace.size() + " " + GlobalVar.FinialFacesThatWillGoToDataBase.size()); if (GlobalVar.allFaces.size() > 0) { FoundPerson.getFoundPerson().setName(PName); FoundPerson.getFoundPerson().setDate(DateFound.getText().toString().trim()); FoundPerson.getFoundPerson().setCity(City); FoundPerson.getFoundPerson().setLongitude(Longitude); FoundPerson.getFoundPerson().setLatitude(Latitude); GlobalVar.flag=1; startActivity(new Intent(FoundObjectActivity.this, Alert.class)); finish(); } else { FoundPerson(); } dialog.dismiss(); } @Override protected Void doInBackground(Void... voids) { GlobalVar.ImgThatHaveMoreThanOneFace.clear(); GlobalVar.FinialFacesThatWillGoToDataBase.clear(); GlobalVar.allFaces.clear(); boolean flag = false; for (int i = 0; i < Person_Images.size(); i++) { Bitmap My = Person_Images.get(i); Bitmap faceBitmap; List faces = new ArrayList<>();//In one Img; Frame frame = new Frame.Builder().setBitmap(My).build(); SparseArray sparseArray = faceDetector.detect(frame); for (int j = 0; j < sparseArray.size(); j++) { flag = false; Face face = sparseArray.valueAt(j); if (((int) face.getPosition().y + (int) face.getHeight()) > My.getHeight()) { int H = My.getHeight() - (int) face.getPosition().y; faceBitmap = Bitmap.createBitmap(My, (int) face.getPosition().x, (int) face.getPosition().y, (int) face.getWidth(), H); } else if (((int) face.getPosition().x + (int) face.getWidth()) > My.getWidth()) { int W = My.getWidth() - (int) face.getPosition().x; faceBitmap = Bitmap.createBitmap(My, (int) face.getPosition().x, (int) face.getPosition().y, W, (int) face.getHeight()); } else if ((((int) face.getPosition().x + (int) face.getWidth()) > My.getWidth()) && (((int) face.getPosition().y + (int) face.getHeight()) > My.getHeight())) { int H = My.getHeight() - (int) face.getPosition().y; int W = My.getWidth() - (int) face.getPosition().x; faceBitmap = Bitmap.createBitmap(My, (int) face.getPosition().x, (int) face.getPosition().y, W, H); } else { faceBitmap = Bitmap.createBitmap(My, (int) face.getPosition().x, (int) face.getPosition().y, (int) face.getWidth(), (int) face.getHeight()); } if (sparseArray.size() == 1) { GlobalVar.FinialFacesThatWillGoToDataBase.add(faceBitmap); flag = true; } else { faces.add(faceBitmap); } } if (!flag) { GlobalVar.ImgThatHaveMoreThanOneFace.add(My); GlobalVar.allFaces.add(faces); } } return null; } } private boolean CheckMatchObject() { location = Location.getText().toString(); AutoCompleteTextView V = ObjectF.getView().findViewById(R.id.ColorOfObject); EditText serialObject = ObjectF.getView().findViewById(R.id.Serial); EditText brandObject = ObjectF.getView().findViewById(R.id.brand); EditText textArea_informationObject = ObjectF.getView().findViewById(R.id.textArea_information); EditText TypeObject; ObjectColor = V.getText().toString(); Serial = serialObject.getText().toString(); brand = brandObject.getText().toString(); textArea_information = textArea_informationObject.getText().toString(); if (location.isEmpty()) { FancyToast.makeText(this, "Specify where you found this object", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show(); return false; } else if (Type.equals("Type")) { FancyToast.makeText(this, "You must Choose the Type!", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show(); return false; } else if (Type.equals("Others")) { TypeObject = ObjectF.getView().findViewById(R.id.Other); if (TypeObject.getText().toString().isEmpty()) { TypeObject.setError("Field can't be empty"); return false; } else { Type = TypeObject.getText().toString(); } } else if (brand.isEmpty()) { brandObject.setError("Field can't be empty"); return false; } else if (ObjectColor.isEmpty()) { V.setError("Field can't be empty"); return false; } else if (!listColor.contains(ObjectColor.trim())) { V.setError("Color isn't known!"); return false; } else if (textArea_information.isEmpty()) { textArea_informationObject.setError("Field can't be empty"); return false; } return true; } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PLACE_PICKER_REQUEST && resultCode == RESULT_OK) { Place place = PlacePicker.getPlace(data, this); StringBuilder stringBuilder = new StringBuilder(); Latitude = place.getLatLng().latitude; Longitude = place.getLatLng().longitude; isInternetAvailable Available = new isInternetAvailable(); Available.execute(); CurrentLocation Locate = new CurrentLocation(); Locate.execute(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == 12 && (grantResults.length > 0) && grantResults[0] == PackageManager.PERMISSION_GRANTED) { getCurrentLocation(); } else if (requestCode == 12 && (grantResults.length > 0) && grantResults[0] == PackageManager.PERMISSION_DENIED) { FancyToast.makeText(this, "Permission denied", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show(); } else if (requestCode == 11 && (grantResults.length > 0) && grantResults[0] == PackageManager.PERMISSION_DENIED) { FancyToast.makeText(this, "Permission denied", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show(); } } @SuppressLint("MissingPermission") private void getCurrentLocation() { LocationManager locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE); if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) ) { fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener() { @SuppressLint("MissingPermission") @Override public void onComplete(@NonNull Task task) { Location location = task.getResult(); if (location != null) { Longitude = location.getLongitude(); Latitude = location.getLatitude(); } else { @SuppressLint("RestrictedApi") LocationRequest locationRequest = new LocationRequest() .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) .setInterval(10000) .setFastestInterval(1000) .setNumUpdates(1); LocationCallback locationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { Location location1 = locationResult.getLastLocation(); Longitude = location1.getLongitude(); Latitude = location1.getLatitude(); } }; fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper()); } } }); } else { //when location servies is not enabled //open location setting startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } } class CurrentLocation extends AsyncTask { @Override protected void onPreExecute() { super.onPreExecute(); progressbar.setVisibility(View.VISIBLE); } @Override protected void onPostExecute(String Locate) { super.onPostExecute(Locate); if (Locate.isEmpty()) FancyToast.makeText(FoundObjectActivity.this, "An error has occurred , please try again", FancyToast.LENGTH_LONG, FancyToast.WARNING, false).show(); Location.setText(Locate); progressbar.setVisibility(View.GONE); } @Override protected String doInBackground(Void... voids) { Geocoder geocoder = new Geocoder(FoundObjectActivity.this, new Locale("en")); String Locate = ""; try { List

addresses = geocoder.getFromLocation(Latitude, Longitude, 1); String Country = addresses.get(0).getCountryName(); String CityG = addresses.get(0).getAdminArea(); int index = CityG.lastIndexOf(' '); if(index == -1) City = CityG; else City = CityG.substring(0, index); String area = addresses.get(0).getLocality(); Locate = area + "," + CityG + "," + Country + "."; } catch (IOException e) { Toast.makeText(FoundObjectActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show(); } return Locate; } } public boolean isNetworkAvailable(Context context) { ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo nInfo = cm.getActiveNetworkInfo(); boolean connected = nInfo != null && nInfo.isAvailable() && nInfo.isConnected(); return connected; } class isInternetAvailable extends AsyncTask { @Override protected void onPreExecute() { super.onPreExecute(); progressbar.setVisibility(View.VISIBLE); } @Override protected void onPostExecute(Boolean aBoolean) { super.onPostExecute(aBoolean); progressbar.setVisibility(View.GONE); if (!aBoolean) FancyToast.makeText(FoundObjectActivity.this, "No Internet Connection", FancyToast.LENGTH_LONG, FancyToast.WARNING, false).show(); } @Override protected Boolean doInBackground(Void... voids) { Boolean flag; try { String command = "ping -c 1 google.com"; flag = (Runtime.getRuntime().exec(command).waitFor() == 0); } catch (Exception e) { flag = false; } return flag; } } protected void inti() { DateFound = findViewById(R.id.DateFound); progressbar = findViewById(R.id.ProgressBar); Button foundLocatin = findViewById(R.id.FoundLocatin); Person = findViewById(R.id.PersonFound); Object = findViewById(R.id.ObjectFound); MatchFound = findViewById(R.id.MatchFound); Location = findViewById(R.id.Location); DateFound.setOnClickListener(this); foundLocatin.setOnClickListener(this); Person.setOnClickListener(this); Object.setOnClickListener(this); MatchFound.setOnClickListener(this); PersonF = new PersonFragment(); ObjectF = new ObjectFragment(); List = new prepareList(); listColor = List.prepareListColor(this); } @Override public void getType(String T) { Type = T; } @Override public void getImageCheck(Boolean check) { } @Override public void getBitmap_Image(Bitmap Bitmap_Image) { } @Override public void getBitmap_ImagePersonImages(List PImages) { Person_Images = PImages; Log.e("img", "getBitmap_ImagePersonImages: Hi " + Person_Images.size()); } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("year", year); outState.putInt("month", month); outState.putInt("Day", Day); outState.putBoolean("flagPerson", flagPerson); outState.putBoolean("flagObject", flagObject); } public void FoundItems() { String Datee = DateFound.getText().toString().trim(); ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class); Call call = apiInterface.storeFoundObj(User.getUser().getId(), Datee, City, Longitude , Latitude); call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { Log.d("e","responce="+response.body()); if (response.isSuccessful()) { try { Log.d("e","found="+response.body().toString()); JSONObject jsonObject = new JSONObject(response.body().toString()); String id = jsonObject.getString("id"); Toast.makeText(FoundObjectActivity.this, "Object is posted.", Toast.LENGTH_SHORT).show(); Call call2 = apiInterface.storeFoundItem(id, Type, Serial, brand, ObjectColor, textArea_information); call2.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { if (response.isSuccessful()) { Toast.makeText(FoundObjectActivity.this, "Item is posted.", Toast.LENGTH_SHORT).show(); User.getUser().getFounds().add(Integer.parseInt(id)); finish(); } else { Toast.makeText(FoundObjectActivity.this, "The item is not posted.", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call call, Throwable t) { Toast.makeText(FoundObjectActivity.this, t.getMessage(), Toast.LENGTH_LONG).show(); } }); } catch (JSONException e) { Toast.makeText(FoundObjectActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show(); } } else Toast.makeText(FoundObjectActivity.this, "Object is not posted.", Toast.LENGTH_SHORT).show(); } @Override public void onFailure(Call call, Throwable t) { Toast.makeText(FoundObjectActivity.this, t.getMessage(), Toast.LENGTH_LONG).show(); } }); } public Uri getImageUri(Bitmap bitmap_Image) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bitmap_Image.compress(Bitmap.CompressFormat.JPEG, 100, bytes); String path = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap_Image, (System.currentTimeMillis()%1000)+"", null); return Uri.parse(path); } private String getRealPathFromURI(Uri imageUri) { String[] proj = {MediaStore.Images.Media.DATA}; CursorLoader loader = new CursorLoader(this, imageUri, proj, null, null, null); Cursor cursor = loader.loadInBackground(); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String result = cursor.getString(column_index); cursor.close(); return result; } public void FoundPerson() { String Datee = DateFound.getText().toString().trim(); ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class); Uri imageURI = getImageUri(GlobalVar.FinialFacesThatWillGoToDataBase.get(0)); File file = new File(getRealPathFromURI(imageURI)); RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file); MultipartBody.Part Pimage = MultipartBody.Part.createFormData("image", file.getName(), requestBody); Call call = apiInterface.storeFoundPerson(User.getUser().getId(), Datee, City, Longitude , Latitude, PName, Pimage); call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { if(response.isSuccessful()) { FancyToast.makeText(FoundObjectActivity.this, "The data has been saved successfully", FancyToast.LENGTH_LONG, FancyToast.SUCCESS, false).show(); try { String id = new JSONObject(response.body().toString()).getString("id"); } catch (JSONException e) { Log.e("TAG", "onResponse: "+e.getMessage()); } finish(); }else Toast.makeText(FoundObjectActivity.this, "The object is not posted.", Toast.LENGTH_SHORT).show(); } @Override public void onFailure(Call call, Throwable t) { Toast.makeText(FoundObjectActivity.this, t.getMessage(), Toast.LENGTH_LONG).show(); } }); } public void getItems(FoundItem item, Context context) { ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(context).getNGROKLink()).create(ApiInterface.class); Call> call = apiInterface.getLItem(item.getType()); Log.d("tes=",Type); GlobalVar.type=Type; call.enqueue(new Callback>() { @Override public void onResponse(Call> call, Response> response) { GlobalVar.lostList = new ArrayList<>(); GlobalVar.lostList = response.body(); GlobalVar.percentList = new ArrayList<>(); if (response.body()!=null&&GlobalVar.lostList.size()!=0) { storeCandidatesNotifictation() ; for (int i = 0; i < GlobalVar.lostList.size(); i++) { GlobalVar.percentList.add(MatchItems(item, GlobalVar.lostList.get(i))); } } else Toast.makeText(context, "There is no items can be candidates !", Toast.LENGTH_SHORT).show(); } @Override public void onFailure(Call> call, Throwable t) { Toast.makeText(FoundObjectActivity.this, t.getMessage(), Toast.LENGTH_LONG).show(); } }); } public String MatchItems(FoundItem item1, LostItem item2) { int percentage =20; if (item1.getBrand().equals(item2.getBrand())) percentage += 20; if (item1.getColor().equals(item2.getColor())) percentage +=20; if (item1.getSerial_number().equals(item2.getSerial_number())) { return "100%"; } String p=percentage+"%"; return p; } public void storeCandidatesNotifictation(){ ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class); Call call = apiInterface.storeNotification(User.getUser().getId(),"Candidate Items","There are Candidates founded",3); call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { if (response.isSuccessful()) { Toast.makeText(FoundObjectActivity.this, "Notification is posted.", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(FoundObjectActivity.this, "The Notification is not posted.", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call call, Throwable t) { Toast.makeText(FoundObjectActivity.this, t.getMessage(), Toast.LENGTH_LONG).show(); } }); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/lostFoundObject/LostObjectDetailsActivity.java ================================================ package com.helloworld.goodpoint.ui.lostFoundObject; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.util.SparseArray; import android.view.View; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.loader.content.CursorLoader; import com.google.android.gms.vision.Frame; import com.google.android.gms.vision.face.Face; import com.google.android.gms.vision.face.FaceDetector; import com.google.gson.JsonObject; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.pojo.LostItem; import com.helloworld.goodpoint.pojo.LostPerson; import com.helloworld.goodpoint.pojo.User; import com.helloworld.goodpoint.retrofit.ApiClient; import com.helloworld.goodpoint.retrofit.ApiInterface; import com.helloworld.goodpoint.ui.Alert; import com.helloworld.goodpoint.ui.GlobalVar; import com.helloworld.goodpoint.ui.PrefManager; import com.helloworld.goodpoint.ui.prepareList; import com.shashank.sony.fancytoastlib.FancyToast; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class LostObjectDetailsActivity extends AppCompatActivity implements View.OnClickListener, objectDataType { private TextView DateT; private Button Person, Object, Match; private Fragment PersonF, ObjectF; private DatePickerDialog.OnDateSetListener DateSet; private AutoCompleteTextView autoCom; private int year, month, Day; private prepareList pList; private List list, listColor; private String City, ObjectColor, Serial, brand, textArea_information, Type; private String PName; private Bitmap Bitmap_Image; Uri imageURI; private FaceDetector faceDetector; private List Person_Images; private boolean flagPerson, flagObject, CheckImageObeject; List Llist; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lost_object_details); inti(); Calendar cal = Calendar.getInstance();//To get today's date inti(); if (savedInstanceState != null) { year = savedInstanceState.getInt("year"); month = savedInstanceState.getInt("month"); Day = savedInstanceState.getInt("Day"); flagPerson = savedInstanceState.getBoolean("flagPerson"); flagObject = savedInstanceState.getBoolean("flagObject"); if (flagPerson) { Person.setTextColor(0xFFF38E3A); Object.setTextColor(Color.BLACK); } else if (flagObject) { Object.setTextColor(0xFFF38E3A); Person.setTextColor(Color.BLACK); } } else { year = cal.get(Calendar.YEAR); month = cal.get(Calendar.MONTH); Day = cal.get(Calendar.DAY_OF_MONTH); } //String todayDate = year + "/" + (month + 1) + "/" + Day; String todayDate = year + "-" + (month + 1) + "-" + Day; DateT.setText(todayDate); DateSet = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int y, int m, int d) { m++; if (y > year || (m - 1 > month && y >= year) || (d > Day && m - 1 >= month && y >= year)) { FancyToast.makeText(LostObjectDetailsActivity.this, "Invalid date", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show(); //String todayDate = year + "/" + (month + 1) + "/" + Day; String todayDate = year + "-" + (month + 1) + "-" + Day; DateT.setText(todayDate); } else { year = y; month = m - 1; Day = d; //String Date = y + "/" + m + "/" + d; String Date = y + "-" + m + "-" + d; DateT.setText(Date); } } }; } @Override public void onClick(View view) { FragmentManager FM = getFragmentManager(); FragmentTransaction FT = FM.beginTransaction(); switch (view.getId()) { case R.id.Person: FT.replace(R.id.FragmentID, PersonF, null); Person.setTextColor(0xFFF38E3A); Object.setTextColor(Color.BLACK); FT.commit(); flagPerson = true; flagObject = false; break; case R.id.Object: FT.replace(R.id.FragmentID, ObjectF, "object"); Object.setTextColor(0xFFF38E3A); Person.setTextColor(Color.BLACK); FT.commit(); flagObject = true; flagPerson = false; break; case R.id.Date: DatePickerDialog dialog = new DatePickerDialog( LostObjectDetailsActivity.this, android.R.style.Theme_Holo_Light_Dialog_MinWidth, DateSet, year, month, Day ); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.show(); break; case R.id.Match: if (!flagObject && !flagPerson) { FancyToast.makeText(this, "Specify the type of the missing object", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show(); } else if (flagObject && CheckMatchObject()) { LostItems(); FancyToast.makeText(this, "The data has been saved successfully", FancyToast.LENGTH_LONG, FancyToast.SUCCESS, false).show(); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //finish(); } else if (flagPerson && CheckMatchPerson()) { faceDetector = new FaceDetector.Builder(this) .setTrackingEnabled(false) .setLandmarkType(FaceDetector.ALL_LANDMARKS) .setMode(FaceDetector.FAST_MODE).build(); if (!faceDetector.isOperational()) { Toast.makeText(this, "Face Detection can't be setup", Toast.LENGTH_SHORT).show(); } checkFaces N = new checkFaces(this); N.execute(); } break; } } private boolean CheckMatchPerson() { EditText PersonName = PersonF.getView().findViewById(R.id.PersonName); PName = PersonName.getText().toString(); City = autoCom.getText().toString(); if (City.isEmpty()) { autoCom.setError("Field can't be empty"); return false; } else if (!list.contains(City.trim())) { autoCom.setError("Please Enter a valid city!"); return false; } if (PName.isEmpty()) { PersonName.setError("Field can't be empty"); return false; } else if (Person_Images.size() == 0) { FancyToast.makeText(this, "You must put at least one picture!", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show(); return false; } return true; } private boolean CheckMatchObject() { AutoCompleteTextView V = ObjectF.getView().findViewById(R.id.ColorOfObject); EditText serialObject = ObjectF.getView().findViewById(R.id.Serial); EditText brandObject = ObjectF.getView().findViewById(R.id.brand); EditText textArea_informationObject = ObjectF.getView().findViewById(R.id.textArea_information); EditText TypeObject; City = autoCom.getText().toString(); ObjectColor = V.getText().toString(); Serial = serialObject.getText().toString(); brand = brandObject.getText().toString(); textArea_information = textArea_informationObject.getText().toString(); if (City.isEmpty()) { autoCom.setError("Field can't be empty"); return false; } else if (!list.contains(City.trim())) { autoCom.setError("Please Enter a valid city!"); return false; } else if (Type.equals("Type")) { FancyToast.makeText(this, "You must Choose the Type!", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show(); return false; } else if (Type.equals("Others")) { TypeObject = ObjectF.getView().findViewById(R.id.Other); if (TypeObject.getText().toString().isEmpty()) { TypeObject.setError("Field can't be empty"); return false; } else { Type = TypeObject.getText().toString(); } } else if (brand.isEmpty()) { brandObject.setError("Field can't be empty"); return false; } else if (ObjectColor.isEmpty()) { V.setError("Field can't be empty"); return false; } else if (!listColor.contains(ObjectColor.trim())) { V.setError("Color isn't known!"); return false; } else if (CheckImageObeject && Bitmap_Image == null) { FancyToast.makeText(this, "You should put the image to the item!", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show(); return false; } else if (textArea_information.isEmpty()) { textArea_informationObject.setError("Field can't be empty"); return false; } return true; } class checkFaces extends AsyncTask { AlertDialog.Builder builder; AlertDialog dialog; Context context; private checkFaces(Context context) { this.context = context.getApplicationContext(); builder = new AlertDialog.Builder(LostObjectDetailsActivity.this); } @Override protected void onPreExecute() { super.onPreExecute(); builder.setCancelable(false); View view = getLayoutInflater().inflate(R.layout.progress_bar_alert, null); builder.setView(view); dialog = builder.create(); dialog.show(); } @Override protected void onPostExecute(Void a) { super.onPostExecute(a); if (GlobalVar.allFaces.size() > 0) { LostPerson.getLostPerson().setName(PName); LostPerson.getLostPerson().setDate(DateT.getText().toString().trim()); LostPerson.getLostPerson().setCity(City); GlobalVar.flag=2; startActivity(new Intent(LostObjectDetailsActivity.this, Alert.class)); finish(); } else { LostPerson(); } dialog.dismiss(); } @Override protected Void doInBackground(Void... voids) { GlobalVar.ImgThatHaveMoreThanOneFace.clear(); GlobalVar.FinialFacesThatWillGoToDataBase.clear(); GlobalVar.allFaces.clear(); boolean flag = false; for (int i = 0; i < Person_Images.size(); i++) { Bitmap My = Person_Images.get(i); Bitmap faceBitmap; List faces = new ArrayList<>();//In one Img; Frame frame = new Frame.Builder().setBitmap(My).build(); SparseArray sparseArray = faceDetector.detect(frame); for (int j = 0; j < sparseArray.size(); j++) { flag = false; Face face = sparseArray.valueAt(j); if (((int) face.getPosition().y + (int) face.getHeight()) > My.getHeight()) { int H = My.getHeight() - (int) face.getPosition().y; faceBitmap = Bitmap.createBitmap(My, (int) face.getPosition().x, (int) face.getPosition().y, (int) face.getWidth(), H); } else if (((int) face.getPosition().x + (int) face.getWidth()) > My.getWidth()) { int W = My.getWidth() - (int) face.getPosition().x; faceBitmap = Bitmap.createBitmap(My, (int) face.getPosition().x, (int) face.getPosition().y, W, (int) face.getHeight()); } else if ((((int) face.getPosition().x + (int) face.getWidth()) > My.getWidth()) && (((int) face.getPosition().y + (int) face.getHeight()) > My.getHeight())) { int H = My.getHeight() - (int) face.getPosition().y; int W = My.getWidth() - (int) face.getPosition().x; faceBitmap = Bitmap.createBitmap(My, (int) face.getPosition().x, (int) face.getPosition().y, W, H); } else { faceBitmap = Bitmap.createBitmap(My, (int) face.getPosition().x, (int) face.getPosition().y, (int) face.getWidth(), (int) face.getHeight()); } if (sparseArray.size() == 1) { GlobalVar.FinialFacesThatWillGoToDataBase.add(faceBitmap);// flag = true; } else { faces.add(faceBitmap); } } if (!flag) { GlobalVar.ImgThatHaveMoreThanOneFace.add(My); GlobalVar.allFaces.add(faces); } } return null; } } @Override public void getType(String T) { Type = T; } @Override public void getImageCheck(Boolean Check) { CheckImageObeject = Check; } @Override public void getBitmap_Image(Bitmap BImage) { Bitmap_Image = BImage; } @Override public void getBitmap_ImagePersonImages(List PImages) { Person_Images = PImages; } protected void inti() { DateT = findViewById(R.id.Date); autoCom = findViewById(R.id.auto); Person = findViewById(R.id.Person); Object = findViewById(R.id.Object); Match = findViewById(R.id.Match); Person.setOnClickListener(this); Object.setOnClickListener(this); Match.setOnClickListener(this); DateT.setOnClickListener(this); PersonF = new PersonFragment(); ObjectF = new ObjectFragment(); pList = new prepareList(); list = pList.prepareList(this); listColor = pList.prepareListColor(this); ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list); autoCom.setThreshold(1);//start working from first char autoCom.setAdapter(adapter); flagPerson = false; flagObject = false; } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("year", year); outState.putInt("month", month); outState.putInt("Day", Day); outState.putBoolean("flagPerson", flagPerson); outState.putBoolean("flagObject", flagObject); } public Uri getImageUri(Bitmap bitmap_Image) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bitmap_Image.compress(Bitmap.CompressFormat.JPEG, 100, bytes); String path = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap_Image, (System.currentTimeMillis()%1000)+"", null); return Uri.parse(path); } private String getRealPathFromURI(Uri imageUri) { String[] proj = {MediaStore.Images.Media.DATA}; CursorLoader loader = new CursorLoader(this, imageUri, proj, null, null, null); Cursor cursor = loader.loadInBackground(); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String result = cursor.getString(column_index); cursor.close(); return result; } public void LostItems() { String Datee = DateT.getText().toString().trim(); ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class); Call call = apiInterface.storeLostObj(User.getUser().getId(), Datee, City); call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { if (response.isSuccessful()) { try { JSONObject jsonObject = new JSONObject(response.body().toString()); String id = jsonObject.getString("id"); Toast.makeText(LostObjectDetailsActivity.this, "Object is posted.", Toast.LENGTH_SHORT).show(); Call call2; if (Bitmap_Image != null) { imageURI = getImageUri(Bitmap_Image); File file = new File(getRealPathFromURI(imageURI)); RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/from-data"), file); MultipartBody.Part image = MultipartBody.Part.createFormData("image", file.getName(), requestBody); call2 = apiInterface.storeLostItem(id, Type, Serial, brand, ObjectColor, textArea_information, image); } else call2 = apiInterface.storeLostItem(id, Type, Serial, brand, ObjectColor, textArea_information); call2.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { Log.d("e","responce="+response.body()); if (response.isSuccessful()) { Toast.makeText(LostObjectDetailsActivity.this, "Item is posted.", Toast.LENGTH_SHORT).show(); User.getUser().getLosts().add(Integer.parseInt(id)); finish(); } else { Toast.makeText(LostObjectDetailsActivity.this, "The item is not posted.", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call call, Throwable t) { Toast.makeText(LostObjectDetailsActivity.this, t.getMessage(), Toast.LENGTH_LONG).show(); } }); } catch (JSONException e) { Toast.makeText(LostObjectDetailsActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show(); } } else Toast.makeText(LostObjectDetailsActivity.this, "The object is not posted.", Toast.LENGTH_SHORT).show(); } @Override public void onFailure(Call call, Throwable t) { Toast.makeText(LostObjectDetailsActivity.this, t.getMessage(), Toast.LENGTH_LONG).show(); } }); } public void LostPerson() { String Datee = DateT.getText().toString().trim(); ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class); imageURI = getImageUri(GlobalVar.FinialFacesThatWillGoToDataBase.get(0)); File file = new File(getRealPathFromURI(imageURI)); RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file); MultipartBody.Part Pimage = MultipartBody.Part.createFormData("image", file.getName(), requestBody); //MultipartBody.Part image = MultipartBody.Part.createFormData("images", file.getName(), requestBody); //Pimages.add(image); Call call = apiInterface.storeLostPerson(Datee,City,User.getUser().getId(),PName,Pimage); call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { if(response.isSuccessful()) { FancyToast.makeText(LostObjectDetailsActivity.this, "The data has been saved successfully", FancyToast.LENGTH_LONG, FancyToast.SUCCESS, false).show(); try { String id = new JSONObject(response.body().toString()).getString("id"); } catch (JSONException e) { Log.e("TAG", "onResponse: "+e.getMessage()); } finish(); }else { try { Log.e("onResponse: ", response.errorBody().string()); } catch (IOException e) { Log.e("onResponse: ", e.getMessage()); } } } @Override public void onFailure(Call call, Throwable t) { Toast.makeText(LostObjectDetailsActivity.this, t.getMessage(), Toast.LENGTH_LONG).show(); Log.e("onFailure: ", t.getMessage()); } }); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/lostFoundObject/ObjectFragment.java ================================================ package com.helloworld.goodpoint.ui.lostFoundObject; import android.Manifest; import android.app.Fragment; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.CheckBox; import android.widget.ImageButton; import android.widget.Spinner; import android.widget.Toast; import androidx.core.app.ActivityCompat; import com.google.android.material.textfield.TextInputLayout; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.ui.prepareList; import com.shashank.sony.fancytoastlib.FancyToast; import java.io.IOException; import java.util.List; import static android.app.Activity.RESULT_OK; public class ObjectFragment extends Fragment implements AdapterView.OnItemSelectedListener, View.OnClickListener { private Spinner spinner; public List list; private AutoCompleteTextView autoCom; private TextInputLayout other; private ImageButton objectImageView; private Bitmap Bitmap_Image ; private CheckBox checkIcon; private Uri imageUri; private prepareList List; private String Type ; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getActivity() instanceof LostObjectDetailsActivity) { if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 11); } } List= new prepareList(); list = List.prepareListColor(getActivity().getApplicationContext()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_object, container, false); spinner = v.findViewById(R.id.spinner); autoCom = v.findViewById(R.id.ColorOfObject); other = v.findViewById(R.id.other); checkIcon = v.findViewById(R.id.checkIcon); objectImageView = v.findViewById(R.id.objectImageView); objectImageView.setOnClickListener(this); if (getActivity() instanceof LostObjectDetailsActivity) { checkIcon.setVisibility(View.VISIBLE); checkIcon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //is chkIos checked? if (((CheckBox) v).isChecked()) { objectImageView.setVisibility(View.VISIBLE); ((objectDataType)getActivity()).getImageCheck(true); } else { objectImageView.setVisibility(View.GONE); ((objectDataType)getActivity()).getImageCheck(false); } } }); } ArrayAdapter adapter = new ArrayAdapter<>( getActivity().getApplicationContext(), R.layout.spinner_item, getResources().getStringArray(R.array.Types)); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(this); adapter = new ArrayAdapter<>(getActivity().getApplicationContext(),R.layout.spinner_item , list); autoCom.setThreshold(1);//start working from first char autoCom.setAdapter(adapter); // Inflate the layout for this fragment return v; } @Override public void onClick(View v) { if(v == objectImageView) { if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 11); } else { Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI); gallery.setType("image/*"); if (gallery.resolveActivity(getActivity().getPackageManager()) != null) { startActivityForResult(gallery, 1); } else FancyToast.makeText(getActivity().getApplicationContext(),"Error",FancyToast.LENGTH_LONG, FancyToast.ERROR,false).show(); } } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK && data != null) { if(requestCode == 1) { imageUri = data.getData(); try { Bitmap_Image = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), imageUri); ((objectDataType)getActivity()).getBitmap_Image( Bitmap_Image); } catch (IOException e) { FancyToast.makeText(getActivity().getApplicationContext(),"Error",FancyToast.LENGTH_LONG, FancyToast.ERROR,false).show(); e.printStackTrace(); } objectImageView.setImageURI(imageUri); } } } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { int posit = parent.getSelectedItemPosition(); Type = parent.getItemAtPosition(position).toString(); ((objectDataType)getActivity()).getType(Type); if(posit == 9) { other.setVisibility(View.VISIBLE); } else { other.setVisibility(View.GONE); } } @Override public void onNothingSelected(AdapterView parent) { } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/lostFoundObject/PersonFragment.java ================================================ package com.helloworld.goodpoint.ui.lostFoundObject; import android.Manifest; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.Fragment; import android.content.ClipData; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.util.SparseArray; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.Toast; import androidx.appcompat.widget.PopupMenu; import androidx.core.app.ActivityCompat; import com.google.android.gms.vision.Frame; import com.google.android.gms.vision.face.Face; import com.google.android.gms.vision.face.FaceDetector; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.detection.DetectorActivity; import com.helloworld.goodpoint.ui.GlobalVar; import com.shashank.sony.fancytoastlib.FancyToast; import java.util.ArrayList; import java.util.List; import static android.app.Activity.RESULT_OK; public class PersonFragment extends Fragment implements View.OnClickListener { private ImageButton imageView; private ImageView imageView2; private List bitmap = new ArrayList<>(); private LinearLayout linearLayout,ADDP; private LayoutInflater inflater2; private Uri photoFromGallery; private View rootView; private Button Close,add_new__photo; private ProgressBar CheckImages; private int nmberOfImageSelected; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},11); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ((objectDataType)getActivity()).getBitmap_ImagePersonImages(bitmap); rootView = inflater.inflate(R.layout.fragment_person, container, false); imageView = rootView.findViewById(R.id.imageView); ADDP = rootView.findViewById(R.id.ADDP); add_new__photo= rootView.findViewById(R.id.add_new__photo); CheckImages = rootView.findViewById(R.id.CheckImages); CheckImages.setVisibility(View.GONE); linearLayout = (LinearLayout) rootView.findViewById(R.id.Gallery2); inflater2 = LayoutInflater.from(getActivity()); add_new__photo.setOnClickListener(this); return rootView; } @Override public void onClick(View view) { if(view == add_new__photo) { if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 11); } else{ if (getActivity() instanceof FoundObjectActivity) { PopupMenu popupMenu = new PopupMenu(getActivity(), view); popupMenu.getMenuInflater().inflate(R.menu.choose_photo, popupMenu.getMenu()); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.TakePhoto: Intent i = new Intent(getActivity().getApplicationContext(), DetectorActivity.class); startActivityForResult(i,10); /* Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (i.resolveActivity(getActivity().getPackageManager()) != null) { startActivityForResult(i, 10); } else FancyToast.makeText(getActivity().getApplicationContext(),"Error",FancyToast.LENGTH_LONG, FancyToast.ERROR,false).show();*/ break; case R.id.Gallery: Intent pickPhoto = new Intent(Intent.ACTION_GET_CONTENT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); pickPhoto.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); pickPhoto.setType("image/*");//accept any type of images if (pickPhoto.resolveActivity(getActivity().getPackageManager()) != null) { startActivityForResult(pickPhoto, 1); } else FancyToast.makeText(getActivity().getApplicationContext(), "Error", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show(); break; } return true; } }); popupMenu.show(); } else if (getActivity() instanceof LostObjectDetailsActivity) { Intent pickPhoto = new Intent(Intent.ACTION_GET_CONTENT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); pickPhoto.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); pickPhoto.setType("image/*");//accept any type of images if (pickPhoto.resolveActivity(getActivity().getPackageManager()) != null) { startActivityForResult(pickPhoto, 1); } else FancyToast.makeText(getActivity().getApplicationContext(),"Error",FancyToast.LENGTH_LONG, FancyToast.ERROR,false).show(); } } } } int NumOfImgSelected ; int BitMapSize = bitmap.size(); @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); BitMapSize = bitmap.size(); ADDP.setVisibility(View.VISIBLE); if(resultCode==RESULT_OK&&data!=null) { switch(requestCode) { case 10: { if (bitmap.size() >= 10) { FancyToast.makeText(getActivity().getApplicationContext(), "You cannot choose more than 10 images", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show(); } else { if(GlobalVar.realcameraImage != null) { bitmap.add(GlobalVar.realcameraImage) ; NumOfImgSelected = 1;} } break; } case 1: try { ClipData clipData = data.getClipData(); if(clipData != null) { NumOfImgSelected = clipData.getItemCount(); for (int i = 0; i < clipData.getItemCount(); i++) { photoFromGallery = clipData.getItemAt(i).getUri(); if (bitmap.size() >= 10) { Toast toast = FancyToast.makeText(getActivity().getApplicationContext(), "You cannot choose more than 10 images", FancyToast.LENGTH_LONG, FancyToast.ERROR, false); toast.setGravity(Gravity.BOTTOM, 0, 0); toast.show(); break; } bitmap.add(MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), photoFromGallery)); } } else{ NumOfImgSelected = 1; photoFromGallery = data.getData(); if(bitmap.size()>=10) { Toast toast = FancyToast.makeText(getActivity().getApplicationContext(),"You cannot choose more than 10 images",FancyToast.LENGTH_LONG, FancyToast.ERROR,false); toast.setGravity(Gravity.BOTTOM,0,0); toast.show(); } else { bitmap.add(MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), photoFromGallery)); } } } catch (Exception e) { e.printStackTrace(); } break; } ((objectDataType)getActivity()).getBitmap_ImagePersonImages(bitmap); if(BitMapSize != bitmap.size()) { checkIfAllImagesContainFacesOrNot N = new checkIfAllImagesContainFacesOrNot(); N.execute(bitmap); } } } class checkIfAllImagesContainFacesOrNot extends AsyncTask,Void, List> { @Override protected void onPreExecute() { super.onPreExecute(); CheckImages.setVisibility(View.VISIBLE); add_new__photo.setVisibility(View.GONE); } @Override protected void onPostExecute(List ImgNotHaveFaces) { super.onPostExecute(ImgNotHaveFaces); CheckImages.setVisibility(View.GONE); add_new__photo.setVisibility(View.VISIBLE); if(ImgNotHaveFaces.size()>0) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setCancelable(false); @SuppressLint({"NewApi", "LocalSuppress"}) View view = getLayoutInflater().inflate(R.layout.images_be_removed, null); LinearLayout RemovedImg = view.findViewById(R.id.RemovedImg); if (ImgNotHaveFaces.size() > 1) builder.setMessage("These " + ImgNotHaveFaces.size() + " images do not contain any faces so they will be removed"); else builder.setMessage("This image do not contain any faces so it will be removed"); for (int i = 0; i < ImgNotHaveFaces.size(); i++) { @SuppressLint({"NewApi", "LocalSuppress"}) View view2 = getLayoutInflater().inflate(R.layout.images, null); (view2.findViewById(R.id.imageView2)).setVisibility(View.GONE); (view2.findViewById(R.id.Close)).setVisibility(View.GONE); ImageView imageView = view2.findViewById(R.id.faces); imageView.setImageBitmap(ImgNotHaveFaces.get(i)); RemovedImg.addView(view2); } builder.setView(view).setNegativeButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Log.e("img"," Finished I Now Have "+ImgNotHaveFaces.size() +" img "); for (int i = linearLayout.getChildCount(); i < bitmap.size(); i++) { View view = inflater2.inflate(R.layout.images, linearLayout, false); imageView2 = view.findViewById(R.id.imageView2); Close = (Button)view.findViewById(R.id.Close); Close.setBackgroundColor(0x80F38E3A); imageView2.setImageBitmap(bitmap.get(i)); linearLayout.addView(view); } setOnClickListeners(); ImgNotHaveFaces.clear(); } }); AlertDialog dialog = builder.create(); dialog.show(); } else { for (int i = linearLayout.getChildCount(); i < bitmap.size(); i++) { View view = inflater2.inflate(R.layout.images, linearLayout, false); imageView2 = view.findViewById(R.id.imageView2); Close = (Button)view.findViewById(R.id.Close); Close.setBackgroundColor(0x80F38E3A); imageView2.setImageBitmap(bitmap.get(i)); linearLayout.addView(view); } setOnClickListeners(); } } @Override protected List doInBackground(List... bitmap) { List ImgNotHaveFaces = new ArrayList<>(); int counter = NumOfImgSelected; int index = bitmap[0].size(); while(counter > 0 && index > 0) { Bitmap My = bitmap[0].get(--index); FaceDetector faceDetector = new FaceDetector.Builder(getActivity()) .setTrackingEnabled(false) .setLandmarkType(FaceDetector.ALL_LANDMARKS) .setMode(FaceDetector.FAST_MODE).build(); if (!faceDetector.isOperational()) { Toast.makeText(getActivity().getApplicationContext(), "Face Detection can't be setup", Toast.LENGTH_SHORT).show(); } else { Frame frame = new Frame.Builder().setBitmap(My).build(); SparseArray sparseArray = faceDetector.detect(frame); Log.e("Camera", "doInBackground22: Esraa " + sparseArray.size()); if(sparseArray.size()==0) { ImgNotHaveFaces.add(bitmap[0].get(index)); bitmap[0].remove(index); Log.e("img", "I removed Image number " + (index) ); } } counter--; } ((objectDataType)getActivity()).getBitmap_ImagePersonImages(bitmap[0]); return ImgNotHaveFaces; } } private void setOnClickListeners() { for (int index = 0; index < linearLayout.getChildCount(); index++) { final int finalIndex1 = index; View view = linearLayout.getChildAt(index); Close = view.findViewById(R.id.Close); imageView2 = view.findViewById(R.id.imageView2); Close.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { bitmap.remove(finalIndex1); ((objectDataType)getActivity()).getBitmap_ImagePersonImages(bitmap); if(nmberOfImageSelected == finalIndex1) { imageView.setVisibility(View.GONE); imageView.setImageDrawable(getResources().getDrawable(R.drawable.ic_baseline_gallery_24)); } linearLayout.removeViewAt(finalIndex1); setOnClickListeners(); } }); imageView2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { imageView2 = view.findViewById(R.id.imageView2); imageView.setVisibility(View.VISIBLE); imageView.setImageDrawable(imageView2.getDrawable()); nmberOfImageSelected = finalIndex1; } }); } } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/lostFoundObject/objectDataType.java ================================================ package com.helloworld.goodpoint.ui.lostFoundObject; import android.graphics.Bitmap; import android.net.Uri; import java.util.List; public interface objectDataType { public void getType(String Type); public void getImageCheck(Boolean check); public void getBitmap_Image(Bitmap Bitmap_Image); public void getBitmap_ImagePersonImages(List Bitmap_Images); } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/myService/MyService.java ================================================ package com.helloworld.goodpoint.ui.myService; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class MyService extends Service { public MyService() { } @Override public void onCreate() { super.onCreate(); Log.d("msg","Service Started"); try { Thread.sleep(5000); } catch (Exception e) { e.printStackTrace(); } stopSelf(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); Log.d("msg","Service Destroyed"); } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/myService/NotificationBroadcast.java ================================================ package com.helloworld.goodpoint.ui.myService; import android.annotation.SuppressLint; import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.media.AudioAttributes; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.os.PowerManager; import android.util.Log; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import com.google.gson.JsonObject; import com.helloworld.goodpoint.App; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.pojo.NotificationItem; import com.helloworld.goodpoint.pojo.User; import com.helloworld.goodpoint.retrofit.ApiClient; import com.helloworld.goodpoint.retrofit.ApiInterface; import com.helloworld.goodpoint.retrofit.Decode; import com.helloworld.goodpoint.ui.NotificationActivity; import com.helloworld.goodpoint.ui.PrefManager; import org.json.JSONObject; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class NotificationBroadcast extends BroadcastReceiver { String user_id; //@SuppressLint("UnsafeProtectedBroadcastReceiver") @Override public void onReceive(Context context, Intent intent) { String refresh = new PrefManager(context).isLoginned(); Log.e("TAG", "onReceive: Token: "+refresh); newNotification(context); if(refresh.isEmpty()) { if(User.getUser() != null && User.getUser().getId() != null && !User.getUser().getId().isEmpty()) user_id = User.getUser().getId(); else return; }else{ try { String bodyToken = Decode.decoded(refresh); JSONObject jsonObject = new JSONObject(bodyToken); user_id = jsonObject.getString("user_id"); } catch (Exception e) { Log.e("TAG", "onReceive: "+e.getMessage()); } } ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(context).getNGROKLink()).create(ApiInterface.class); Call> call = apiInterface.getNewNotification(user_id); call.enqueue(new Callback>() { @Override public void onResponse(Call> call, Response> response) { if(response.body()==null || response.body().isEmpty()) return; for(NotificationItem item: response.body()){ showNotification(context,item.getId(),item.getTitle(),item.getDescription(),item.getType()); Call sentCall = apiInterface.updateSent(item.getId(),true); sentCall.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { Log.e("TAG", "onResponse: Success"); } @Override public void onFailure(Call call, Throwable t) { Log.e("TAG", "onFailure: "+t.getMessage()); } }); } } @Override public void onFailure(Call> call, Throwable t) { Log.e("TAG", "onFailure: "+t.getMessage()); } }); } private void newNotification(Context context) { Intent i = new Intent(App.getInstance(),NotificationBroadcast.class); i.setAction("com.helloworld.goodpoint.ui.myService.NotificationBroadcast"); PendingIntent pendingIntent = PendingIntent.getBroadcast(App.getInstance(),10,i,PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmManager.setAlarmClock(new AlarmManager.AlarmClockInfo(System.currentTimeMillis()+20000,pendingIntent),pendingIntent); } private void createNotification(Context context, String id, String title, String description, int type) { Log.d("Good Point Service", "createNotification: "+id); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Intent notifyIntent = new Intent(context, NotificationActivity.class); PendingIntent pintent = PendingIntent.getActivity(context,type,notifyIntent,PendingIntent.FLAG_UPDATE_CURRENT); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel nc = new NotificationChannel("Good Point",title, NotificationManager.IMPORTANCE_HIGH); nc.setDescription(description); nm.createNotificationChannel(nc); NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"Good Point"); builder.setContentTitle(title).setContentText(description); builder.setSmallIcon(R.drawable.application_icon2).setStyle(new NotificationCompat.BigTextStyle().bigText(description)); builder.setContentIntent(pintent).setAutoCancel(true); NotificationManagerCompat nmc = NotificationManagerCompat.from(context); nmc.notify(Integer.parseInt(id),builder.build()); }else{ Notification.Builder builder = new Notification.Builder(context); builder.setContentTitle(title).setContentText(description); builder.setSmallIcon(R.drawable.application_icon2).setStyle(new Notification.BigTextStyle().bigText(description)); builder.setContentIntent(pintent); nm.notify(Integer.parseInt(id),builder.build()); } } private void showNotification(Context context, String id, String title, String description, int type) { Log.e("TAG", "showNotification: "+id); Log.e("TAG", "showNotification: "+title); Log.e("TAG", "showNotification: "+description); Log.e("TAG", "showNotification: "+type); PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); @SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG"); wl.acquire(10); Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); //Uri ringtoneUri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.consequence); Ringtone r = RingtoneManager.getRingtone(context, ringtoneUri); r.play(); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, "Good Point"); NotificationManager mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); context.grantUriPermission("com.android.systemui", ringtoneUri, Intent.FLAG_GRANT_READ_URI_PERMISSION); Intent notifyIntent = new Intent(context, NotificationActivity.class); notifyIntent.putExtra("ID",id); PendingIntent pintent = PendingIntent.getActivity(context,type,notifyIntent,PendingIntent.FLAG_UPDATE_CURRENT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { AudioAttributes att = new AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_NOTIFICATION) .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) .build(); NotificationChannel mChannel = new NotificationChannel("Good Point", title, NotificationManager.IMPORTANCE_HIGH); mChannel.setDescription(description); mChannel.enableLights(true); mChannel.enableVibration(true); mChannel.setSound(ringtoneUri, att); mChannel.setBypassDnd(true); mChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC); mChannel.setShowBadge(true); if (mNotifyManager != null) { mNotifyManager.createNotificationChannel(mChannel); } notificationBuilder .setSmallIcon(R.drawable.application_icon2) .setPriority(NotificationCompat.PRIORITY_MAX) .setCategory(NotificationCompat.CATEGORY_EVENT) .setStyle(new NotificationCompat.BigTextStyle().bigText(description)) .setSound(ringtoneUri) .setContentTitle(title) .setAutoCancel(true) .setContentIntent(pintent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC); }else { notificationBuilder.setContentTitle(title) .setSmallIcon(R.drawable.application_icon2) .setPriority(NotificationCompat.PRIORITY_MAX) .setCategory(NotificationCompat.CATEGORY_EVENT) .setStyle(new NotificationCompat.BigTextStyle().bigText(description)) .setSound(ringtoneUri) .setAutoCancel(true) .setContentIntent(pintent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC); } if (mNotifyManager != null) { mNotifyManager.notify(Integer.parseInt(id), notificationBuilder.build()); Log.e("TAG", "showNotification: Success"); } else Log.e("TAG", "showNotification: Fail"); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/prepareList.java ================================================ package com.helloworld.goodpoint.ui; import android.app.Activity; import android.content.Context; import androidx.appcompat.app.AppCompatActivity; import com.helloworld.goodpoint.R; import java.util.ArrayList; import java.util.List; public class prepareList { public List prepareList(Context con) { List list = new ArrayList<>(); list.add(con.getString(R.string.Cairo)); list.add(con.getString(R.string.SharmElSheikh)); list.add(con.getString(R.string.Alexandria)); list.add(con.getString(R.string.ShubraElKheima)); list.add(con.getString(R.string.ElBeheira)); list.add(con.getString(R.string.Giza)); list.add(con.getString(R.string.PortSaid)); list.add(con.getString(R.string.Suez)); list.add(con.getString(R.string.ElMahallaElKubra)); list.add(con.getString(R.string.Luxor)); list.add(con.getString(R.string.Mansoura)); list.add(con.getString(R.string.Tanta)); list.add(con.getString(R.string.Asyut)); list.add(con.getString(R.string.Ismailia)); list.add(con.getString(R.string.Faiyum)); list.add(con.getString(R.string.Zagazig)); list.add(con.getString(R.string.Damietta)); list.add(con.getString(R.string.Aswan)); list.add(con.getString(R.string.Minya)); list.add(con.getString(R.string.BeniSuef)); list.add(con.getString(R.string.Hurghada)); list.add(con.getString(R.string.Qena)); list.add(con.getString(R.string.Sohag)); list.add(con.getString(R.string.ShibinElKom)); list.add(con.getString(R.string.Banha)); list.add(con.getString(R.string.Arish)); return list; } public List prepareListColor(Context con) { Listlist = new ArrayList<>(); list.add(con.getString(R.string.Blue)); list.add(con.getString(R.string.Red)); list.add(con.getString(R.string.Yellow)); list.add(con.getString(R.string.Orange)); list.add(con.getString(R.string.Green)); list.add(con.getString(R.string.Violet)); list.add(con.getString(R.string.Brown)); list.add(con.getString(R.string.Magenta)); list.add(con.getString(R.string.Tan)); list.add(con.getString(R.string.Cyan)); list.add(con.getString(R.string.Olive)); list.add(con.getString(R.string.Pink)); list.add(con.getString(R.string.Black)); list.add(con.getString(R.string.White)); list.add(con.getString(R.string.Gray)); list.add(con.getString(R.string.Purple)); return list; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/select_multiple_faces/ItemList.java ================================================ package com.helloworld.goodpoint.ui.select_multiple_faces; import android.graphics.Bitmap; import java.util.List; public class ItemList { private Bitmap ItemImage; private List subItemList; public ItemList(Bitmap ItemImage, List subItemList) { this.subItemList = subItemList; this.ItemImage = ItemImage; } public List getSubItemList() { return subItemList; } public void setSubItemList(List subItemList) { this.subItemList = subItemList; } public Bitmap getItemImage() { return ItemImage; } public void setItemImage(Bitmap itemImage) { ItemImage = itemImage; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/select_multiple_faces/ItemListAdapter.java ================================================ package com.helloworld.goodpoint.ui.select_multiple_faces; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.helloworld.goodpoint.R; import java.util.List; public class ItemListAdapter extends RecyclerView.Adapter { private RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool(); private List itemList; private Context cxt; ItemListAdapter(List itemList,Context cxt) { this.itemList = itemList; this.cxt=cxt; } @NonNull @Override public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_view_of_images, viewGroup, false); return new ItemViewHolder(view); } @Override public void onBindViewHolder(@NonNull ItemViewHolder itemViewHolder, int i) { com.helloworld.goodpoint.ui.select_multiple_faces.ItemList item = itemList.get(i); itemViewHolder.tvItemImage.setImageBitmap(item.getItemImage()); // Create layout manager with initial prefetch item count LinearLayoutManager layoutManager = new LinearLayoutManager( itemViewHolder.rvSubItem.getContext(), LinearLayoutManager.HORIZONTAL, false ); layoutManager.setInitialPrefetchItemCount(item.getSubItemList().size()); // Create sub item view adapter com.helloworld.goodpoint.ui.select_multiple_faces.SubItemListAdapter subItemAdapter = new com.helloworld.goodpoint.ui.select_multiple_faces.SubItemListAdapter(item.getSubItemList(),cxt); itemViewHolder.rvSubItem.setLayoutManager(layoutManager); itemViewHolder.rvSubItem.setAdapter(subItemAdapter); itemViewHolder.rvSubItem.setRecycledViewPool(viewPool); } @Override public int getItemCount() { return itemList.size(); } class ItemViewHolder extends RecyclerView.ViewHolder { private ImageView tvItemImage; private RecyclerView rvSubItem; ItemViewHolder(View itemView) { super(itemView); tvItemImage = itemView.findViewById(R.id.ItemImage); rvSubItem = itemView.findViewById(R.id.recycler_view_sub_items); } } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/select_multiple_faces/Selection.java ================================================ package com.helloworld.goodpoint.ui.select_multiple_faces; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.ui.GlobalVar; import com.helloworld.goodpoint.ui.test; import com.shashank.sony.fancytoastlib.FancyToast; import java.util.ArrayList; import java.util.List; public class Selection extends AppCompatActivity implements AdapterView.OnItemClickListener { private static final String TAG = "Selection"; //vars //private ArrayList mNames = new ArrayList<>(); //private ArrayList mImageUrls = new ArrayList<>(); RadioButton rb; Button Done_btn; ImageView imageView; SubItemListAdapter recyclerViewAdapter; RecyclerView rvItem; List> faces; List mfaces; boolean click = false; int k = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.multiple_faces_selection); rvItem = findViewById(R.id.recycler_view_sub_items); imageView = findViewById(R.id.ItemImage); rb = (RadioButton) findViewById(R.id.radioButton); faces = GlobalVar.allFaces; mfaces = GlobalVar.ImgThatHaveMoreThanOneFace; List mfaces = GlobalVar.ImgThatHaveMoreThanOneFace; click = false; createCard(k); Done_btn = (Button) findViewById(R.id.Done_btn); if (k == mfaces.size() - 1) { Done_btn.setText("Done"); } Done_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (click) { SubItemList list = GlobalVar.slist.get(GlobalVar.position); GlobalVar.FinialFacesThatWillGoToDataBase.add(list.getSubItemImage()); if (k == mfaces.size() - 1) { startActivity(new Intent(Selection.this, test.class)); finish(); } else { k++; createCard(k); click = false; if (k == mfaces.size() - 1) { Done_btn.setText("Done"); } } } else FancyToast.makeText(Selection.this, "Specify the face of the missing person", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show(); // } }); } private void createCard(int i) { imageView.setImageBitmap(mfaces.get(i)); LinearLayoutManager layoutManager = new LinearLayoutManager( rvItem.getContext(), LinearLayoutManager.HORIZONTAL, false ); recyclerViewAdapter = new SubItemListAdapter(buildSubItemList(faces.get(i)), this); recyclerViewAdapter.setOnItemClickListener(this); rvItem.setAdapter(recyclerViewAdapter); rvItem.setLayoutManager(layoutManager); } private List buildSubItemList(List faces) { List subItemList = new ArrayList<>(); for (int i = 0; i < faces.size(); i++) { com.helloworld.goodpoint.ui.select_multiple_faces.SubItemList subItem = new com.helloworld.goodpoint.ui.select_multiple_faces.SubItemList(faces.get(i), i); subItemList.add(subItem); } GlobalVar.slist = subItemList; return subItemList; } @Override public void onItemClick(AdapterView parent, View view, int position, long id) { SubItemList list = GlobalVar.slist.get(position); click = true; int i = list.getPos(); i += 1; GlobalVar.position=position; Toast.makeText(this, "Face number (" + i + ") is selected", Toast.LENGTH_SHORT).show(); } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/select_multiple_faces/SubItemList.java ================================================ package com.helloworld.goodpoint.ui.select_multiple_faces; import android.graphics.Bitmap; import java.io.Serializable; public class SubItemList implements Serializable { private Bitmap subItemImage; public int getPos() { return pos; } public void setPos(int pos) { this.pos = pos; } private int pos; public SubItemList(Bitmap subItemImage,int pos) { this.subItemImage = subItemImage; this.pos=pos; } public Bitmap getSubItemImage() { return subItemImage; } public void setSubItemImage(Bitmap subItemImage) { this.subItemImage = subItemImage; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/select_multiple_faces/SubItemListAdapter.java ================================================ package com.helloworld.goodpoint.ui.select_multiple_faces; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.RadioButton; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.helloworld.goodpoint.R; import java.util.List; public class SubItemListAdapter extends RecyclerView.Adapter { private List subItemList; private int lastSelectedPosition = -1; private Context context; private AdapterView.OnItemClickListener onItemClickListener; SubItemListAdapter(List subItemList, Context ctx) { this.subItemList = subItemList; context = ctx; } @NonNull @Override public SubItemViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_sub_list_items, viewGroup, false); return new SubItemViewHolder(view,this); } @Override public void onBindViewHolder(@NonNull SubItemViewHolder subItemViewHolder, int i) { com.helloworld.goodpoint.ui.select_multiple_faces.SubItemList subItem = subItemList.get(i); subItemViewHolder.tvItemImage.setImageBitmap(subItem.getSubItemImage()); try { subItemViewHolder.bindData(subItem, i); subItem.setPos(i); } catch (Exception e) { e.printStackTrace(); } //Toast.makeText(cxt, "size="+item.getSubItemList().size(),Toast.LENGTH_LONG).show(); } public void setOnItemClickListener(AdapterView.OnItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } public void onItemHolderClick(SubItemViewHolder holder) { if (onItemClickListener != null) onItemClickListener.onItemClick(null, holder.itemView, holder.getAdapterPosition(), holder.getItemId()); } @Override public int getItemCount() { return subItemList.size(); } class SubItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private SubItemListAdapter mAdapter; private ImageView tvItemImage; private RadioButton rb; public SubItemViewHolder(View itemView, final SubItemListAdapter mAdapter) { super(itemView); this.mAdapter=mAdapter; tvItemImage = itemView.findViewById(R.id.img_view); rb = itemView.findViewById(R.id.radioButton); itemView.setOnClickListener(this); rb.setOnClickListener( this); } public void bindData(SubItemList list, int position) { rb.setChecked(position==lastSelectedPosition); } public void onClick(View v){ lastSelectedPosition = getAdapterPosition(); notifyItemRangeChanged(0,subItemList.size()); mAdapter.onItemHolderClick(SubItemViewHolder.this); } } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/sub.java ================================================ package com.helloworld.goodpoint.ui; import android.graphics.Bitmap; import java.io.Serializable; public class sub implements Serializable { private Bitmap subItemImage; public int getPos() { return pos; } public void setPos(int pos) { this.pos = pos; } private int pos; public sub(Bitmap subItemImage,int pos) { this.subItemImage = subItemImage; this.pos=pos; } public Bitmap getSubItemImage() { return subItemImage; } public void setSubItemImage(Bitmap subItemImage) { this.subItemImage = subItemImage; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/subAdapter.java ================================================ package com.helloworld.goodpoint.ui; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.RadioButton; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.helloworld.goodpoint.R; import java.util.List; public class subAdapter extends RecyclerView.Adapter { private List subItemList; private int lastSelectedPosition = -1; private Context context; private AdapterView.OnItemClickListener onItemClickListener; subAdapter(List subItemList, Context ctx) { this.subItemList = subItemList; context = ctx; } @NonNull @Override public subViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.rr, viewGroup, false); return new subViewHolder(view,this); } @Override public void onBindViewHolder(@NonNull subViewHolder subItemViewHolder, int i) { sub subItem = subItemList.get(i); subItemViewHolder.tvItemImage.setImageBitmap(subItem.getSubItemImage()); //Toast.makeText(cxt, "size="+item.getSubItemList().size(),Toast.LENGTH_LONG).show(); } public void setOnItemClickListener(AdapterView.OnItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } public void onItemHolderClick(subViewHolder holder) { if (onItemClickListener != null) onItemClickListener.onItemClick(null, holder.itemView, holder.getAdapterPosition(), holder.getItemId()); } @Override public int getItemCount() { return subItemList.size(); } class subViewHolder extends RecyclerView.ViewHolder { private subAdapter mAdapter; private ImageView tvItemImage; private RadioButton rb; public subViewHolder(View itemView, final subAdapter mAdapter) { super(itemView); this.mAdapter=mAdapter; tvItemImage = itemView.findViewById(R.id.img1_view); } } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/ui/test.java ================================================ package com.helloworld.goodpoint.ui; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.loader.content.CursorLoader; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.gson.JsonObject; import com.helloworld.goodpoint.R; import com.helloworld.goodpoint.pojo.FoundPerson; import com.helloworld.goodpoint.pojo.LostPerson; import com.helloworld.goodpoint.pojo.User; import com.helloworld.goodpoint.retrofit.ApiClient; import com.helloworld.goodpoint.retrofit.ApiInterface; import com.helloworld.goodpoint.ui.lostFoundObject.FoundObjectActivity; import com.helloworld.goodpoint.ui.lostFoundObject.LostObjectDetailsActivity; import com.shashank.sony.fancytoastlib.FancyToast; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class test extends AppCompatActivity { subAdapter recyclerViewAdapter; RecyclerView rvItem; List mfaces; Button Save_btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.r); rvItem = findViewById(R.id.q); mfaces = GlobalVar.FinialFacesThatWillGoToDataBase; createCard(); Save_btn = (Button) findViewById(R.id.Save_btn); Save_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(GlobalVar.flag==1) FoundPerson(); else if(GlobalVar.flag==2) LostPerson(); //FancyToast.makeText(test.this, "Done", FancyToast.LENGTH_LONG, FancyToast.SUCCESS, false).show(); } }); } private void createCard() { LinearLayoutManager layoutManager = new LinearLayoutManager( rvItem.getContext(), LinearLayoutManager.HORIZONTAL, false ); recyclerViewAdapter = new subAdapter(buildSubItemList(mfaces), this); rvItem.setAdapter(recyclerViewAdapter); rvItem.setLayoutManager(layoutManager); } public Uri getImageUri(Bitmap bitmap_Image) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bitmap_Image.compress(Bitmap.CompressFormat.JPEG, 100, bytes); String path = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap_Image, (System.currentTimeMillis()%1000)+"", null); return Uri.parse(path); } private String getRealPathFromURI(Uri imageUri) { String[] proj = {MediaStore.Images.Media.DATA}; CursorLoader loader = new CursorLoader(this, imageUri, proj, null, null, null); Cursor cursor = loader.loadInBackground(); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String result = cursor.getString(column_index); cursor.close(); return result; } public void FoundPerson() { String Datee = FoundPerson.getFoundPerson().getDate(); ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class); Uri imageURI = getImageUri(GlobalVar.FinialFacesThatWillGoToDataBase.get(0)); File file = new File(getRealPathFromURI(imageURI)); RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file); MultipartBody.Part Pimage = MultipartBody.Part.createFormData("image", file.getName(), requestBody); String PName = FoundPerson.getFoundPerson().getName(); String City = FoundPerson.getFoundPerson().getCity(); double Longitude = FoundPerson.getFoundPerson().getLongitude(); double Latitude = FoundPerson.getFoundPerson().getLatitude(); Call call = apiInterface.storeFoundPerson(User.getUser().getId(), Datee, City, Longitude , Latitude, PName, Pimage); call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { if(response.isSuccessful()) { FancyToast.makeText(test.this, "The data has been saved successfully", FancyToast.LENGTH_LONG, FancyToast.SUCCESS, false).show(); try { String id = new JSONObject(response.body().toString()).getString("id"); } catch (JSONException e) { Log.e("TAG", "onResponse: "+e.getMessage()); } startActivity(new Intent(test.this, HomeActivity.class)); finish(); }else Toast.makeText(test.this, "The object is not posted.", Toast.LENGTH_SHORT).show(); } @Override public void onFailure(Call call, Throwable t) { Toast.makeText(test.this, t.getMessage(), Toast.LENGTH_LONG).show(); } }); } public void LostPerson() { String Datee = LostPerson.getLostPerson().getDate(); ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class); Uri imageURI = getImageUri(GlobalVar.FinialFacesThatWillGoToDataBase.get(0)); File file = new File(getRealPathFromURI(imageURI)); RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file); MultipartBody.Part Pimage = MultipartBody.Part.createFormData("image", file.getName(), requestBody); //MultipartBody.Part image = MultipartBody.Part.createFormData("images", file.getName(), requestBody); //Pimages.add(image); String PName = LostPerson.getLostPerson().getName(); String City = LostPerson.getLostPerson().getCity(); Call call = apiInterface.storeLostPerson(Datee,City,User.getUser().getId(),PName,Pimage); call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { if(response.isSuccessful()) { FancyToast.makeText(test.this, "The data has been saved successfully", FancyToast.LENGTH_LONG, FancyToast.SUCCESS, false).show(); try { String id = new JSONObject(response.body().toString()).getString("id"); } catch (JSONException e) { Log.e("TAG", "onResponse: "+e.getMessage()); } startActivity(new Intent(test.this, HomeActivity.class)); finish(); }else { try { Log.e("onResponse: ", response.errorBody().string()); } catch (IOException e) { Log.e("onResponse: ", e.getMessage()); } } } @Override public void onFailure(Call call, Throwable t) { Toast.makeText(test.this, t.getMessage(), Toast.LENGTH_LONG).show(); Log.e("onFailure: ", t.getMessage()); } }); } private List buildSubItemList(List faces) { List subItemList = new ArrayList<>(); for (int i = 0; i < faces.size(); i++) { sub subItem = new sub(faces.get(i), i); subItemList.add(subItem); } return subItemList; } } ================================================ FILE: app/src/main/java/com/helloworld/goodpoint/utils/Draw.java ================================================ package com.helloworld.goodpoint.utils; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.view.View; import androidx.annotation.Nullable; import org.w3c.dom.Text; public class Draw extends View { protected Paint boundaryPaint; protected Paint textPaint; private Rect rect; private String Text; public void init(int i){ boundaryPaint = new Paint(); boundaryPaint.setColor(Color.GREEN); boundaryPaint.setStrokeWidth(10f); // boundaryPaint.setStyle(Paint.Style.STROKE); textPaint = new Paint(); if(i == 1) textPaint.setColor(Color.GREEN); else textPaint.setColor(Color.RED); textPaint.setTextSize(50f); textPaint.setStyle(Paint.Style.FILL); } public Draw(Context context, String Tex) { super(context); // rect = rec; Text = Tex; } protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawText(Text,70,70,textPaint); // canvas.drawRect(rect.left+150,rect.top+150,rect.right+150,rect.bottom+150,boundaryPaint); } } ================================================ FILE: app/src/main/java/fragments/PageFragment1.java ================================================ package fragments; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.helloworld.goodpoint.R; public class PageFragment1 extends Fragment { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { ViewGroup rootview=(ViewGroup)inflater.inflate(R.layout.slider_page1,container,false); return rootview; } } ================================================ FILE: app/src/main/java/fragments/PageFragment2.java ================================================ package fragments; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.helloworld.goodpoint.R; public class PageFragment2 extends Fragment { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { ViewGroup rootview=(ViewGroup)inflater.inflate(R.layout.slider_page2,container,false); return rootview; } } ================================================ FILE: app/src/main/java/fragments/PageFragment3.java ================================================ package fragments; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.helloworld.goodpoint.R; public class PageFragment3 extends Fragment { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { ViewGroup rootview=(ViewGroup)inflater.inflate(R.layout.slider_page3,container,false); return rootview; } } ================================================ FILE: app/src/main/res/anim/rotate_splash.xml ================================================ ================================================ FILE: app/src/main/res/drawable/account_circle.xml ================================================ ================================================ FILE: app/src/main/res/drawable/active_dot.xml ================================================ ================================================ FILE: app/src/main/res/drawable/add_new_photo2.xml ================================================ ================================================ FILE: app/src/main/res/drawable/application_icon.xml ================================================ ================================================ FILE: app/src/main/res/drawable/application_icon2.xml ================================================ ================================================ FILE: app/src/main/res/drawable/background.xml ================================================ ================================================ FILE: app/src/main/res/drawable/background2.xml ================================================ ================================================ FILE: app/src/main/res/drawable/bottom_sheet_background.xml ================================================ ================================================ FILE: app/src/main/res/drawable/btn_login.xml ================================================ ================================================ FILE: app/src/main/res/drawable/buttons.xml ================================================ ================================================ FILE: app/src/main/res/drawable/circle.xml ================================================ ================================================ FILE: app/src/main/res/drawable/circle2.xml ================================================ ================================================ FILE: app/src/main/res/drawable/custom_button.xml ================================================ ================================================ FILE: app/src/main/res/drawable/custom_button_location.xml ================================================ ================================================ FILE: app/src/main/res/drawable/default_dot.xml ================================================ ================================================ FILE: app/src/main/res/drawable/details_background.xml ================================================ ================================================ FILE: app/src/main/res/drawable/details_btns.xml ================================================ ================================================ FILE: app/src/main/res/drawable/general_back_icon.xml ================================================ ================================================ FILE: app/src/main/res/drawable/halfcircle.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_account_circle.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_add.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_background.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_account_circle_150.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_account_circle_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_add_a_photo_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_archive_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_assignment_turned_in_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_business_center_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_check_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_check_circle_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_date_range_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_email_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_exit_to_app_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_fact_check_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_feedback_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_gallery_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_help_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_location_on_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_location_on_241.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_location_on_242.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_location_on_243.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_lock_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_navigate_next_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_notifications_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_person_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_phone_android_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_photo_camera_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_remove_red_eye_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_room_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_search_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_search_241.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_settings_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_share_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_star_rate_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_visibility_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_baseline_visibility_off_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_close.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_design.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_done.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_found.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_home.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_home_background.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_image.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_launcher_background.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_launcher_background1.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_launcher_foreground.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_location.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_lock.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_lost.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_notification.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_password.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_password_reset.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_photo.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_prof_pic.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_profile.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_realcam.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_rotat_image.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_signup.xml ================================================ ================================================ FILE: app/src/main/res/drawable/location_signin.xml ================================================ ================================================ FILE: app/src/main/res/drawable/nav_head_color.xml ================================================ ================================================ FILE: app/src/main/res/drawable/notification_button1.xml ================================================ ================================================ FILE: app/src/main/res/drawable/notification_button2.xml ================================================ ================================================ FILE: app/src/main/res/drawable/oval.xml ================================================ ================================================ FILE: app/src/main/res/drawable/q_circle.xml ================================================ ================================================ FILE: app/src/main/res/drawable/radius_expand.xml ================================================ ================================================ FILE: app/src/main/res/drawable/show_password.xml ================================================ ================================================ FILE: app/src/main/res/drawable/signin_background.xml ================================================ ================================================ FILE: app/src/main/res/drawable/switch_icon.xml ================================================ ================================================ FILE: app/src/main/res/drawable/wave.xml ================================================ ================================================ FILE: app/src/main/res/drawable/white_oval.xml ================================================ ================================================ FILE: app/src/main/res/drawable-mdpi/avd_done.xml ================================================ ================================================ FILE: app/src/main/res/drawable-v24/ic_launcher_foreground.xml ================================================ ================================================ FILE: app/src/main/res/drawable-xxxhdpi/bottom_sheet_bg.xml ================================================ ================================================ FILE: app/src/main/res/drawable-xxxhdpi/ic_baseline_add.xml ================================================ ================================================ FILE: app/src/main/res/drawable-xxxhdpi/ic_baseline_remove.xml ================================================ ================================================ FILE: app/src/main/res/drawable-xxxhdpi/ic_launcher_background.xml ================================================ ================================================ FILE: app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.xml ================================================ ================================================ FILE: app/src/main/res/drawable-xxxhdpi/rectangle.xml ================================================ ================================================ FILE: app/src/main/res/font/muli_black.xml ================================================ ================================================ FILE: app/src/main/res/font/muli_extralight.xml ================================================ ================================================ FILE: app/src/main/res/font/roboto_bold.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_action.xml ================================================