predefined status service linked to backend

This commit is contained in:
marcin.jedynski 2018-11-21 03:38:53 +01:00
parent d62c451adb
commit 662b8c29c4
9 changed files with 368 additions and 74 deletions

View File

@ -19,9 +19,15 @@ import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.jakewharton.retrofit2.adapter.rxjava2.HttpException;
import com.uam.wmi.findmytutor.R;
import com.uam.wmi.findmytutor.model.Feedback;
import com.uam.wmi.findmytutor.network.ApiClient;
import com.uam.wmi.findmytutor.service.BackgroundLocalizationService;
import com.uam.wmi.findmytutor.service.FeedbackService;
import com.uam.wmi.findmytutor.service.PredefinedStatusesService;
import com.uam.wmi.findmytutor.utils.PrefUtils;
import com.uam.wmi.findmytutor.utils.RestApiHelper;
import com.uam.wmi.findmytutor.utils.RightButtonPreference;
import java.util.Arrays;
@ -32,55 +38,84 @@ import java.util.Map;
import java.util.Objects;
import java.util.Set;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.DisposableSingleObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import retrofit2.Response;
import static com.mapbox.mapboxsdk.Mapbox.getApplicationContext;
public class SharingFragment extends PreferenceFragment {
private HashMap<Integer, String> locationLevelMapping;
// private HashMap<Integer, String> statusMapping;
private HashMap<Integer, String> statusMapping;
private PredefinedStatusesService statusesService;
private CompositeDisposable disposable;
protected Preference locationSharing;
protected Preference locationMode;
protected Preference manualLocationList;
protected PreferenceCategory preferenceCategory;
protected RightButtonPreference manualLocationButton;
protected Preference manualStatus;
protected ListPreference statusList;
void getStatuses(CompositeDisposable disposable){
disposable.add(statusesService.getUserPredefinedStatuses(PrefUtils.getUserId(getApplicationContext()))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableSingleObserver<List<String>>() {
@Override
public void onSuccess(List<String> strings) {
setListPreferenceData(statusList.getKey(),strings.toArray(new String[strings.size()]));
}
@Override
public void onError(Throwable e) {
Toast.makeText(getApplicationContext(), "Error handling status fetch", Toast.LENGTH_SHORT).show();
}
}));
}
@SuppressLint("ResourceType")
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.pref_sharing);
locationSharing = findPreference("key_sharing_enabled");
locationMode = findPreference("key_location_level");
preferenceCategory = (PreferenceCategory) findPreference("category_sharing");
manualLocationList = findPreference("key_manual_location_value");
manualLocationButton = (RightButtonPreference) findPreference("manual_location_button");
manualStatus = findPreference("key_manual_status");
statusList =(ListPreference) findPreference("key_status_value");
statusesService = ApiClient.getClient(getApplicationContext()).create(PredefinedStatusesService.class);
disposable = new CompositeDisposable();
getStatuses(disposable);
locationLevelMapping = new HashMap<Integer, String>();
locationLevelMapping.put(0,"presence");
locationLevelMapping.put(1,"approximated");
locationLevelMapping.put(2,"exact");
locationLevelMapping.put(3,"manual");
addPreferencesFromResource(R.layout.pref_sharing);
Preference manualStatus = findPreference("key_manual_status");
Preference locationSharing = findPreference("key_sharing_enabled");
Preference locationMode = findPreference("key_location_level");
Preference statusList = findPreference("key_status_value");
Preference manualLocationList = findPreference("key_manual_location_value");
RightButtonPreference manualLocationButton = (RightButtonPreference) findPreference("manual_location_button");
PreferenceCategory preferenceCategory = (PreferenceCategory) findPreference("category_sharing");
String temp = PrefUtils.getLocationLevel(getApplicationContext());
if(!temp.equals("manual")){
preferenceCategory.removePreference(manualLocationList);
preferenceCategory.removePreference(manualLocationButton);
}
manualLocationButton.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
//ToDO wywołanie wybierania lokalizacji z mapy
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.hide(SharingFragment.this);
fragmentTransaction.commit();
return true;
}
});
manualStatus.setOnPreferenceChangeListener((preference, newValue) -> {
ListPreference lp = (ListPreference) findPreference("key_status_value");
updateListPreference(lp, newValue, "manual_statuses");
PrefUtils.storeStatus(getApplicationContext(),(String) newValue);
statusMapping = new HashMap<Integer, String>();
statusMapping.put(0,"available");
statusMapping.put(1,"consultation");
statusMapping.put(2,"busy");
/** Main sharing switch**/
locationSharing.setOnPreferenceChangeListener((buttonView, newValue) -> {
PrefUtils.storeEnableSharingLocalization(getApplicationContext(), (Boolean) newValue);
((MapActivity)getActivity()).handleBackgroundTaskLifeCycle();
return true;
});
/** Sharing level list **/
locationMode.setOnPreferenceChangeListener((preference, newValue) -> {
ListPreference lp = (ListPreference) preference;
PrefUtils.storeLocationMode(getApplicationContext(),locationLevelMapping.get(Integer.parseInt((String) newValue)));
@ -95,16 +130,49 @@ public class SharingFragment extends PreferenceFragment {
return true;
});
/** Manual location category hiding when location level is != manual **/
if(!PrefUtils.getLocationLevel(getApplicationContext()).equals("manual")){
preferenceCategory.removePreference(manualLocationList);
preferenceCategory.removePreference(manualLocationButton);
}
/** Custom manual location list change listener **/
manualLocationList.setOnPreferenceChangeListener((preference, newValue) -> {
ListPreference lp = (ListPreference) preference;
//ToDo handle manual location change
return true;
});
/** Button 'choose from map' button listener **/
manualLocationButton.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
//ToDO wywołanie wybierania lokalizacji z mapy
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.hide(SharingFragment.this);
fragmentTransaction.commit();
return true;
}
});
/** Status list change listener **/
statusList.setOnPreferenceChangeListener((preference, newValue) -> {
ListPreference lp = (ListPreference) preference;
CharSequence [] entries = lp.getEntries();
PrefUtils.storeStatus(getApplicationContext(),(String) entries[Integer.parseInt((String) newValue)]);
// PrefUtils.storeStatus(getApplicationContext(),statusMapping.get(Integer.parseInt((String) newValue)));
return true;
});
/** Custom status list change listener **/
manualStatus.setOnPreferenceChangeListener((preference, newValue) -> {
// ListPreference lp = (ListPreference) findPreference("key_status_value");
// updateListPreference(lp, newValue, "manual_statuses");
// PrefUtils.storeStatus(getApplicationContext(),(String) newValue);
// statusList.setValue((String) newValue);
disposable.add(statusesService.postUserPredefinedStatus(PrefUtils.getUserId(getApplicationContext()),(String) newValue)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::handleResponse, this::handleError));
locationSharing.setOnPreferenceChangeListener((buttonView, newValue) -> {
PrefUtils.storeEnableSharingLocalization(getApplicationContext(), (Boolean) newValue);
((MapActivity)getActivity()).handleBackgroundTaskLifeCycle();
return true;
});
@ -136,8 +204,9 @@ public class SharingFragment extends PreferenceFragment {
Set <String> manualStatusSet = sharedPref.getStringSet(storageKey,defaultEntries);
manualStatusSet.add((String) newValue);
String [] manualStatusArr = manualStatusSet.toArray(new String[0]);
Arrays.sort(manualStatusArr);
//Arrays.sort(manualStatusArr);
setListPreferenceData(lp.getKey(),manualStatusArr);
// lp.setValue((String) newValue);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putStringSet(storageKey,manualStatusSet);
@ -145,6 +214,7 @@ public class SharingFragment extends PreferenceFragment {
}
protected void setListPreferenceData(String lp_name, String [] entries) {
//todo bug z pustym statusem
ListPreference lp = (ListPreference) findPreference(lp_name);
lp.setEntries(entries);
CharSequence[] entryValues = new CharSequence [entries.length];
@ -156,4 +226,27 @@ public class SharingFragment extends PreferenceFragment {
lp.setDefaultValue("1");
lp.setEntryValues(entryValues);
}
private void handleResponse(List<String> resp) {
getStatuses(disposable);
String newStatus = resp.toArray(new String[resp.size()])[resp.size()-1];
// Toast.makeText(getApplicationContext(), newStatus, Toast.LENGTH_SHORT).show();
statusList.setValue(Integer.toString(resp.size()-1));
statusList.setSummary(newStatus);
}
private void handleError(Throwable error) {
if (error instanceof HttpException) {
ResponseBody responseBody = ((HttpException) error).response().errorBody();
Toast.makeText(getApplicationContext(),
RestApiHelper.getErrorMessage(responseBody), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"Network error " + error.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("FEEDBACK",error.getMessage());
}
}
}

View File

@ -0,0 +1,187 @@
package com.uam.wmi.findmytutor.model;
import java.util.UUID;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class PredefinedCoordViewModel {
@SerializedName("predefinedCoordinateId")
@Expose
private UUID predefinedCoordinateId;
/**
*
* (Required)
*
*/
@SerializedName("latitude")
@Expose
private Double latitude;
/**
*
* (Required)
*
*/
@SerializedName("longitude")
@Expose
private Double longitude;
/**
*
* (Required)
*
*/
@SerializedName("altitude")
@Expose
private Double altitude;
/**
*
* (Required)
*
*/
@SerializedName("userId")
@Expose
private String userId;
@SerializedName("approximatedLocation")
@Expose
private String approximatedLocation;
@SerializedName("displayMode")
@Expose
private String displayMode = "predefined";
@SerializedName("label")
@Expose
private String label;
/**
* No args constructor for use in serialization
*
*/
public PredefinedCoordViewModel() {
}
/**
*
* @param altitude
* @param userId
* @param displayMode
* @param label
* @param longitude
* @param latitude
* @param approximatedLocation
* @param predefinedCoordinateId
*/
public PredefinedCoordViewModel(UUID predefinedCoordinateId, Double latitude, Double longitude, Double altitude, String userId, String approximatedLocation, String displayMode, String label) {
super();
this.predefinedCoordinateId = predefinedCoordinateId;
this.latitude = latitude;
this.longitude = longitude;
this.altitude = altitude;
this.userId = userId;
this.approximatedLocation = approximatedLocation;
this.displayMode = displayMode;
this.label = label;
}
public UUID getPredefinedCoordinateId() {
return predefinedCoordinateId;
}
public void setPredefinedCoordinateId(UUID predefinedCoordinateId) {
this.predefinedCoordinateId = predefinedCoordinateId;
}
/**
*
* (Required)
*
*/
public Double getLatitude() {
return latitude;
}
/**
*
* (Required)
*
*/
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
/**
*
* (Required)
*
*/
public Double getLongitude() {
return longitude;
}
/**
*
* (Required)
*
*/
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
/**
*
* (Required)
*
*/
public Double getAltitude() {
return altitude;
}
/**
*
* (Required)
*
*/
public void setAltitude(Double altitude) {
this.altitude = altitude;
}
/**
*
* (Required)
*
*/
public String getUserId() {
return userId;
}
/**
*
* (Required)
*
*/
public void setUserId(String userId) {
this.userId = userId;
}
public String getApproximatedLocation() {
return approximatedLocation;
}
public void setApproximatedLocation(String approximatedLocation) {
this.approximatedLocation = approximatedLocation;
}
public String getDisplayMode() {
return displayMode;
}
public void setDisplayMode(String displayMode) {
this.displayMode = displayMode;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
}

View File

@ -306,7 +306,7 @@ public class BackgroundLocalizationService extends Service {
latitude,
longitude,
altitude,
PrefUtils.getUserStatus(getApplicationContext()),
(PrefUtils.isStatusEnabled(getApplicationContext())) ? PrefUtils.getUserStatus(getApplicationContext()) : "",
PrefUtils.getUserId(getApplicationContext()),
PrefUtils.getLocationLevel(getApplicationContext())
);

View File

@ -0,0 +1,29 @@
package com.uam.wmi.findmytutor.service;
import com.uam.wmi.findmytutor.model.PredefinedCoordViewModel;
import java.util.List;
import io.reactivex.Single;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
public interface PredefinedStatusesService {
@GET("api/users/predefined/status/{tutorId}")
Single<List<String>> getUserPredefinedStatuses(@Path("tutorId") String tutorId);
@POST("api/users/predefined/status/{tutorId}")
Single<List<String>> postUserPredefinedStatus(@Path("tutorId") String tutorId, @Body String status);
@DELETE("api/users/predefined/status/{tutorId}")
Single<List<String>> deleteUserPredefinedStatus(@Path("tutorId") String tutorId, @Body String status);
@GET("api/users/predefined/coordinate/{tutorId}")
Single<List<PredefinedCoordViewModel>> getUserPredefinedCoords(@Path("tutorId") String tutorId);
@POST("api/users/predefined/coordinate/{tutorId}")
Single<List<PredefinedCoordViewModel>> postUserPredefinedCoord(@Path("tutorId") String tutorId, @Body PredefinedCoordViewModel coord);
@DELETE("api/users/predefined/coordinate/{tutorId}")
Single<List<PredefinedCoordViewModel>> deleteUserPredefinedCoord(@Path("tutorId") String tutorId, @Body PredefinedCoordViewModel coord);
}

View File

@ -54,6 +54,10 @@ public class PrefUtils {
return getSharedPreferences(context).getString("USER_ID", null);
}
public static boolean isStatusEnabled(Context context){
return getSharedPreferences(context).getBoolean("key_status_enabled",false);
}
public static String getUserStatus(Context context) {
return getSharedPreferences(context).getString("status_entry", "Available");
}

View File

@ -5,11 +5,8 @@ import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.uam.wmi.findmytutor.R;
import static com.mapbox.mapboxsdk.Mapbox.getApplicationContext;
public class RightButtonPreference extends Preference {
public RightButtonPreference(Context context, AttributeSet attrs) {
@ -30,11 +27,9 @@ public class RightButtonPreference extends Preference {
Button button = (Button)view.findViewById(R.id.button_choose_from_map);
if(button != null)
{
button.setText("dupa");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "dupa4", Toast.LENGTH_SHORT).show();
callChangeListener(null);
notifyChanged();
}

View File

@ -44,7 +44,7 @@
android:title="@string/status_switch_title"/>
<ListPreference
android:defaultValue="1"
android:key="key_status_value"
android:key="@string/key_status_value"
android:entries="@array/status_entries"
android:entryValues="@array/status_values"
android:summary="%s"

View File

@ -14,7 +14,7 @@
<string name="location_level_presence">Obecność</string>
<string name="location_level_approximated">Przybliżona</string>
<string name="location_level_precise">Dokładna</string>
<string name="settings_location_level">Sczegółowość udostępniania</string>
<string name="settings_location_level">Poziom udostępniania</string>
<string name="key_location_level">key_location_level</string>
<string name="settings_description">Opis</string>
<string name="key_description">key_description</string>
@ -116,7 +116,7 @@
<string name="userDutyHoursHeader"><b>Dyżury</b></string>
<string name="dutyHours"> <b>Dyżury</b></string>
<string name="userDepartment">Zakład</string>
<string name="loading">Loading</string>
<string name="loading">Ładowanie</string>
<string name="logo_find_my_tutor">Logo find my tutor</string>
<string name="prompt_login">Login (Ldap)</string>
<string name="action_log_in">Zaloguj!</string>
@ -130,6 +130,14 @@
<string name="navigation_item_feedback">Wyślij nam feedback</string>
<string name="navigation_item_bug">Zgłoś błąd</string>
<string name="fab_title_bound_area">Bounds OFF</string>
<string name="email_subject_feedback">Find My Tutor - feedback</string>
<string name="email_subject_bug">Find My Tutor - zgłoszenie błędu</string>
<string name="modal_feedback_hint">Proszę opisz swoje spostrzeżnia.</string>
<string name="modal_feedback_question">Wyślij anonimowo</string>
<string name="location_level_manual">Manualna</string>
<string name="preference_manual_location_button">Wybierz z mapy</string>
<string name="permission_denied_explanation">Odmowa dostępu</string>
<string name="permission_rationale">Uprawnienia powinny zostać przyznane.</string>
</resources>

View File

@ -44,7 +44,7 @@
<string name="action_white_list">White List</string>
<string name="title_activity_settings">Settings</string>
<string name="fmt_email">findmytutorwmi@gmail.com</string>
<string name="fmt_email" translatable="false">findmytutorwmi@gmail.com</string>
<!-- Strings related to SharingActivity -->
@ -68,6 +68,7 @@
<string name="key_location_level">key_location_level</string>
<string name="status_list_title">Choose status</string>
<string name="key_status_value">key_status_value</string>
<string name="status_switch_title">Status</string>
<string name="description_busy">Busy</string>
<string name="description_available">Available</string>
@ -175,7 +176,7 @@
<item quantity="other">%d locations reported</item>
</plurals>
<string name="title_activity_main2">Main2Activity</string>
<string name="title_activity_main2" translatable="false">Main2Activity</string>
<!--PulsingLayerOpacityColorActivity activity-->
<string name="fab_title_hotels">TODO</string>
@ -199,35 +200,12 @@
<string name="action_log_in">Log in </string>
<string name="user_list_nav">Users list</string>
<string name="error_invalid_login_name">Invalid login format.</string>
<string name="title_locale_utils">Locale utils</string>
<string name="title_locale_utils" translatable="false">Locale utils</string>
<string name="permission_denied_explanation">Permission denied</string>
<string name="permission_rationale">permission should be granted</string>
<string name="launch_activity" />
<string name="remove_location_updates" />
<string name="map_activity_label">MapActivity</string>
<string name="pref_title_social_recommendations">Enable social recommendations</string>
<string name="pref_description_social_recommendations">Recommendations for people to contact
based on your message history
</string>
<string name="pref_title_display_name">Display name</string>
<string name="pref_default_display_name">John Smith</string>
<string name="pref_title_add_friends_to_messages">Add friends to messages</string>
<string name="pref_title_sync_frequency">Sync frequency</string>
<string name="pref_title_system_sync_settings">System sync settings</string>
<!-- Example settings for Notifications -->
<string name="pref_header_notifications">Notifications</string>
<string name="pref_title_new_message_notifications">New message notifications</string>
<string name="pref_title_ringtone">Ringtone</string>
<string name="pref_ringtone_silent">Silent</string>
<string name="pref_title_vibrate">Vibrate</string>
<string name="permission_rationale" translatable="false">permission should be granted</string>
<string name="launch_activity" translatable="false" />
<string name="remove_location_updates" translatable="false" />
<string name="map_activity_label" translatable="false">MapActivity</string>
<string name="nav_profile">User profile</string>
</resources>