diff --git a/app/build.gradle b/app/build.gradle index ddf3e1a..e5042a6 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -10,8 +10,8 @@ android { applicationId "com.uam.wmi.findmytutor" minSdkVersion 22 targetSdkVersion 27 - versionCode 3 - versionName "0.9.0-alpha" + versionCode 8 + versionName "0.9.1-alpha" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" vectorDrawables.useSupportLibrary = true } @@ -30,7 +30,7 @@ repositories { } dependencies { - implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation fileTree(include: ['*.jar'], dir: 'libs') implementation 'com.android.support:preference-v7:27.1.1' implementation 'com.android.support:appcompat-v7:27.1.1' implementation 'com.android.support:design:27.1.1' @@ -43,18 +43,18 @@ dependencies { implementation 'com.google.code.gson:gson:2.8.5' implementation 'com.squareup.retrofit2:retrofit:2.4.0' implementation 'com.squareup.retrofit2:converter-gson:2.4.0' - implementation "io.swagger:swagger-annotations:1.5.15" - implementation "org.threeten:threetenbp:1.3.5" + implementation 'io.swagger:swagger-annotations:1.5.15' + implementation 'org.threeten:threetenbp:1.3.5' implementation 'com.mapbox.mapboxsdk:mapbox-android-sdk:6.6.5' implementation 'io.reactivex.rxjava2:rxjava:2.2.0' implementation 'com.android.support:recyclerview-v7:27.1.1' implementation 'io.reactivex.rxjava2:rxandroid:2.1.0' - implementation "com.jakewharton:butterknife:8.8.1" + implementation 'com.jakewharton:butterknife:8.8.1' annotationProcessor "com.jakewharton:butterknife-compiler:8.8.1" - implementation "com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0" - implementation "com.squareup.okhttp3:okhttp:3.11.0" - implementation "com.squareup.okhttp3:okhttp-urlconnection:3.10.0" - implementation "com.squareup.okhttp3:logging-interceptor:3.11.0" + implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0' + implementation 'com.squareup.okhttp3:okhttp:3.11.0' + implementation 'com.squareup.okhttp3:okhttp-urlconnection:3.10.0' + implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0' implementation 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1' implementation 'com.auth0.android:jwtdecode:1.1.1' implementation 'com.annimon:stream:1.2.1' @@ -62,5 +62,5 @@ dependencies { implementation 'com.mapbox.mapboxsdk:mapbox-sdk-turf:4.0.0' // FloatingBarMenu implementation 'com.getbase:floatingactionbutton:1.10.1' - + implementation 'org.apache.commons:commons-collections4:4.0' } diff --git a/app/src/main/java/com/uam/wmi/findmytutor/activity/BaseActivity.java b/app/src/main/java/com/uam/wmi/findmytutor/activity/BaseActivity.java index b442f6d..3209b11 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/activity/BaseActivity.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/activity/BaseActivity.java @@ -20,15 +20,19 @@ import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; +import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.FrameLayout; import android.widget.Toast; + +import com.mapbox.mapboxsdk.Mapbox; import com.uam.wmi.findmytutor.R; import com.uam.wmi.findmytutor.service.BackgroundLocalizationService; import com.uam.wmi.findmytutor.utils.ActiveFragment; import com.uam.wmi.findmytutor.utils.FeedbackUtils; +import com.uam.wmi.findmytutor.utils.MapUtils; import com.uam.wmi.findmytutor.utils.PrefUtils; import com.uam.wmi.findmytutor.utils.RxSearchObservable; @@ -38,10 +42,15 @@ import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; +import io.reactivex.Observable; +import io.reactivex.ObservableSource; import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; +import static com.uam.wmi.findmytutor.utils.Consts.deafultMapZoom; +import static com.uam.wmi.findmytutor.utils.Consts.searchMapZoom; import static com.uam.wmi.findmytutor.utils.PrefUtils.storeBackgroundLocationStatus; @@ -49,7 +58,6 @@ public abstract class BaseActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener { - protected static final int REQUEST_PERMISSIONS = 100; private final static int REQUEST_CODE_ASK_PERMISSIONS = 1; private static final String[] REQUIRED_SDK_PERMISSIONS = new String[]{ Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS}; @@ -201,7 +209,7 @@ public abstract class BaseActivity } public void handleBackgroundTaskLifeCycle() { - Boolean shouldServiceRun = PrefUtils.isEnableSharingLocalization(getApplicationContext()); + Boolean shouldServiceRun = PrefUtils.isEnableSharingLocalization(getApplicationContext()) && isTutor; if (shouldServiceRun) { startBackgroundLocalizationTask(); @@ -267,16 +275,21 @@ public abstract class BaseActivity searchView.setOnQueryTextFocusChangeListener((v, hasFocus) -> { if (!hasFocus && activeFragment.equals(ActiveFragment.NONE)) { restoreMapMarkers(); + adjustMapToSearch(deafultMapZoom); + } + + if(hasFocus && activeFragment.equals(ActiveFragment.NONE)){ + adjustMapToSearch(searchMapZoom); } }); - RxSearchObservable.fromView(searchView) + .skip(0) .map(String::toLowerCase) - .debounce(300, TimeUnit.MILLISECONDS) - .distinctUntilChanged() + .debounce(250, TimeUnit.MILLISECONDS) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) + .switchMap((Function>) Observable::just) .subscribe(this::executeSearch); return true; @@ -285,16 +298,17 @@ public abstract class BaseActivity private void executeSearch(String input) { if (activeFragment.equals(ActiveFragment.USER_LIST)) { ((UsersListFragment) userListFragment).searchUser(input); + } else if (activeFragment.equals(ActiveFragment.NONE)) { searchUser(input); } } - public void searchUser(String textToSearch) { - } + abstract void searchUser(String textToSearch); - public void restoreMapMarkers() { - } + abstract void restoreMapMarkers(); + + abstract void adjustMapToSearch(Integer zoom); @Override public boolean onOptionsItemSelected(MenuItem item) { diff --git a/app/src/main/java/com/uam/wmi/findmytutor/activity/LoginActivity.java b/app/src/main/java/com/uam/wmi/findmytutor/activity/LoginActivity.java index 1054754..a7dd423 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/activity/LoginActivity.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/activity/LoginActivity.java @@ -10,14 +10,11 @@ import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; - -import android.util.Log; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; -import android.widget.Switch; import com.auth0.android.jwt.Claim; import com.auth0.android.jwt.JWT; @@ -44,7 +41,6 @@ import okhttp3.ResponseBody; public class LoginActivity extends AppCompatActivity { - // UI references. private AutoCompleteTextView mLoginNameView; private EditText mPasswordView; private View mProgressView; @@ -151,12 +147,10 @@ public class LoginActivity extends AppCompatActivity { } - private void loginProcess(String email, String password) { - ValidateUser user = new ValidateUser(email, password); - LdapUser fuser = new LdapUser(email,password,"tutor","tutor","mieszko","nocny","szmsdsdsdsdare@wmi.pl"); -// disposable.add(ldapService.validate(user) - disposable.add(ldapService.fakeValidate(fuser) + ValidateUser user = new ValidateUser(email, password); + + disposable.add(ldapService.validate(user) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::handleResponse, this::handleError)); @@ -165,9 +159,9 @@ public class LoginActivity extends AppCompatActivity { private void getUserProfile(String userId) { disposable.add(userService.getUserById(userId) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(this::saveUserProfileToSharedPreferences, this::handleError)); + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(this::saveUserProfileToSharedPreferences, this::handleError)); } private void showSnackBarMessage(String message) { @@ -183,12 +177,12 @@ public class LoginActivity extends AppCompatActivity { Claim userId = jwt.getClaim("nameid"); Claim role = jwt.getClaim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role"); - if(Objects.requireNonNull(role.asString()).equals("Student")){ + if (Objects.requireNonNull(role.asString()).equals("Student")) { PrefUtils.storeIsTutor(getApplicationContext(), false); - }else{ + } else { PrefUtils.storeIsTutor(getApplicationContext(), true); } - + PrefUtils.storeIsLoggedIn(getApplicationContext(), true); PrefUtils.storeApiKey(getApplicationContext(), token); PrefUtils.storeUserId(getApplicationContext(), userId.asString()); diff --git a/app/src/main/java/com/uam/wmi/findmytutor/activity/MapActivity.java b/app/src/main/java/com/uam/wmi/findmytutor/activity/MapActivity.java index 4a8a7e2..8e89d40 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/activity/MapActivity.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/activity/MapActivity.java @@ -4,7 +4,6 @@ import android.Manifest; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.annotation.SuppressLint; -import android.graphics.Color; import android.location.Location; import android.os.Bundle; import android.os.Handler; @@ -25,6 +24,7 @@ import com.getbase.floatingactionbutton.FloatingActionButton; import com.jakewharton.retrofit2.adapter.rxjava2.HttpException; import com.mapbox.android.core.permissions.PermissionsListener; import com.mapbox.android.core.permissions.PermissionsManager; +import com.mapbox.geojson.Point; import com.mapbox.mapboxsdk.Mapbox; import com.mapbox.mapboxsdk.annotations.Icon; import com.mapbox.mapboxsdk.annotations.IconFactory; @@ -46,13 +46,13 @@ import com.uam.wmi.findmytutor.network.ApiClient; import com.uam.wmi.findmytutor.service.CoordinateService; import com.uam.wmi.findmytutor.service.PredefinedStatusesService; import com.uam.wmi.findmytutor.service.UserService; -import com.uam.wmi.findmytutor.utils.FeedbackUtils; +import com.uam.wmi.findmytutor.utils.ApproximatedLocalization; import com.uam.wmi.findmytutor.utils.ManualLocationUtils; import com.uam.wmi.findmytutor.utils.MapMarker; import com.uam.wmi.findmytutor.utils.PrefUtils; import com.uam.wmi.findmytutor.utils.RestApiHelper; import com.uam.wmi.findmytutor.utils.SharingLevel; -import com.uam.wmi.findmytutor.utils.mapUtils; +import com.uam.wmi.findmytutor.utils.MapUtils; import java.util.ArrayList; import java.util.HashMap; @@ -99,6 +99,7 @@ public class MapActivity extends BaseActivity private int tiltParam = 30; private String myId; private boolean isTutor; + private ApproximatedLocalization approximatedLocalization; @Override protected void onCreate(Bundle savedInstanceState) { @@ -121,6 +122,7 @@ public class MapActivity extends BaseActivity }; + selectLocationButton = findViewById(R.id.select_location_button); removeLocationButton = findViewById(R.id.remove_location_button); Mapbox.getInstance(this, getString(R.string.access_token)); @@ -131,6 +133,7 @@ public class MapActivity extends BaseActivity //start background task handleBackgroundTaskLifeCycle(); manualLocationUtils = new ManualLocationUtils(MapActivity.this); + approximatedLocalization = new ApproximatedLocalization(MapUtils.loadJsonFromAsset(getApplicationContext(), "building.geojson")); } @Override @@ -151,7 +154,7 @@ public class MapActivity extends BaseActivity stopBackgroundLocalizationTask(); removeLocationButton.setVisibility(View.GONE); - Toast.makeText(MapActivity.this, "Your marker will disappear in next couple minutes", Toast.LENGTH_SHORT).show(); + Toast.makeText(MapActivity.this, R.string.manual_marker_info, Toast.LENGTH_SHORT).show(); }); } else { @@ -161,28 +164,13 @@ public class MapActivity extends BaseActivity return true; }); - setToggleMapBoundsArea(); - if (isTutor) { setOnMapLongClickListener(); } - } - private void setToggleMapBoundsArea() { - mapUtils.setMapBoundsArea(getApplicationContext(), mapboxMap, mapView, true); - - FloatingActionButton toggleBoundsAreaFab = findViewById(R.id.fab_toggle_bound_area); - toggleBoundsAreaFab.setOnClickListener(view -> { - if (toggleBoundsAreaFab.getTitle().equals("Bounds OFF")) { - toggleBoundsAreaFab.setTitle("Bounds ON"); - mapUtils.setMapBoundsArea(getApplicationContext(), mapboxMap, mapView, false); - } else { - toggleBoundsAreaFab.setTitle("Bounds OFF"); - mapUtils.setMapBoundsArea(getApplicationContext(), mapboxMap, mapView, true); - } - - }); + setOnMapClickListener(); + MapUtils.setMapBoundsArea(getApplicationContext(), mapboxMap, mapView, true); } private void updateUserHashMap(String userId, Long markerId) { @@ -238,62 +226,21 @@ public class MapActivity extends BaseActivity private void showError(Throwable e) { String message; + Log.e("ERR",e.toString()); + if (e instanceof HttpException) { ResponseBody responseBody = ((HttpException) e).response().errorBody(); message = RestApiHelper.getErrorMessage(responseBody); } else { - message = "Network Error!"; + message = getString(R.string.network_error); } Toast.makeText(MapActivity.this, message, Toast.LENGTH_SHORT).show(); } - - /* private void setOnMapLongClickListener() { - - mapboxMap.addOnMapLongClickListener((LatLng latLng) -> { - selectLocationButton.setVisibility(View.VISIBLE); - removeLocationButton.setVisibility(View.GONE); - - if (tmpLocalMarker == null) { - - String sharingLevel = SharingLevel.MANUAL.toString(); - Icon defaultIcon = getMapIcon(sharingLevel, myId); - - MarkerOptions markerOptions = new MarkerOptions() - .setIcon(defaultIcon) - .position(latLng); - - tmpLocalMarker = mapboxMap.addMarker(markerOptions); - MapMarker marker = new MapMarker(tmpLocalMarker, markerOptions, defaultIcon, sharingLevel); - - markerHash.put(myId, marker); - updateUserHashMap(myId, marker.getMarker().getId()); - - } else { - ValueAnimator markerAnimator = ObjectAnimator.ofObject(tmpLocalMarker, "position", - new mapUtils.LatLngEvaluator(), tmpLocalMarker.getPosition(), latLng); - markerAnimator.setDuration(2000); - markerAnimator.start(); - } - - selectLocationButton.setOnClickListener((View view) -> { - if (tmpLocalMarker != null) { - try { - manualLocationUtils.showLocationDialog("Name the location", latLng); - startBackgroundLocalizationTask(); - } catch (IllegalArgumentException e) { - Timber.e(String.valueOf(e)); - } - - selectLocationButton.setVisibility(View.GONE); - mapboxMap.removeMarker(tmpLocalMarker); - tmpLocalMarker = null; - } - }); - }); - - }*/ + private void setOnMapClickListener() { + mapboxMap.addOnMapClickListener(e -> removeLocationButton.setVisibility(View.GONE)); + } private void setOnMapLongClickListener() { @@ -310,14 +257,11 @@ public class MapActivity extends BaseActivity .position(latLng); tmpLocalMarker = mapboxMap.addMarker(markerOptions); - MapMarker marker = new MapMarker(tmpLocalMarker, markerOptions, defaultIcon, sharingLevel); - - updateUserHashMap(myId, marker.getMarker().getId()); - + new MapMarker(tmpLocalMarker, markerOptions, defaultIcon, sharingLevel); } else { ValueAnimator markerAnimator = ObjectAnimator.ofObject(tmpLocalMarker, "position", - new mapUtils.LatLngEvaluator(), tmpLocalMarker.getPosition(), latLng); + new MapUtils.LatLngEvaluator(), tmpLocalMarker.getPosition(), latLng); markerAnimator.setDuration(2000); markerAnimator.start(); } @@ -325,21 +269,22 @@ public class MapActivity extends BaseActivity selectLocationButton.setOnClickListener((View view) -> { if (tmpLocalMarker != null) { + String approximatedLocation = approximatedLocalization.getNameOfBuildingPart(Point.fromLngLat(latLng.getLongitude(), latLng.getLatitude())); try { droppedMarkercoordinate = new Coordinate( latLng.getLatitude(), latLng.getLongitude(), latLng.getAltitude(), - "approx", + approximatedLocation, PrefUtils.getUserFirstName(getApplicationContext()) + " " + PrefUtils.getUserLastName(getApplicationContext()), PrefUtils.getUserId(getApplicationContext()), PrefUtils.getLocationLevel(getApplicationContext()) ); - PrefUtils.putManualLocation(this, latLng); - handleBackgroundTaskLifeCycle(); + PrefUtils.putManualLocation(this, latLng, approximatedLocation); + handleBackgroundTaskLifeCycle(); } catch (IllegalArgumentException e) { Timber.e(String.valueOf(e)); @@ -347,7 +292,7 @@ public class MapActivity extends BaseActivity Toast.makeText( MapActivity.this, - "Manual Locations selected!" + latLng, + getString(R.string.manual_location_selected), Toast.LENGTH_LONG ).show(); @@ -365,7 +310,7 @@ public class MapActivity extends BaseActivity public void showLocationDialog(LatLng latLng) { LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext()); - @SuppressLint("InflateParams") View view = layoutInflaterAndroid.inflate(R.layout.location_modal, null); + @SuppressLint("InflateParams") View view = layoutInflaterAndroid.inflate(R.layout.location_modal, null); AlertDialog.Builder alertDialogBuilderUserInput = new android.support.v7.app.AlertDialog.Builder(this); alertDialogBuilderUserInput.setView(view).setPositiveButton(getApplicationContext().getString(R.string.modal_location_send), null); @@ -392,42 +337,42 @@ public class MapActivity extends BaseActivity Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.modal_location_hint), Toast.LENGTH_SHORT).show(); modalUserInput.requestFocus(); } else { - PrefUtils.putManualLocation(getApplicationContext(), latLng); - sendLocation(body,latLng); + sendLocation(body, latLng); alertDialog.dismiss(); } }); }); - - - alertDialog.show(); } private void sendLocation(String body, LatLng latLng) { + PredefinedStatusesService predefinedStatusesService = ApiClient.getClient(getApplicationContext()).create(PredefinedStatusesService.class); + PredefinedCoordViewModel droppedMarkercoordinate = new PredefinedCoordViewModel( latLng.getLatitude(), latLng.getLongitude(), latLng.getAltitude(), PrefUtils.getUserId(getApplicationContext()), - "string", - "predefined", + approximatedLocalization.getNameOfBuildingPart(Point.fromLngLat(latLng.getLongitude(), latLng.getLatitude())), + SharingLevel.PREDEFINED.toString(), body ); - PredefinedStatusesService predefinedStatusesService = ApiClient.getClient(getApplicationContext()).create(PredefinedStatusesService.class); CompositeDisposable disposable = new CompositeDisposable(); - disposable.add(predefinedStatusesService.postUserPredefinedCoord(PrefUtils.getUserId(getApplicationContext()), droppedMarkercoordinate) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(this::handleResponse, this::handleError)); + disposable.add( + predefinedStatusesService.postUserPredefinedCoord(PrefUtils.getUserId(getApplicationContext()), droppedMarkercoordinate) + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(this::SaveCurrentManualLocation, this::handleError) + ); } - private void handleResponse(List resp) { - Toast.makeText(getApplicationContext(), "Location saved!", Toast.LENGTH_SHORT).show(); + private void SaveCurrentManualLocation(PredefinedCoordViewModel resp) { + Toast.makeText(getApplicationContext(), R.string.location_saved, Toast.LENGTH_SHORT).show(); + PrefUtils.putCurrentManualLocation(getApplicationContext(),resp.getPredefinedCoordinateId()); } private void fetchTopCoords() { @@ -436,12 +381,13 @@ public class MapActivity extends BaseActivity coordinateService.getOnlineCoordinates() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) + .map(tutors -> Stream.of(tutors). + filterNot(t -> t.getDisplayMode().equals(SharingLevel.PRESENCE.toString())).toList()) .subscribeWith(new DisposableSingleObserver>() { @Override public void onSuccess(List coordsList) { - if (tmpLocalMarker != null && coordsList.isEmpty()) { Timber.e("200 empty []"); mapboxMap.clear(); @@ -495,7 +441,7 @@ public class MapActivity extends BaseActivity LatLng toDestination = new LatLng(element.getLatitude(), element.getLongitude()); // TODO fix flickiering markers ValueAnimator markerAnimator = ObjectAnimator.ofObject(marker, "position", - new mapUtils.LatLngEvaluator(), + new MapUtils.LatLngEvaluator(), marker.getPosition(), toDestination); markerAnimator.setDuration(2000); @@ -617,7 +563,7 @@ public class MapActivity extends BaseActivity Location lastKnownLocation = locationComponent.getLastKnownLocation(); if (lastKnownLocation != null) { - mapUtils.makeNewCamera(mapboxMap, + MapUtils.makeNewCamera(mapboxMap, lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude(), zoomParam, @@ -775,4 +721,8 @@ public class MapActivity extends BaseActivity mapboxMap.getMarkerViewManager().update(); } + + public void adjustMapToSearch(Integer zoom) { + MapUtils.setZoom(mapboxMap,zoom); + } } diff --git a/app/src/main/java/com/uam/wmi/findmytutor/activity/SettingsActivity.java b/app/src/main/java/com/uam/wmi/findmytutor/activity/SettingsActivity.java index 1758057..1b7a63d 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/activity/SettingsActivity.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/activity/SettingsActivity.java @@ -58,8 +58,6 @@ public class SettingsActivity extends AppCompatPreferenceActivity { languagesList.setDefaultValue(1); } - - languagesList.setOnPreferenceChangeListener((preference, newValue) -> { if (!newValue.toString().equals("0")){ diff --git a/app/src/main/java/com/uam/wmi/findmytutor/activity/SharingFragment.java b/app/src/main/java/com/uam/wmi/findmytutor/activity/SharingFragment.java index 56d342e..21d904f 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/activity/SharingFragment.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/activity/SharingFragment.java @@ -13,6 +13,7 @@ import android.view.View; import android.view.ViewGroup; import android.widget.Toast; +import com.annimon.stream.IntPair; import com.annimon.stream.Stream; import com.jakewharton.retrofit2.adapter.rxjava2.HttpException; import com.uam.wmi.findmytutor.R; @@ -65,12 +66,12 @@ public class SharingFragment extends PreferenceFragment { @Override public void onSuccess(List strings) { String[] statusesArray = strings.toArray(new String[strings.size()]); - setListPreferenceData(statusList.getKey(), statusesArray); + setListPreferenceData(statusList.getKey(), statusesArray,strings.size() -1); } @Override public void onError(Throwable e) { - Toast.makeText(getApplicationContext(), "Error handling status fetch", Toast.LENGTH_SHORT).show(); + Toast.makeText(getApplicationContext(), R.string.error_status_fetch, Toast.LENGTH_SHORT).show(); } })); @@ -87,14 +88,21 @@ public class SharingFragment extends PreferenceFragment { List names = Stream.of(coords).map(PredefinedCoordViewModel::getName).collect(com.annimon.stream.Collectors.toList()); predefinedCoordsList.addAll(coords); String[] stringnames = names.toArray(new String[0]); + String currentCoordId = PrefUtils.getCurrentManualLocation(getApplicationContext()); - setListPreferenceData(manualLocationList.getKey(), stringnames); + List activeId = Stream.of(coords).indexed() + .filter(v -> v.getSecond().getPredefinedCoordinateId().equals(currentCoordId)).map(IntPair::getFirst).toList(); + if(activeId.size() > 0) + setListPreferenceData(manualLocationList.getKey(), stringnames, activeId.get(0)); + else{ + setListPreferenceData(manualLocationList.getKey(), stringnames,null); + } } @Override public void onError(Throwable e) { - Toast.makeText(getApplicationContext(), "Error handling status fetch", Toast.LENGTH_SHORT).show(); + Toast.makeText(getApplicationContext(), R.string.manual_status_error, Toast.LENGTH_SHORT).show(); } })); @@ -161,13 +169,15 @@ public class SharingFragment extends PreferenceFragment { preferenceCategory.removePreference(manualLocationList); preferenceCategory.removePreference(manualLocationButton); } + /** Custom manual location list change listener **/ manualLocationList.setOnPreferenceChangeListener((preference, newValue) -> { ListPreference lp = (ListPreference) preference; - PredefinedCoordViewModel temp = Stream.of(predefinedCoordsList).filter(p -> p.getName().equals(lp.getEntries()[Integer.parseInt((String) newValue)].toString())).single(); + PredefinedCoordViewModel temp = Stream.of(predefinedCoordsList).filter(p -> p.getName().equals(lp.getEntries()[Integer.parseInt((String) newValue)].toString())).toList().get(0); - PrefUtils.putManualLocation(getApplicationContext(), temp.getGeoData()); + PrefUtils.putManualLocation(getApplicationContext(), temp.getGeoData(), temp.getApproximatedLocation() ); + PrefUtils.putCurrentManualLocation(getApplicationContext(),temp.getPredefinedCoordinateId()); return true; }); @@ -210,8 +220,7 @@ public class SharingFragment extends PreferenceFragment { return view; } - protected void setListPreferenceData(String lp_name, String[] entries) { - //todo bug z pustym statusem + protected void setListPreferenceData(String lp_name, String[] entries, Integer activeId) { ListPreference lp = (ListPreference) findPreference(lp_name); lp.setEntries(entries); CharSequence[] entryValues = new CharSequence[entries.length]; @@ -220,13 +229,17 @@ public class SharingFragment extends PreferenceFragment { entryValues[i] = Integer.toString(i); } - lp.setDefaultValue("0"); + lp.setDefaultValue(0); lp.setEntryValues(entryValues); - } + + if(entries.length > 0) + lp.setValueIndex(activeId); + }; private void handleResponse(List resp) { String[] statusesArray = resp.toArray(new String[resp.size()]); - setListPreferenceData(statusList.getKey(), statusesArray); + + setListPreferenceData(statusList.getKey(), statusesArray,resp.size() - 1); statusList.setValueIndex(resp.size() - 1); PrefUtils.storeStatus(getApplicationContext(), resp.get(resp.size() - 1)); diff --git a/app/src/main/java/com/uam/wmi/findmytutor/activity/TutorTab.java b/app/src/main/java/com/uam/wmi/findmytutor/activity/TutorTab.java index e3df91d..d98a4f5 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/activity/TutorTab.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/activity/TutorTab.java @@ -69,12 +69,10 @@ public class TutorTab extends AppCompatActivity { .subscribeWith(new DisposableSingleObserver() { @Override public void onSuccess(TutorTabViewModel tutorTabViewModel) { -// newTab = tutorTabViewModel; -// Log.d("TUTORTAB onsuc toPost",newTab.toString()); List dutyHoursList = Stream.of(tutorTabViewModel.getDutyHours()) .map(DutyHourViewModel::getSummary).toList(); - Log.d("TUTORTAB", Arrays.toString(dutyHoursList.toArray())); + userRoom.setText(String.format("%s: %s", getString(R.string.userRoom), tutorTabViewModel.getRoom())); userEmail.setText(String.format("%s: %s", getString(R.string.userEmail), tutorTabViewModel.getEmailTutorTab())); if (!tutorTabViewModel.getNote().equals("")) { @@ -115,10 +113,6 @@ public class TutorTab extends AppCompatActivity { @Override public void onClick(View view) { newTab = new TutorTabViewModel(PrefUtils.getUserId(getApplicationContext()),note.getText().toString()); - Log.d("TUTORTAB button",note.getText().toString()); - Log.d("TUTORTAB toPost",newTab.toString()); - //topost jest nullem -// toPost.setNote(note.getText().toString()); putUserTab(newTab); } }); @@ -147,7 +141,6 @@ public class TutorTab extends AppCompatActivity { } else { Toast.makeText(getApplicationContext(), "Network error " + error.getMessage(), Toast.LENGTH_SHORT).show(); - Log.d("FEEDBACK", error.getMessage()); } } @@ -158,7 +151,7 @@ public class TutorTab extends AppCompatActivity { ResponseBody responseBody = ((HttpException) e).response().errorBody(); message = RestApiHelper.getErrorMessage(responseBody); } else { - message = "Network Error !"; + message = "Network Error!"; } // Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG) diff --git a/app/src/main/java/com/uam/wmi/findmytutor/activity/UsersListFragment.java b/app/src/main/java/com/uam/wmi/findmytutor/activity/UsersListFragment.java index 433ed70..1f26899 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/activity/UsersListFragment.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/activity/UsersListFragment.java @@ -9,6 +9,7 @@ import android.support.v7.app.AlertDialog; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; +import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -31,9 +32,12 @@ import com.uam.wmi.findmytutor.utils.MyDividerItemDecoration; import com.uam.wmi.findmytutor.utils.RecyclerTouchListener; import com.uam.wmi.findmytutor.utils.RestApiHelper; +import java.text.Collator; +import java.text.Normalizer; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Locale; import butterknife.BindView; import butterknife.ButterKnife; @@ -61,6 +65,7 @@ public class UsersListFragment extends Fragment { private TutorsListAdapter mAdapter; private List tutorsList = new ArrayList<>(); private List tutorsFiltered = new ArrayList<>(); + private Collator plCollator = Collator.getInstance(Locale.forLanguageTag("pl-PL")); public UsersListFragment() { } @@ -108,6 +113,7 @@ public class UsersListFragment extends Fragment { } public void searchUser(String textToSearch) { + tutorsFiltered.clear(); tutorsFiltered.addAll(Stream.of(tutorsList).filter(t -> t.toSearchAbleString().toLowerCase().contains(textToSearch.toLowerCase())).toList()); @@ -212,7 +218,7 @@ public class UsersListFragment extends Fragment { private int sortByUserName(User t1, User t2) { - return t1.getFirstName().compareTo(t2.getFirstName()); + return plCollator.compare(t1.getLastName(),t2.getLastName()); } private void showError(Throwable e) { diff --git a/app/src/main/java/com/uam/wmi/findmytutor/model/Coordinate.java b/app/src/main/java/com/uam/wmi/findmytutor/model/Coordinate.java index 9b9d580..9fc2acf 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/model/Coordinate.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/model/Coordinate.java @@ -14,8 +14,8 @@ import io.swagger.annotations.ApiModelProperty; */ public class Coordinate extends BaseResponse { - Range latitudeRange = Range.create(52.466709, 52.467007); - Range longtitudeRange = Range.create(16.926159, 16.926976); + Range latitudeRange = Range.create(52.46598, 52.467545); + Range longtitudeRange = Range.create(16.926099, 16.927794); @SerializedName("coordinateId") private UUID coordinateId = null; @@ -45,8 +45,8 @@ public class Coordinate extends BaseResponse { private String label; public Coordinate (Double latitude, Double longitude, Double altitude, String approximatedLocation, String label, String userId, String displayMode) { - //if (!latitudeRange.contains(latitude)) throw new IllegalArgumentException("Inappropriate latitude value" + latitude); - //if (!longtitudeRange.contains(longitude)) throw new IllegalArgumentException("Inappropriate longitude value" + longitude); + if (!latitudeRange.contains(latitude)) throw new IllegalArgumentException("Inappropriate latitude value" + latitude); + if (!longtitudeRange.contains(longitude)) throw new IllegalArgumentException("Inappropriate longitude value" + longitude); //if (approximatedLocation == null) throw new IllegalArgumentException("Inappropriate approximatedLocation"); this.latitude = latitude; diff --git a/app/src/main/java/com/uam/wmi/findmytutor/model/Feedback.java b/app/src/main/java/com/uam/wmi/findmytutor/model/Feedback.java index 1726c75..5d438f8 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/model/Feedback.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/model/Feedback.java @@ -1,5 +1,5 @@ - package com.uam.wmi.findmytutor.model; + import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; @@ -8,18 +8,53 @@ public class Feedback { @SerializedName("isAnonymous") @Expose private Boolean isAnonymous; - @SerializedName("header") + @SerializedName("type") @Expose - private String header; + private String type; + @SerializedName("user") + @Expose + private String user; + @SerializedName("deviceOS") + @Expose + private String deviceOS; + @SerializedName("appVersion") + @Expose + private String appVersion; + @SerializedName("deviceModel") + @Expose + private String deviceModel; @SerializedName("body") @Expose private String body; - public Feedback(boolean isAnonymous, String header, String body){ + /** + * No args constructor for use in serialization + * + */ + public Feedback() { + } + + /** + * + * @param body + * @param appVersion + * @param deviceModel + * @param type + * @param isAnonymous + * @param user + * @param deviceOS + */ + public Feedback(Boolean isAnonymous, String type, String user, String deviceOS, String appVersion, String deviceModel, String body) { + super(); this.isAnonymous = isAnonymous; - this.header = header; + this.type = type; + this.user = user; + this.deviceOS = deviceOS; + this.appVersion = appVersion; + this.deviceModel = deviceModel; this.body = body; } + public Boolean getIsAnonymous() { return isAnonymous; } @@ -28,12 +63,74 @@ public class Feedback { this.isAnonymous = isAnonymous; } - public String getHeader() { - return header; + public Feedback withIsAnonymous(Boolean isAnonymous) { + this.isAnonymous = isAnonymous; + return this; } - public void setHeader(String header) { - this.header = header; + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Feedback withType(String type) { + this.type = type; + return this; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public Feedback withUser(String user) { + this.user = user; + return this; + } + + public String getDeviceOS() { + return deviceOS; + } + + public void setDeviceOS(String deviceOS) { + this.deviceOS = deviceOS; + } + + public Feedback withDeviceOS(String deviceOS) { + this.deviceOS = deviceOS; + return this; + } + + public String getAppVersion() { + return appVersion; + } + + public void setAppVersion(String appVersion) { + this.appVersion = appVersion; + } + + public Feedback withAppVersion(String appVersion) { + this.appVersion = appVersion; + return this; + } + + public String getDeviceModel() { + return deviceModel; + } + + public void setDeviceModel(String deviceModel) { + this.deviceModel = deviceModel; + } + + public Feedback withDeviceModel(String deviceModel) { + this.deviceModel = deviceModel; + return this; } public String getBody() { @@ -44,4 +141,38 @@ public class Feedback { this.body = body; } -} \ No newline at end of file + public Feedback withBody(String body) { + this.body = body; + return this; + } + + @Override + public String toString() { + return Boolean.toString(this.isAnonymous) + this.type + this.user+this.deviceOS+this.appVersion+this.deviceModel+this.body; + } + // @Override +// public String toString() { +// return new ToStringBuilder(this).append("isAnonymous", isAnonymous).append("type", type).append("user", user).append("deviceOS", deviceOS).append("appVersion", appVersion).append("deviceModel", deviceModel).append("body", body).toString(); +// } + +} + +// private Boolean isAnonymous; +// @SerializedName("type") +// @Expose +// private String type; +// @SerializedName("user") +// @Expose +// private String user; +// @SerializedName("deviceOS") +// @Expose +// private String deviceOS; +// @SerializedName("appVersion") +// @Expose +// private String appVersion; +// @SerializedName("deviceModel") +// @Expose +// private String deviceModel; +// @SerializedName("body") +// @Expose +// private String body; \ No newline at end of file diff --git a/app/src/main/java/com/uam/wmi/findmytutor/model/PredefinedCoordViewModel.java b/app/src/main/java/com/uam/wmi/findmytutor/model/PredefinedCoordViewModel.java index e881da6..1b5e71c 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/model/PredefinedCoordViewModel.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/model/PredefinedCoordViewModel.java @@ -8,7 +8,7 @@ public class PredefinedCoordViewModel { @SerializedName("predefinedCoordinateId") @Expose - private UUID predefinedCoordinateId; + private String predefinedCoordinateId; /** * * (Required) @@ -67,7 +67,6 @@ public class PredefinedCoordViewModel { * @param longitude * @param latitude * @param approximatedLocation - * @param predefinedCoordinateId */ public PredefinedCoordViewModel(Double latitude, Double longitude, Double altitude, String userId, String approximatedLocation, String displayMode, String name) { super(); @@ -80,11 +79,11 @@ public class PredefinedCoordViewModel { this.name = name; } - public UUID getPredefinedCoordinateId() { + public String getPredefinedCoordinateId() { return predefinedCoordinateId; } - public void setPredefinedCoordinateId(UUID predefinedCoordinateId) { + public void setPredefinedCoordinateId(String predefinedCoordinateId) { this.predefinedCoordinateId = predefinedCoordinateId; } diff --git a/app/src/main/java/com/uam/wmi/findmytutor/model/User.java b/app/src/main/java/com/uam/wmi/findmytutor/model/User.java index 7788f61..7363608 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/model/User.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/model/User.java @@ -701,23 +701,18 @@ public class User extends BaseResponse { return Objects.hash(isOnline, isUsingBlacklist, isUsingWhitelist, blacklist, whitelist, department, ldapLogin, title, firstName, lastName, isActive, tutorTab, coordinates, id, userName, normalizedUserName, email, normalizedEmail, emailConfirmed, passwordHash, securityStamp, concurrencyStamp, phoneNumber, phoneNumberConfirmed, twoFactorEnabled, lockoutEnd, lockoutEnabled, accessFailedCount); } - public String toSearchAbleString() { - StringBuilder sb = new StringBuilder(); - sb.append(getFirstName()).append(" "); - sb.append(getLastName()).append(" "); - sb.append(getDepartment()).append(" "); - sb.append(getEmail()); - return sb.toString(); + return getFirstName() + " " + + getLastName() + " " + + getDepartment() + " " + + getEmail(); } public String toSearchAbleUserName(){ - StringBuilder sb = new StringBuilder(); - sb.append(getFirstName()); - sb.append(getLastName()); - return sb.toString(); + return getFirstName() + + getLastName(); } diff --git a/app/src/main/java/com/uam/wmi/findmytutor/network/ApiClient.java b/app/src/main/java/com/uam/wmi/findmytutor/network/ApiClient.java index e95a240..74ba47f 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/network/ApiClient.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/network/ApiClient.java @@ -22,7 +22,7 @@ public class ApiClient { private static Retrofit retrofit = null; private static int REQUEST_TIMEOUT = 60; private static OkHttpClient okHttpClient; - private static final String BASE_URL = "https://s416084.projektstudencki.pl/develop/"; + private static final String BASE_URL = "https://s416084.projektstudencki.pl/master/"; public static Retrofit getClient(Context context) { @@ -51,24 +51,21 @@ public class ApiClient { httpClient.addInterceptor(interceptor); - httpClient.addInterceptor(new Interceptor() { - @Override - public Response intercept(Chain chain) throws IOException { - Request original = chain.request(); - Request.Builder requestBuilder = original.newBuilder() - .addHeader("Accept", "application/json") - .addHeader("Content-Type", "application/json"); + httpClient.addInterceptor(chain -> { + Request original = chain.request(); + Request.Builder requestBuilder = original.newBuilder() + .addHeader("Accept", "application/json") + .addHeader("Content-Type", "application/json"); - // Adding Authorization token (API Key) - // Requests will be denied without API key - if (!TextUtils.isEmpty(PrefUtils.getApiKey(context))) { - requestBuilder.addHeader("Authorization", "Bearer " + PrefUtils.getApiKey(context)); - } - - Request request = requestBuilder.build(); - return chain.proceed(request); + // Adding Authorization token (API Key) + // Requests will be denied without API key + if (!TextUtils.isEmpty(PrefUtils.getApiKey(context))) { + requestBuilder.addHeader("Authorization", "Bearer " + PrefUtils.getApiKey(context)); } + + Request request = requestBuilder.build(); + return chain.proceed(request); }); okHttpClient = httpClient.build(); diff --git a/app/src/main/java/com/uam/wmi/findmytutor/network/RetrofitClientInstance.java b/app/src/main/java/com/uam/wmi/findmytutor/network/RetrofitClientInstance.java deleted file mode 100644 index c59609b..0000000 --- a/app/src/main/java/com/uam/wmi/findmytutor/network/RetrofitClientInstance.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.uam.wmi.findmytutor.network; - -import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; - -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.logging.HttpLoggingInterceptor; -import retrofit2.Retrofit; -import retrofit2.converter.gson.GsonConverterFactory; - -public class RetrofitClientInstance { - - private static final String BASE_URL = "https://s416084.projektstudencki.pl/develop/"; - - private static Retrofit.Builder builder - = new Retrofit.Builder() - .baseUrl(BASE_URL) - .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) - .addConverterFactory(GsonConverterFactory.create()); - - private static Retrofit retrofit = builder.build(); - - private static OkHttpClient.Builder httpClient - = new OkHttpClient.Builder(); - - private static HttpLoggingInterceptor logging - = new HttpLoggingInterceptor() - .setLevel(HttpLoggingInterceptor.Level.BASIC); - - public static S createService(Class serviceClass) { - if (!httpClient.interceptors().contains(logging)) { - httpClient.addInterceptor(logging); - builder.client(httpClient.build()); - retrofit = builder.build(); - } - return retrofit.create(serviceClass); - } - - public static S createService(Class serviceClass, final String token) { - if (token != null) { - httpClient.interceptors().clear(); - httpClient.addInterceptor(chain -> { - Request original = chain.request(); - Request.Builder builder1 = original.newBuilder() - .header("Authorization", "Bearer " + token); - Request request = builder1.build(); - return chain.proceed(request); - }); - builder.client(httpClient.build()); - retrofit = builder.build(); - } - return retrofit.create(serviceClass); - } -} - diff --git a/app/src/main/java/com/uam/wmi/findmytutor/service/BackgroundLocalizationService.java b/app/src/main/java/com/uam/wmi/findmytutor/service/BackgroundLocalizationService.java index a510713..ec258c3 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/service/BackgroundLocalizationService.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/service/BackgroundLocalizationService.java @@ -34,11 +34,10 @@ import com.uam.wmi.findmytutor.utils.ApproximatedLocalization; import com.uam.wmi.findmytutor.utils.PrefUtils; import com.uam.wmi.findmytutor.utils.RestApiHelper; import com.uam.wmi.findmytutor.utils.SharingLevel; -import com.uam.wmi.findmytutor.utils.mapUtils; +import com.uam.wmi.findmytutor.utils.MapUtils; import java.util.ArrayList; import java.util.List; -import java.util.Timer; import java.util.TimerTask; import io.reactivex.android.schedulers.AndroidSchedulers; @@ -50,7 +49,7 @@ import timber.log.Timber; import static com.uam.wmi.findmytutor.utils.Consts.presenceApproximatedName; import static com.uam.wmi.findmytutor.utils.Consts.presenceLatitude; -import static com.uam.wmi.findmytutor.utils.Consts.presencelongitude; +import static com.uam.wmi.findmytutor.utils.Consts.presenceLongitude; import static com.uam.wmi.findmytutor.utils.PrefUtils.storeBackgroundLocationStatus; public class BackgroundLocalizationService extends Service { @@ -58,11 +57,11 @@ public class BackgroundLocalizationService extends Service { private static final String TAG = "MyLocationService"; private static final int LOCATION_INTERVAL = 1000; private static final float LOCATION_DISTANCE = 5f; + public static String str_receiver = "background.location.broadcast"; private static long notify_interval = 10000; Location mLastLocation; Boolean stopService = false; Intent intent; - public static String str_receiver = "background.location.broadcast"; ArrayList providers = new ArrayList(); LocationListener[] mLocationListeners; @@ -148,23 +147,22 @@ public class BackgroundLocalizationService extends Service { if (!stopService) { - Timer mTimer = new Timer(); - mTimer.schedule(new TimerTaskToGetLocation(), 20, notify_interval); - intent = new Intent(str_receiver); - fn_getlocation(); + mStatusChecker = () -> { + try { + fn_getlocation(); + } finally { + mHandler.postDelayed(mStatusChecker, notify_interval); + } + }; + + AsyncTask.execute(mStatusChecker); + } } - private class TimerTaskToGetLocation extends TimerTask { - @Override - public void run() { - mHandler.post(BackgroundLocalizationService.this::fn_getlocation); - } - } - @RequiresApi(api = Build.VERSION_CODES.O) private void startMyOwnForeground() { @@ -260,6 +258,13 @@ public class BackgroundLocalizationService extends Service { } } + private class TimerTaskToGetLocation extends TimerTask { + @Override + public void run() { + mHandler.post(BackgroundLocalizationService.this::fn_getlocation); + } + } + private class LocationListener implements android.location.LocationListener { public LocationListener(String provider) { @@ -291,7 +296,7 @@ public class BackgroundLocalizationService extends Service { @SuppressLint("StaticFieldLeak") private class Task extends AsyncTask { - ApproximatedLocalization approximatedLocalization; + private ApproximatedLocalization approximatedLocalization; private Double latitude; private Double longitude; private Double altitude; @@ -304,7 +309,7 @@ public class BackgroundLocalizationService extends Service { latitude = location.getLatitude(); longitude = location.getLongitude(); altitude = location.getAltitude(); - approximatedLocalization = new ApproximatedLocalization(mapUtils.loadJsonFromAsset(getApplicationContext(), "building.geojson")); + approximatedLocalization = new ApproximatedLocalization(MapUtils.loadJsonFromAsset(getApplicationContext(), "building.geojson")); approximatedBuildingPart = approximatedLocalization.getNameOfBuildingPart(Point.fromLngLat(longitude, latitude)); } @@ -315,7 +320,7 @@ public class BackgroundLocalizationService extends Service { if (locationLevel.equals(SharingLevel.PRESENCE.toString())) { latitude = presenceLatitude; - longitude = presencelongitude; + longitude = presenceLongitude; approximatedBuildingPart = presenceApproximatedName; } else if (locationLevel.equals(SharingLevel.APPROXIMATED.toString())) { List points = approximatedLocalization.getMiddlePointOfBuildingPart(approximatedBuildingPart); @@ -325,6 +330,7 @@ public class BackgroundLocalizationService extends Service { LatLng latLng = PrefUtils.getManualLocation(getApplicationContext()); latitude = latLng.getLatitude(); longitude = latLng.getLongitude(); + approximatedBuildingPart = PrefUtils.getManualLocationApproximation(getApplicationContext()); } try { diff --git a/app/src/main/java/com/uam/wmi/findmytutor/service/FeedbackService.java b/app/src/main/java/com/uam/wmi/findmytutor/service/FeedbackService.java index a6d166c..6461a19 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/service/FeedbackService.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/service/FeedbackService.java @@ -10,8 +10,8 @@ import retrofit2.http.POST; public interface FeedbackService { @POST("api/Feedback") - Observable> postFeedback(@Body Feedback feedback); + Observable postFeedback(@Body Feedback feedback); @GET("api/Feedback") - Single getFeedback(); + Observable getFeedback(); } diff --git a/app/src/main/java/com/uam/wmi/findmytutor/service/PredefinedStatusesService.java b/app/src/main/java/com/uam/wmi/findmytutor/service/PredefinedStatusesService.java index b52d79e..5af0c22 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/service/PredefinedStatusesService.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/service/PredefinedStatusesService.java @@ -22,7 +22,7 @@ public interface PredefinedStatusesService { Single> getUserPredefinedCoords(@Path("tutorId") String tutorId); @POST("api/users/predefined/coordinate/{tutorId}") - Single> postUserPredefinedCoord(@Path("tutorId") String tutorId, @Body PredefinedCoordViewModel coord); + Single postUserPredefinedCoord(@Path("tutorId") String tutorId, @Body PredefinedCoordViewModel coord); @DELETE("api/users/predefined/coordinate/{tutorId}") Single> deleteUserPredefinedCoord(@Path("tutorId") String tutorId, @Body PredefinedCoordViewModel coord); diff --git a/app/src/main/java/com/uam/wmi/findmytutor/utils/Consts.java b/app/src/main/java/com/uam/wmi/findmytutor/utils/Consts.java index bedd885..7f03193 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/utils/Consts.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/utils/Consts.java @@ -1,7 +1,14 @@ package com.uam.wmi.findmytutor.utils; +import android.util.Range; + public class Consts { - public final static Double presenceLatitude = 65.600244; - public final static Double presencelongitude = 480.032153; + public final static Integer deafultMapZoom = 17; + public final static Integer searchMapZoom = 13; + public final static Double presenceLatitude = 52.466365; + public final static Double presenceLongitude = 16.926792; public final static String presenceApproximatedName = "unknown"; + public final static Range latitudeRange = Range.create(52.466709, 52.467007); + public final static Range longtitudeRange = Range.create(16.926159, 16.926976); + } diff --git a/app/src/main/java/com/uam/wmi/findmytutor/utils/FeedbackUtils.java b/app/src/main/java/com/uam/wmi/findmytutor/utils/FeedbackUtils.java index ab12f54..17021d3 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/utils/FeedbackUtils.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/utils/FeedbackUtils.java @@ -30,6 +30,7 @@ import retrofit2.Response; public class FeedbackUtils { private Context activityContext; + AlertDialog.Builder alertDialogBuilderUserInput; public FeedbackUtils(Context context){ activityContext = context; } @@ -37,7 +38,7 @@ public class FeedbackUtils { LayoutInflater layoutInflaterAndroid = LayoutInflater.from(activityContext); View view = layoutInflaterAndroid.inflate(R.layout.feedback_modal, null); - AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(activityContext); + alertDialogBuilderUserInput = new AlertDialog.Builder(activityContext); alertDialogBuilderUserInput.setView(view).setPositiveButton(activityContext.getString(R.string.modal_feedback_send),null); final AlertDialog alertDialog = alertDialogBuilderUserInput.create(); @@ -77,31 +78,42 @@ public class FeedbackUtils { private void sendFeedback(String header, String body, boolean mode) { String appVersion = null; String metadata = null; + Feedback userFeedback= null; try { appVersion = activityContext.getPackageManager().getPackageInfo(activityContext.getPackageName(), 0).versionName; if( !mode ){ - metadata = "\n-----------------------------\n" + - "User ID: " + PrefUtils.getUserId(activityContext) + "\n" + - "Device OS: Android\n" + - "Device OS version: " + Build.VERSION.RELEASE + "\n" + - "App Version: " + appVersion + "\n" + - "Device Model: " + Build.MODEL + "\n" + - "Device Manufacturer: " + Build.MANUFACTURER + "\n" + - "-----------------------------\n"; - body = metadata + body; - header = header + " - " + PrefUtils.getUserFirstName(activityContext) + " " + PrefUtils.getUserLastName(activityContext); + body = PrefUtils.getUserFirstName(activityContext) + " " + PrefUtils.getUserLastName(activityContext) + "\n" + body; + userFeedback = new Feedback(mode, + header, + PrefUtils.getUserId(activityContext), + "Android "+ Build.VERSION.RELEASE, + appVersion, + Build.MODEL, + body); + Log.d("FEEDBACK non anon", userFeedback.toString()); + + }else{ + userFeedback = new Feedback(mode, + header, + "anonymous", + "Android "+ Build.VERSION.RELEASE, + appVersion, + Build.MODEL, + body); + Log.d("FEEDBACK anon",userFeedback.toString()); } } catch (PackageManager.NameNotFoundException e) { + } FeedbackService feedbackService = ApiClient.getClient(activityContext).create(FeedbackService.class); - Feedback userFeedback = new Feedback(mode,header,body); + CompositeDisposable disposable = new CompositeDisposable(); disposable.add(feedbackService.postFeedback(userFeedback) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::handleResponse, this::handleError)); } - private void handleResponse(Response resp) { + private void handleResponse( Void resp) { Toast.makeText(activityContext, activityContext.getString(R.string.modal_feedback_thankyou), Toast.LENGTH_SHORT).show(); } @@ -113,9 +125,9 @@ public class FeedbackUtils { RestApiHelper.getErrorMessage(responseBody), Toast.LENGTH_SHORT).show(); } else { - Toast.makeText(activityContext, - "Network error " + error.getMessage(), Toast.LENGTH_SHORT).show(); - Log.d("FEEDBACK",error.getMessage()); +// Toast.makeText(activityContext, +// "Network error " + error.getMessage(), Toast.LENGTH_SHORT).show(); + Log.d("FEEDBACK handerr ",error.getMessage()); } } } diff --git a/app/src/main/java/com/uam/wmi/findmytutor/utils/LocaleUtils.java b/app/src/main/java/com/uam/wmi/findmytutor/utils/LocaleUtils.java new file mode 100644 index 0000000..f4c15fb --- /dev/null +++ b/app/src/main/java/com/uam/wmi/findmytutor/utils/LocaleUtils.java @@ -0,0 +1,15 @@ +package com.uam.wmi.findmytutor.utils; + +import android.content.Context; +import android.os.Build; + +public class LocaleUtils { + public static String getCurrentLocale(Context context){ + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){ + return String.valueOf(context.getResources().getConfiguration().getLocales().get(0)); + } else{ + //noinspection deprecation + return String.valueOf(context.getResources().getConfiguration().locale); + } + } +} diff --git a/app/src/main/java/com/uam/wmi/findmytutor/utils/mapUtils.java b/app/src/main/java/com/uam/wmi/findmytutor/utils/MapUtils.java similarity index 71% rename from app/src/main/java/com/uam/wmi/findmytutor/utils/mapUtils.java rename to app/src/main/java/com/uam/wmi/findmytutor/utils/MapUtils.java index 79b9f01..c75b338 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/utils/mapUtils.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/utils/MapUtils.java @@ -3,6 +3,7 @@ package com.uam.wmi.findmytutor.utils; import android.animation.TypeEvaluator; import android.content.Context; import android.graphics.Color; +import android.location.Location; import android.view.Gravity; import android.view.View; import android.widget.FrameLayout; @@ -18,16 +19,20 @@ import com.mapbox.mapboxsdk.maps.MapView; import com.mapbox.mapboxsdk.maps.MapboxMap; import com.mapbox.mapboxsdk.style.layers.FillLayer; import com.mapbox.mapboxsdk.style.layers.Layer; +import com.uam.wmi.findmytutor.model.Coordinate; import java.io.IOException; import java.io.InputStream; -public class mapUtils { +import static com.uam.wmi.findmytutor.utils.Consts.latitudeRange; +import static com.uam.wmi.findmytutor.utils.Consts.longtitudeRange; + +public class MapUtils { // Boundires private static final LatLngBounds WMI_BOUNDS = new LatLngBounds.Builder() - .include(new LatLng(52.467886048833094, 16.92912980245876)) - .include(new LatLng(52.46548540224137, 16.925255680881094)) + .include(new LatLng(52.46588041661952, 16.92543089389801)) + .include(new LatLng(52.467824943492374, 16.928574442863464)) .build(); // Map Bounds Area @@ -38,43 +43,16 @@ public class mapUtils { mapboxMap.setLatLngBoundsForCameraTarget(WMI_BOUNDS); makeNewCamera(mapboxMap, 52.466799, 16.927002, 17, 0, 0, 4000); mapboxMap.setMinZoomPreference(16); // TODO export to map config - drawBoundsArea(context, mapboxMap, mapView, check); } else { mapboxMap.setLatLngBoundsForCameraTarget(null); mapboxMap.setMinZoomPreference(2); - drawBoundsArea(context, mapboxMap, mapView, check); } } - // TODO: remove b4 release - private static final PolygonOptions boundsArea = new PolygonOptions() - .add(WMI_BOUNDS.getNorthWest()) - .add(WMI_BOUNDS.getNorthEast()) - .add(WMI_BOUNDS.getSouthEast()) - .add(WMI_BOUNDS.getSouthWest()) - .alpha(0.1f) - .fillColor(Color.YELLOW); - // For adding and removing - private static Polygon polygon; - private static View crosshair; - - private static void drawBoundsArea(Context context, MapboxMap mapboxMap, MapView mapView, Boolean check) { - - - if (check) { - // Visualise bounds area - // showBoundsArea - polygon = mapboxMap.addPolygon(boundsArea); - // showCrosshair - crosshair = new View(context); - crosshair.setLayoutParams(new FrameLayout.LayoutParams(15, 15, Gravity.CENTER)); - crosshair.setBackgroundColor(Color.GREEN); - mapView.addView(crosshair); - } else { - mapboxMap.removePolygon(polygon); - mapView.removeView(crosshair); - } - + // Map Bounds Area + public static void setZoom(MapboxMap mapboxMap, Integer zoom) { + makeNewCamera(mapboxMap, 52.466799, 16.927002, zoom, 0, 0, 1000); + mapboxMap.setMinZoomPreference(16); // TODO export to map config } public static void makeNewCamera(MapboxMap mapboxMap, double lat, double lon, int zoomParam, int bearingParam, int tiltParam, int duration) { @@ -106,6 +84,10 @@ public class mapUtils { } } + public static Boolean checkIfCoordinateIsValid(Location coordinate){ + return (!latitudeRange.contains(coordinate.getLatitude()) && !longtitudeRange.contains(coordinate.getLongitude())); + } + // Function for marker animation public static class LatLngEvaluator implements TypeEvaluator { // Method is used to interpolate the marker animation. diff --git a/app/src/main/java/com/uam/wmi/findmytutor/utils/PrefUtils.java b/app/src/main/java/com/uam/wmi/findmytutor/utils/PrefUtils.java index ba253ce..b60ffbc 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/utils/PrefUtils.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/utils/PrefUtils.java @@ -144,7 +144,7 @@ public class PrefUtils { } public static String getLocale(Context context) { - return getSharedPreferences(context).getString("LOCALE", "en"); + return getSharedPreferences(context).getString("LOCALE", LocaleUtils.getCurrentLocale(context)); } public static Boolean isBackgroundLocationServiceRunning(Context context) { @@ -157,14 +157,14 @@ public class PrefUtils { editor.apply(); } - public static void putManualLocation(Context context, LatLng latLng) { + public static void putManualLocation(Context context, LatLng latLng, String approximatedLocation) { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putString("key_location_level","3"); editor.putString("location_mode", "manual"); + editor.putString("approx_manual_loc", approximatedLocation); editor.putBoolean("key_sharing_enabled", true); editor.putLong("longitude_manual_location", Double.doubleToRawLongBits(latLng.getLongitude())); editor.putLong("latitude_manual_location", Double.doubleToRawLongBits(latLng.getLatitude())); - Log.d("SAVE_COORD","zapisane"); editor.apply(); } @@ -175,4 +175,18 @@ public class PrefUtils { ); } + public static String getManualLocationApproximation(Context context) { + return getSharedPreferences(context).getString("approx_manual_loc", "unknown"); + } + + public static void putCurrentManualLocation(Context context,String manualId) { + SharedPreferences.Editor editor = getSharedPreferences(context).edit(); + editor.putString("current_manual_location", manualId); + editor.apply(); + } + + public static String getCurrentManualLocation(Context context) { + return getSharedPreferences(context).getString("current_manual_location", null); + } + } \ No newline at end of file diff --git a/app/src/main/java/com/uam/wmi/findmytutor/utils/RestApiHelper.java b/app/src/main/java/com/uam/wmi/findmytutor/utils/RestApiHelper.java index dc37d5c..ff60b3e 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/utils/RestApiHelper.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/utils/RestApiHelper.java @@ -23,7 +23,7 @@ public class RestApiHelper extends Activity { JSONObject jsonObject = new JSONObject(responseBody.string()); return jsonObject.getString("message"); } catch (Exception e) { - return e.getMessage(); + return "Something went wrong!"; } } diff --git a/app/src/main/res/layout/activity_login.xml b/app/src/main/res/layout/activity_login.xml index 3b298de..a48aee8 100644 --- a/app/src/main/res/layout/activity_login.xml +++ b/app/src/main/res/layout/activity_login.xml @@ -16,7 +16,7 @@ @@ -30,6 +30,7 @@ diff --git a/app/src/main/res/layout/activity_map.xml b/app/src/main/res/layout/activity_map.xml index e669303..5e5c5a2 100644 --- a/app/src/main/res/layout/activity_map.xml +++ b/app/src/main/res/layout/activity_map.xml @@ -58,47 +58,6 @@ app:fab_colorNormal="@color/mapboxGray" app:pressedTranslationZ="12dp" /> - - - - - - - - -