diff --git a/app/src/main/java/org/deke/risk/riskahead/MainActivity.java b/app/src/main/java/org/deke/risk/riskahead/MainActivity.java index 4ead9f6..1cf22b4 100644 --- a/app/src/main/java/org/deke/risk/riskahead/MainActivity.java +++ b/app/src/main/java/org/deke/risk/riskahead/MainActivity.java @@ -1,11 +1,15 @@ package org.deke.risk.riskahead; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.Context; import android.content.Intent; -import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.FragmentManager; +import android.support.v4.app.NotificationCompat; +import android.support.v4.app.TaskStackBuilder; import android.util.Log; import android.view.View; import android.widget.Button; @@ -15,7 +19,6 @@ import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; -import com.beardedhen.androidbootstrap.font.FontAwesome; import com.mikepenz.google_material_typeface_library.GoogleMaterial; import com.mikepenz.iconics.IconicsDrawable; @@ -23,9 +26,13 @@ import org.deke.risk.riskahead.helper.AppConfig; import org.deke.risk.riskahead.helper.AppController; import org.deke.risk.riskahead.helper.BaseActivity; import org.deke.risk.riskahead.helper.SessionManager; +import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; +import java.util.Calendar; import java.util.HashMap; import java.util.Map; @@ -87,10 +94,133 @@ public class MainActivity extends BaseActivity{ map.setCompoundDrawables(null,null, mapIcon, null); - + startNotifyTask(); } + Runnable mNotifyTask = new Runnable() + { + @Override + public void run() { + Log.d(this.toString(),"Run Notification Task"); + + myPosition = session.getLocation(); + if(myPosition != null){ + + String lastNotificationTime = ""; + + if(session.getLastNotification().equals("")){ + lastNotificationTime = getUser().get(SessionManager.KEY_LASTLOGIN_AT); + }else{ + lastNotificationTime = session.getLastNotification(); + } + + Log.d(this.toString(),"Lookup location with position: "+myPosition+" Radius: 15 lastNotifyTime: "+lastNotificationTime); + StringRequest strReq = getStringRequestIncidentsFromAreaAndTime(myPosition.latitude, myPosition.longitude, 15, lastNotificationTime); + String tag_string_req = "req_incidents"; + AppController.getInstance().addToRequestQueue(strReq, tag_string_req); + } + + mNotifyHandler.postDelayed(mNotifyTask, INTERVAL_NOTIFICATION); + } + }; + + public void startNotifyTask() + { + mNotifyTask.run(); + Log.d("BaseActivity","Start NotfiyTask"); + } + + public void stopNotifyTask() + { + mNotifyHandler.removeCallbacks(mNotifyTask); + Log.d("BaseActivity", "Stop NotfiyTask"); + } + + private StringRequest getStringRequestIncidentsFromAreaAndTime(final Double latitude, final Double longitude, final int radius, final String time) { + return new StringRequest(Request.Method.POST, AppConfig.URL_REGISTER, new Response.Listener() { + + @Override + public void onResponse(String response) { + Log.d(TAG, "Incident notifications: " + response); + + try { + JSONObject jObj = new JSONObject(response); + boolean error = jObj.getBoolean("error"); + + if (!error) { + JSONArray notification = jObj.getJSONArray("msg"); + + sentNotification(notification); + } else { + String errorMsg = jObj.getString("error_msg"); + Log.e(TAG, "Error getting incident notification (server returned error): " + errorMsg); + } + } catch (JSONException e) { + e.printStackTrace(); + } + + } + }, new Response.ErrorListener() { + + @Override + public void onErrorResponse(VolleyError error) { + Log.e(TAG, "Error getting incident notification: " + error.getMessage()); + showMessage(getString(R.string.errormsg_couldnotretrieve)); + stopNotifyTask(); + } + }) { + + @Override + protected Map getParams() { + Map params = new HashMap<>(); + params.put("tag", "getincidentsinareaandtime"); + params.put("uid", user.get(SessionManager.KEY_UID)); + params.put("token", user.get(SessionManager.TOKEN)); + params.put("latitude", Double.toString(latitude)); + params.put("longitude", Double.toString(longitude)); + params.put("radius", Integer.toString(radius)); + params.put("time", "'"+time+"'"); + return params; + } + }; + } + + private void sentNotification(JSONArray notification) { + NotificationCompat.Builder mBuilder = + new NotificationCompat.Builder(getApplicationContext()) + .setSmallIcon(R.drawable.logo_riskahead_header) + .setContentTitle("New incidents reported in your area!") + .setContentText(notification.length() + " new incidents near your last location. Watch out!"); + + NotificationManager mNotificationManager = + (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + + + Intent resultIntent = new Intent(this, MapsActivity.class); + try { + resultIntent.putExtra(EXTRA_MESSAGE, notification.getJSONObject(notification.length()-1).getDouble("latitude")+":"+notification.getJSONObject(notification.length()-1).getDouble("longitude")); + } catch (JSONException e) { + e.printStackTrace(); + } + + TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); + stackBuilder.addParentStack(MapsActivity.class); + + stackBuilder.addNextIntent(resultIntent); + PendingIntent resultPendingIntent = + stackBuilder.getPendingIntent( + 0, + PendingIntent.FLAG_UPDATE_CURRENT + ); + mBuilder.setContentIntent(resultPendingIntent); + + int mId = 1; + mNotificationManager.notify(mId, mBuilder.build()); + + session.setLastNotification(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime())); + + } @Override protected int getLayoutResourceId() { @@ -108,13 +238,20 @@ public class MainActivity extends BaseActivity{ stopRepeatingTask(); } + @Override + protected void onDestroy(){ + super.onDestroy(); + stopNotifyTask(); + } + @Override protected void onResume(){ super.onResume(); - result.setSelection(mainAvtivityID,false); + navDrawer.setSelection(mainAvtivityID,false); startRepeatingTask(); } + Runnable mHandlerTask = new Runnable() { @Override @@ -149,12 +286,12 @@ public class MainActivity extends BaseActivity{ if (!error) { JSONObject jCount = jObj.getJSONObject("msg"); - - count.setText(jCount.getString("total")); + DecimalFormat nf = new DecimalFormat(); + String decimalNumber = nf.format(jCount.getInt("total")); + count.setText(decimalNumber); } else { String errorMsg = jObj.getString("error_msg"); Log.e(TAG, "Error getting incident count (server returned error): " + errorMsg); - showMessage(errorMsg); } } catch (JSONException e) { e.printStackTrace(); diff --git a/app/src/main/java/org/deke/risk/riskahead/MapsActivity.java b/app/src/main/java/org/deke/risk/riskahead/MapsActivity.java index 8d9c2f6..c7f54c8 100644 --- a/app/src/main/java/org/deke/risk/riskahead/MapsActivity.java +++ b/app/src/main/java/org/deke/risk/riskahead/MapsActivity.java @@ -37,6 +37,7 @@ import com.google.android.gms.maps.model.TileOverlayOptions; import com.google.maps.android.clustering.Cluster; import com.google.maps.android.clustering.ClusterManager; import com.google.maps.android.heatmaps.HeatmapTileProvider; +import com.google.maps.android.heatmaps.WeightedLatLng; import org.deke.risk.riskahead.helper.IncidentReport; import org.deke.risk.riskahead.helper.AppConfig; @@ -51,7 +52,6 @@ import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; -import java.util.List; import java.util.Map; @@ -60,21 +60,17 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa private final static String mActivityTitle = "Risk Map"; private static final String TAG = MapsActivity.class.getSimpleName(); + private static final Double PRELOAD_PERCENTAGE = 0.3; private static GoogleMap mMap; private Marker mMarker; + private Marker markerShowingInfoWindow; private IncidentReport clickedClusterItem; - private ArrayList myMarkers = new ArrayList(); - private HashMap visibleMarkers = new HashMap(); - private List mHeatMapPositionList = new ArrayList<>(); - private ClusterManager mClusterManager; - TileOverlay mOverlay; - HeatmapTileProvider mProvider; - - private boolean isMarkerShown = false; + private TileOverlay mOverlay; + private HeatmapTileProvider mProvider; private LatLng myLocation; private LatLng markedLocation; @@ -82,19 +78,35 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa private static final int DEFAULT_ZOOM_LEVEL = 14; private static final int THRESHOLD_ZOOM_LEVEL = 7; + private static final int MIN_ZOOM_LEVEL = 5; + + private LatLng curNortheastBounds; + private LatLng curSouthwestBounds; + + + private boolean markersShown = false; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); userHasToBeLoggedIn(); + findViewById(R.id.btn_maps_confirm_position).setVisibility(View.GONE); + navDrawer.setSelection(mapAvtivityID, false); + + initMap(); + handleIntent(getIntent()); + initClustering(); + + findViewById(R.id.fab_reportwf_map).setVisibility(View.INVISIBLE); + + } + + private void initMap() { mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.frag_maps_map)).getMap(); mMap.getUiSettings().setZoomControlsEnabled(true); mMap.setMyLocationEnabled(true); - handleIntent(getIntent()); - - findViewById(R.id.btn_maps_confirm_position).setVisibility(View.GONE); - mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng point) { @@ -104,9 +116,9 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa markedLocation = point; mMarker = mMap.addMarker(new MarkerOptions().position(point)); mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(point, DEFAULT_ZOOM_LEVEL)); - findViewById(R.id.btn_maps_confirm_position).setVisibility(View.VISIBLE); + findViewById(R.id.fab_reportwf_map).setVisibility(View.VISIBLE); - findViewById(R.id.btn_maps_confirm_position).setOnClickListener(new View.OnClickListener() { + findViewById(R.id.fab_reportwf_map).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { gotoReportActivity(markedLocation.latitude + ":" + markedLocation.longitude); @@ -114,113 +126,334 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa }); } }); - - setUpClustering(); - result.setSelection(mapAvtivityID,false); } - public GoogleMap.OnCameraChangeListener getCameraChangeListener() - { + public GoogleMap.OnCameraChangeListener getCameraChangeListener() { return new GoogleMap.OnCameraChangeListener() { @Override public void onCameraChange(CameraPosition position) { mClusterManager.onCameraChange(position); - Log.d("Zoom", "Zoom: " + position.zoom); - if(position.zoom >= THRESHOLD_ZOOM_LEVEL) - { - isMarkerShown = true; - } else if (position.zoom < THRESHOLD_ZOOM_LEVEL && (isMarkerShown == true)){ - mClusterManager.clearItems(); - visibleMarkers.clear(); - isMarkerShown = false; + if(position.zoom < MIN_ZOOM_LEVEL) { + mMap.animateCamera(CameraUpdateFactory.zoomTo(MIN_ZOOM_LEVEL)); + return; } - addMarkersToMap(); + LatLngBounds bounds = mMap.getProjection().getVisibleRegion().latLngBounds; + Log.d("OnCameraChangeListener", "Position: "+bounds.getCenter()+" Zoom: "+position.zoom + " Bounds: NE:" + bounds.northeast + " SW: " + bounds.southwest); + Log.d("OnCameraChangeListener", "Saved Position - Bounds: NE:" + curNortheastBounds + " SW: " + curSouthwestBounds); + + boolean isOutOfBounds = false; + + double distanceLat = Math.abs(bounds.northeast.latitude - bounds.southwest.latitude); + double distanceLon = Math.abs(bounds.northeast.longitude - bounds.southwest.longitude); + + double southwestLat, southwestLng; + double northeastLat, northeastLng; + + if(bounds.southwest.latitude < bounds.northeast.latitude){ + southwestLat = bounds.southwest.latitude - distanceLat * PRELOAD_PERCENTAGE; + northeastLat = bounds.northeast.latitude + distanceLat * PRELOAD_PERCENTAGE; + + if((curSouthwestBounds != null) && ((bounds.southwest.latitude < curSouthwestBounds.latitude) || (bounds.northeast.latitude > curNortheastBounds.latitude))){ + isOutOfBounds = true; + } + } else { + southwestLat = bounds.southwest.latitude + distanceLat * PRELOAD_PERCENTAGE; + northeastLat = bounds.northeast.latitude - distanceLat * PRELOAD_PERCENTAGE; + + if((curSouthwestBounds != null) && ((bounds.southwest.latitude > curSouthwestBounds.latitude) || (bounds.northeast.latitude < curNortheastBounds.latitude))){ + isOutOfBounds = true; + } + } + + if(bounds.southwest.longitude < bounds.northeast.longitude){ + southwestLng = bounds.southwest.longitude - distanceLon * PRELOAD_PERCENTAGE; + northeastLng = bounds.northeast.longitude + distanceLon * PRELOAD_PERCENTAGE; + + if((curSouthwestBounds != null) && ((bounds.southwest.longitude < curSouthwestBounds.longitude) || (bounds.northeast.longitude > curNortheastBounds.longitude))){ + isOutOfBounds = true; + } + } else { + southwestLng = bounds.southwest.longitude + distanceLon * PRELOAD_PERCENTAGE; + northeastLng = bounds.northeast.longitude - distanceLon * PRELOAD_PERCENTAGE; + + if((curSouthwestBounds != null) && ((bounds.southwest.longitude > curSouthwestBounds.longitude) || (bounds.northeast.longitude < curNortheastBounds.longitude))){ + isOutOfBounds = true; + } + } + + if((curSouthwestBounds == null) || isOutOfBounds) { + curNortheastBounds = new LatLng(northeastLat, northeastLng); + curSouthwestBounds = new LatLng(southwestLat, southwestLng); + + Log.d("OnCameraChangeListener", "isOutOfBounds is true => New Calculated - Bounds: NE:" + curNortheastBounds + " SW: " + curSouthwestBounds); + + if (position.zoom >= THRESHOLD_ZOOM_LEVEL) { + refreshIncidentHeatMap(curNortheastBounds, curSouthwestBounds); + refreshIncidentMarkers(curNortheastBounds, curSouthwestBounds); + markersShown = true; + } else if (position.zoom < THRESHOLD_ZOOM_LEVEL) { + mClusterManager.clearItems(); + refreshIncidentHeatMap(curNortheastBounds, curSouthwestBounds); + markersShown = false; + } + } else if((isOutOfBounds == false) && ((position.zoom >= THRESHOLD_ZOOM_LEVEL) && (markersShown == false))){ + curNortheastBounds = new LatLng(northeastLat, northeastLng); + curSouthwestBounds = new LatLng(southwestLat, southwestLng); + + Log.d("OnCameraChangeListener", "zoom threshold passed => New Calculated - Bounds: NE:" + curNortheastBounds + " SW: " + curSouthwestBounds); + + refreshIncidentHeatMap(curNortheastBounds, curSouthwestBounds); + refreshIncidentMarkers(curNortheastBounds, curSouthwestBounds); + markersShown = true; + } else if((isOutOfBounds == false) && ((position.zoom < THRESHOLD_ZOOM_LEVEL) && (markersShown == true))){ + mClusterManager.clearItems(); + markersShown = false; + } } }; } - private void addMarkersToMap(){ - LatLngBounds bounds = mMap.getProjection().getVisibleRegion().latLngBounds; - mHeatMapPositionList.clear(); - Log.d("Zoom", "Bounds: NE:" + bounds.northeast +" SW: " + bounds.southwest); + private void refreshIncidentMarkers(LatLng northeast, LatLng southwest){ + String tag_string_req = "getincidentsfrombound"; + StringRequest strReq = getStringRequestGetAllIncidentsFromBound(northeast,southwest); + AppController.getInstance().addToRequestQueue(strReq, tag_string_req); + } - for(IncidentReport item : myMarkers) - { - if(bounds.contains(item.getPosition())) - { - mHeatMapPositionList.add(item.getPosition()); - //If the item isn't already being displayed - if(isMarkerShown && !visibleMarkers.containsKey(item.getId())) - { - mClusterManager.addItem(item); - mClusterManager.cluster(); + private void addIncidentMarkersOnMap(JSONArray incidents){ + mClusterManager.clearItems(); - visibleMarkers.put(item.getId(),item); - } - } else { - /* - //If the course was previously on screen - if(courseMarkers.containsKey(item.getId())) - { - //1. Remove the Marker from the GoogleMap - courseMarkers.get(item.getId()).remove(); - - //2. Remove the reference to the Marker from the HashMap - courseMarkers.remove(item.getId()); - } - */ + for(int i = 0; i < incidents.length();i++){ + try { + mClusterManager.addItem(new IncidentReport(incidents.getJSONObject(i))); + } catch (JSONException e) { + e.printStackTrace(); } } - if(!mHeatMapPositionList.isEmpty()) - { - mProvider.setData(mHeatMapPositionList); + + mClusterManager.cluster(); + } + + private void refreshIncidentHeatMap(LatLng northeast, LatLng southwest){ + String tag_string_req = "getincidentsforheatmapfrombound"; + StringRequest strReq = getStringRequestGetAllIncidentsForHeatMapFromBound(northeast, southwest); + AppController.getInstance().addToRequestQueue(strReq, tag_string_req); + } + + private void addIncidentMarkersOnHeatMap(JSONArray incidents){ + ArrayList heatMapPositions = new ArrayList<>(); + + for(int i = 0; i < incidents.length();i++){ + try { + heatMapPositions.add(new WeightedLatLng(new LatLng(incidents.getJSONObject(i).getDouble("latitude"), incidents.getJSONObject(i).getDouble("longitude")),1.0)); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + if(mProvider == null){ + mProvider = new HeatmapTileProvider.Builder() + .radius(50) + .weightedData(heatMapPositions) + .opacity(0.7) + .build(); + + + mOverlay = mMap.addTileOverlay(new TileOverlayOptions().tileProvider(mProvider)); + Log.d("HEATMAP", "HeatMap initialized"); + }else{ + mProvider.setWeightedData(heatMapPositions); mOverlay.clearTileCache(); + Log.d("HEATMAP", "HeatMap updated"); } } + private StringRequest getStringRequestGetAllIncidentsForHeatMapFromBound(final LatLng northeast, final LatLng southwest) { + return new StringRequest(Request.Method.POST, AppConfig.URL_REGISTER, new Response.Listener() { + @Override + public void onResponse(String response) { + Log.d(TAG, "Map HeatMap positions response: " + response); - private void setUpClustering() { + try { + JSONObject jObj = new JSONObject(response); + boolean error = jObj.getBoolean("error"); + + if (!error) { + JSONArray incidents = jObj.getJSONArray("msg"); + Log.d(TAG, "HeatMap positions response length: " + incidents .length()); + addIncidentMarkersOnHeatMap(incidents); + } else { + String errorMsg = jObj.getString("error_msg"); + Log.e(TAG, "Error getting map heat map positions (server returned error): " + errorMsg); + } + } catch (JSONException e) { + e.printStackTrace(); + } + + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + Log.e(TAG, "Error getting map positions: " + error.getMessage()); + showMessage(getString(R.string.errormsg_couldnotretrieve)); + } + }) { + @Override + protected Map getParams() { + Map params = new HashMap<>(); + params.put("tag", "getincidentsforheatmapfrombound"); + params.put("uid", user.get(SessionManager.KEY_UID)); + params.put("token", user.get(SessionManager.TOKEN)); + params.put("nelat", Double.toString(northeast.latitude)); + params.put("nelng", Double.toString(northeast.longitude)); + params.put("swlat", Double.toString(southwest.latitude)); + params.put("swlng", Double.toString(southwest.longitude)); + + return params; + } + }; + } + + private StringRequest getStringRequestGetAllIncidentsFromBound(final LatLng northeast, final LatLng southwest) { + return new StringRequest(Request.Method.POST, AppConfig.URL_REGISTER, new Response.Listener() { + + @Override + public void onResponse(String response) { + Log.d(TAG, "Map positions response: " + response); + + try { + JSONObject jObj = new JSONObject(response); + boolean error = jObj.getBoolean("error"); + + if (!error) { + JSONArray incidents = jObj.getJSONArray("msg"); + Log.d(TAG, "Map positions response length: " + incidents.length()); + addIncidentMarkersOnMap(incidents); + } else { + String errorMsg = jObj.getString("error_msg"); + Log.e(TAG, "Error getting map positions (server returned error): " + errorMsg); + } + } catch (JSONException e) { + e.printStackTrace(); + } + + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + Log.e(TAG, "Error getting map positions: " + error.getMessage()); + showMessage(getString(R.string.errormsg_couldnotretrieve)); + } + }) { + @Override + protected Map getParams() { + Map params = new HashMap<>(); + params.put("tag", "getincidentsfrombound"); + params.put("uid", user.get(SessionManager.KEY_UID)); + params.put("token", user.get(SessionManager.TOKEN)); + params.put("nelat", Double.toString(northeast.latitude)); + params.put("nelng", Double.toString(northeast.longitude)); + params.put("swlat", Double.toString(southwest.latitude)); + params.put("swlng", Double.toString(southwest.longitude)); + + return params; + } + }; + } + + private void initClustering() { mClusterManager = new ClusterManager(this, mMap); mMap.setOnCameraChangeListener(getCameraChangeListener()); - mClusterManager.setRenderer(new OwnIconRendered(MapsActivity.this,mMap,mClusterManager)); + mClusterManager.setRenderer(new OwnIconRendered(MapsActivity.this, mMap, mClusterManager)); mMap.setOnMarkerClickListener(mClusterManager); mMap.setOnInfoWindowClickListener(mClusterManager); mMap.setInfoWindowAdapter(mClusterManager.getMarkerManager()); mClusterManager.setOnClusterItemInfoWindowClickListener(this); - addClusterMarkers(mClusterManager); mClusterManager.setOnClusterClickListener(this); mClusterManager.setOnClusterItemClickListener(this); - mClusterManager - .setOnClusterItemClickListener(new ClusterManager.OnClusterItemClickListener() { - @Override - public boolean onClusterItemClick(IncidentReport item) { - clickedClusterItem = item; - return false; - } - }); + mClusterManager.setOnClusterItemClickListener(new ClusterManager.OnClusterItemClickListener() { + @Override + public boolean onClusterItemClick(IncidentReport item) { + clickedClusterItem = item; + return false; + } + }); mClusterManager.getMarkerCollection().setOnInfoWindowAdapter( new MyCustomAdapterForItems()); } - @Override - public boolean onClusterItemClick(IncidentReport incidentReport) { - return false; + private void loadInfoWindowInformation(View infoView, String incidentID){ + String tag_string_req = "getincidentscoreforinfowindow"; + StringRequest strReq = getStringRequestGetIncidentScoreForInfoWindow(infoView, incidentID); + AppController.getInstance().addToRequestQueue(strReq, tag_string_req); } - @Override - public boolean onClusterClick(Cluster cluster) { - return false; + private StringRequest getStringRequestGetIncidentScoreForInfoWindow(final View infoView, final String incidentID) { + return new StringRequest(Request.Method.POST, AppConfig.URL_REGISTER, new Response.Listener() { + + @Override + public void onResponse(String response) { + Log.d(TAG, "Map positions response: " + response); + + try { + JSONObject jObj = new JSONObject(response); + boolean error = jObj.getBoolean("error"); + + if (!error) { + JSONObject incident = jObj.getJSONObject("msg"); + clickedClusterItem = new IncidentReport(incident); + + TextView tvUsername = ((TextView) infoView.findViewById(R.id.txt_infowindow_fromuser)); + TextView tvScore = ((TextView) infoView.findViewById(R.id.txt_infowindow_points)); + RatingBar rbScore = ((RatingBar) infoView.findViewById(R.id.rb_infowindow_rating)); + + tvUsername.setText(getString(R.string.lbl_mapsinfowindow_author) + ": " + clickedClusterItem.getFromUsername()); + tvScore.setText(getString(R.string.lbl_mapsinfowindow_score) + ": " + String.valueOf(clickedClusterItem.getVotedScore())); + rbScore.setRating(clickedClusterItem.getScoreStars()); + + + if (markerShowingInfoWindow != null && markerShowingInfoWindow.isInfoWindowShown()) { + markerShowingInfoWindow.showInfoWindow(); + markerShowingInfoWindow = null; + } + } else { + String errorMsg = jObj.getString("error_msg"); + Log.e(TAG, "Error getting incident details (server returned error): " + errorMsg); + showMessage(errorMsg); + } + } catch (JSONException e) { + e.printStackTrace(); + } + + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + Log.e(TAG, "Error getting incident details: " + error.getMessage()); + showMessage(getString(R.string.errormsg_couldnotretrieve)); + } + }) { + @Override + protected Map getParams() { + Map params = new HashMap<>(); + params.put("tag", "getincidentfromincidentid"); + params.put("uid", user.get(SessionManager.KEY_UID)); + params.put("token", user.get(SessionManager.TOKEN)); + params.put("incidentid", incidentID); + + return params; + } + }; } public class MyCustomAdapterForItems implements GoogleMap.InfoWindowAdapter { @@ -228,17 +461,18 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa private final View myContentsView; MyCustomAdapterForItems() { - myContentsView = getLayoutInflater().inflate( - R.layout.map_info_window, null); + myContentsView = getLayoutInflater().inflate(R.layout.map_info_window, null); } @Override public View getInfoContents(Marker marker) { + markerShowingInfoWindow = marker; return null; } @Override public View getInfoWindow(Marker marker) { + markerShowingInfoWindow = marker; LinearLayout layCategoryColor = ((LinearLayout) myContentsView.findViewById(R.id.lay_infowindow_color)); TextView tvCategory = ((TextView) myContentsView.findViewById(R.id.txt_infowindow_category)); @@ -247,50 +481,22 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa TextView tvSuspect = ((TextView) myContentsView.findViewById(R.id.txt_infowindow_subject)); TextView tvTime = ((TextView) myContentsView.findViewById(R.id.txt_infowindow_time)); - TextView tvUsername = ((TextView) myContentsView.findViewById(R.id.txt_infowindow_fromuser)); - TextView tvScore = ((TextView) myContentsView.findViewById(R.id.txt_infowindow_points)); - RatingBar rbScore = ((RatingBar) myContentsView.findViewById(R.id.rb_infowindow_rating)); - if (clickedClusterItem != null) { + loadInfoWindowInformation(myContentsView, Integer.toString(clickedClusterItem.getId())); + layCategoryColor.setBackgroundColor(clickedClusterItem.getCategoryColor()); tvCategory.setText(clickedClusterItem.getIncidentCategoryName(getApplicationContext())); tvSubcategory.setText(clickedClusterItem.getIncidentSubCategoryName(getApplicationContext())); tvSuspect.setText(clickedClusterItem.getSuspectString(getApplicationContext())); - tvUsername.setText(getString(R.string.lbl_mapsinfowindow_author) + ": " + clickedClusterItem.getFromUsername()); - //TODO - //tvScore.setText(clickedClusterItem.getVotedScore()); - //tvVictim.setText(clickedClusterItem.getFidVictimCategory()); - //tvTime.setText(clickedClusterItem.getTimeString(getApplicationContext())); - //rbScore.setRating(clickedClusterItem.getScoreStars()); + tvVictim.setText(""); // TODO + tvTime.setText(clickedClusterItem.getTimeString(getApplicationContext())); } return myContentsView; } } - private void addClusterMarkers(ClusterManager mClusterManager) { - - String tag_string_req = "getincidentswithposition"; - StringRequest strReq = getStringRequestGetAllIncidentsWithPosition(); - AppController.getInstance().addToRequestQueue(strReq, tag_string_req); - } - - private void addHeatMap() { - mHeatMapPositionList.add(new LatLng(53.252151,10.422109)); - - mProvider = new HeatmapTileProvider.Builder() - .radius(50) - .data(mHeatMapPositionList) - .opacity(0.7) - .build(); - - - mOverlay = mMap.addTileOverlay(new TileOverlayOptions().tileProvider(mProvider)); - - addMarkersToMap(); - } - private void handleIntent(Intent intent){ if(Intent.ACTION_SEARCH.equals(intent.getAction())) { @@ -308,11 +514,32 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa String longitude = position[1]; LatLng point = new LatLng(Double.parseDouble(latitude),Double.parseDouble(longitude)); - mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(point, 12.0f)); + mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(point, DEFAULT_ZOOM_LEVEL)); + } else { + myPosition = session.getLocation(); + if (myPosition != null) + { + mMap.animateCamera(CameraUpdateFactory.newLatLngZoom( + new LatLng(myPosition.latitude, myPosition.longitude), DEFAULT_ZOOM_LEVEL)); + } } + } } + @Override + public boolean onClusterItemClick(IncidentReport incidentReport) { + return false; + } + + @Override + public boolean onClusterClick(Cluster cluster) { return false; } + + @Override + public void onClusterItemInfoWindowClick(IncidentReport incidentReport) { + gotoViewReportActivity(incidentReport.getId()); + } + @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); @@ -335,7 +562,8 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa private void showLocations(Cursor c){ MarkerOptions markerOptions; LatLng position = null; - mMap.clear(); + //mMap.clear(); + while(c.moveToNext()){ markerOptions = new MarkerOptions(); position = new LatLng(Double.parseDouble(c.getString(1)),Double.parseDouble(c.getString(2))); @@ -350,12 +578,11 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa if (position != null) { myLocation = new LatLng(position.latitude,position.longitude); } - mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation, 12.0f)); + mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation, DEFAULT_ZOOM_LEVEL)); } @Override - public void onLoaderReset(Loader arg0) { - } + public void onLoaderReset(Loader arg0) {} @Override public Loader onCreateLoader(int arg0, Bundle query) { @@ -391,6 +618,12 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa return true; } + @Override + protected void onPause(){ + super.onPause(); + showAd(); + } + @Override public void onDestroy() { if (mMap != null) { @@ -400,7 +633,6 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa super.onDestroy(); } - @Override protected int getLayoutResourceId() { return R.layout.activity_maps; @@ -410,68 +642,4 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa protected String getActivityName() { return mActivityTitle; } - - private StringRequest getStringRequestGetAllIncidentsWithPosition() { - showDialog(); - return new StringRequest(Request.Method.POST, AppConfig.URL_REGISTER, new Response.Listener() { - - @Override - public void onResponse(String response) { - Log.d(TAG, "Map positions response: " + response); - - try { - JSONObject jObj = new JSONObject(response); - boolean error = jObj.getBoolean("error"); - - if (!error) { - JSONArray incidents = jObj.getJSONArray("message"); - - for(int i=0;i getParams() { - Map params = new HashMap<>(); - params.put("tag", "getincidentswithpositionandscore"); - params.put("uid", user.get(SessionManager.KEY_UID)); - params.put("token", user.get(SessionManager.TOKEN)); - - return params; - } - }; - } - - @Override - public void onClusterItemInfoWindowClick(IncidentReport incidentReport) { - gotoViewReportActivity(incidentReport.getId()); - } - - @Override - protected void onPause(){ - super.onPause(); - showAd(); - } - } diff --git a/app/src/main/java/org/deke/risk/riskahead/ProfileActivity.java b/app/src/main/java/org/deke/risk/riskahead/ProfileActivity.java index 080d70f..6e612db 100644 --- a/app/src/main/java/org/deke/risk/riskahead/ProfileActivity.java +++ b/app/src/main/java/org/deke/risk/riskahead/ProfileActivity.java @@ -53,7 +53,7 @@ public class ProfileActivity extends BaseActivity{ @Override protected void onResume() { super.onResume(); - result.setSelection(userstatsAvtivityID, false); + navDrawer.setSelection(userstatsAvtivityID, false); } @Override diff --git a/app/src/main/java/org/deke/risk/riskahead/ReportWFActivity.java b/app/src/main/java/org/deke/risk/riskahead/ReportWFActivity.java index d409cec..fb1ed83 100644 --- a/app/src/main/java/org/deke/risk/riskahead/ReportWFActivity.java +++ b/app/src/main/java/org/deke/risk/riskahead/ReportWFActivity.java @@ -1,12 +1,15 @@ package org.deke.risk.riskahead; +import android.app.AlertDialog; import android.app.Fragment; import android.app.FragmentTransaction; +import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.location.Address; import android.location.Geocoder; import android.os.Bundle; +import android.support.design.widget.FloatingActionButton; import android.util.Log; import android.view.Menu; import android.view.MenuItem; @@ -38,9 +41,9 @@ import java.util.List; import java.util.Locale; import java.util.Map; -public class ReportWFActivity extends BaseActivity implements ReportWF_1_Fragment.OnInputFinishedListener, ReportWF_1_Fragment.OnCallMapListener, ReportWF_2_Fragment.OnInputFinishedListener, ReportWF_3_Fragment.OnInputFinishedListener { +public class ReportWFActivity extends BaseActivity implements ReportWF_1_Fragment.OnInputFinishedListener, ReportWF_2_Fragment.OnInputFinishedListener, ReportWF_3_Fragment.OnInputFinishedListener { - private final static String mActivityTitle = "Report NEW"; + private final static String mActivityTitle = "Report Incident"; private final static String TAG = ReportWFActivity.class.getSimpleName(); private List fragList = new ArrayList(); @@ -51,11 +54,17 @@ public class ReportWFActivity extends BaseActivity implements ReportWF_1_Fragmen private BootstrapButton btnContinue; private BootstrapButton btnReportNow; + private FloatingActionButton btnMap; private IncidentReport incident = new IncidentReport(); private int currentState = 0; + public boolean resetSignal = false; + + SharedPreferences mPrefs; + SharedPreferences.Editor prefsEditor; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -83,6 +92,22 @@ public class ReportWFActivity extends BaseActivity implements ReportWF_1_Fragmen reportIncident(incident); } }); + + btnMap = (FloatingActionButton) findViewById(R.id.fab_reportwf_map); + btnMap.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if(incident != null && incident.getPosition() != null){ + gotoMapActivity(incident.getPosition().latitude+":"+incident.getPosition().longitude); + }else { + gotoMapActivity(); + } + } + }); + + + mPrefs = getPreferences(MODE_PRIVATE); + prefsEditor = mPrefs.edit(); } private void reportIncident(IncidentReport incident){ @@ -91,6 +116,16 @@ public class ReportWFActivity extends BaseActivity implements ReportWF_1_Fragmen AppController.getInstance().addToRequestQueue(strReq, tag_string_req); } + private void resetStateAndIncident(){ + resetSignal = true; + currentState = 0; + incident = new IncidentReport(); + + prefsEditor.remove("incident"); + prefsEditor.remove("currentState"); + prefsEditor.commit(); + } + private void modifiyPos(String pos){ String[] position = pos.split(":"); Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault()); @@ -121,7 +156,9 @@ public class ReportWFActivity extends BaseActivity implements ReportWF_1_Fragmen } public void setIncident(IncidentReport newIncident){ - incident = newIncident; + if(resetSignal == false){ + incident = newIncident; + } } private void initFragment(int state) { @@ -175,42 +212,33 @@ public class ReportWFActivity extends BaseActivity implements ReportWF_1_Fragmen } @Override - public void onPause(){ - super.onPause(); + public void onStop(){ + super.onStop(); - SharedPreferences mPrefs = getPreferences(MODE_PRIVATE); - Gson gson = new Gson(); - - SharedPreferences.Editor prefsEditor = mPrefs.edit(); - - prefsEditor.putString("incident",gson.toJson(incident)); - prefsEditor.putInt("currentState", currentState); - prefsEditor.commit(); + if(resetSignal == false){ + Gson gson = new Gson(); + prefsEditor.putString("incident", gson.toJson(incident)); + prefsEditor.putInt("currentState", currentState); + prefsEditor.commit(); + } } @Override public void onResume(){ super.onResume(); - SharedPreferences mPrefs = getPreferences(MODE_PRIVATE); Gson gson = new Gson(); - if(!mPrefs.getString("incident", "").equals("")) incident = gson.fromJson(mPrefs.getString("incident", ""), IncidentReport.class); Intent intent = getIntent(); String pos = intent.getStringExtra(EXTRA_MESSAGE); + if(pos != null) modifiyPos(pos); currentState = mPrefs.getInt("currentState",0); if(currentState != 0) initFragment(currentState); - result.setSelection(reportAvtivityID, false); - } - - - @Override - public void onCallMap() { - gotoMapActivity(); + navDrawer.setSelection(reportAvtivityID, false); } @Override @@ -218,12 +246,39 @@ public class ReportWFActivity extends BaseActivity implements ReportWF_1_Fragmen int id = item.getItemId(); if((id == R.id.menu_btn_gotostart)){ - initFragment(0); + new AlertDialog.Builder(ReportWFActivity.this) + .setTitle("New Incident?") + .setMessage("Reset everything?") + .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + resetStateAndIncident(); + + initFragment(0); + } + }) + .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + // do nothing + } + }) + .setIcon(android.R.drawable.ic_dialog_alert) + .show(); + + + } return super.onOptionsItemSelected(item); } + public void setMapButtonVisibility(boolean isVisible){ + if(isVisible){ + btnMap.setVisibility(View.VISIBLE); + }else{ + btnMap.setVisibility(View.INVISIBLE); + } + + } private StringRequest getStringRequestAddIncidentWithPosition(final IncidentReport incident) { showDialog(); @@ -239,13 +294,13 @@ public class ReportWFActivity extends BaseActivity implements ReportWF_1_Fragmen if (!error) { showMessage("Report added!"); - SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); - editor.clear().commit(); - + LatLng gotoPosition = new LatLng(incident.getPosition().latitude,incident.getPosition().longitude); + resetStateAndIncident(); showAd(); - gotoMapActivity(incident.getPosition().latitude+":"+incident.getPosition().longitude); + + gotoMapActivity(gotoPosition.latitude+":"+gotoPosition.longitude); } else { String errorMsg = jObj.getString("error_msg"); Log.e(TAG, "Error adding incident (Server returned error): " + errorMsg); @@ -270,6 +325,33 @@ public class ReportWFActivity extends BaseActivity implements ReportWF_1_Fragmen params.put("tag", "addincidentwithposition"); params.put("uid", user.get(SessionManager.KEY_UID)); params.put("token", user.get(SessionManager.TOKEN)); + params.put("latitude", Double.toString(incident.getPosition().latitude)); + params.put("longitude", Double.toString(incident.getPosition().longitude)); + params.put("fid_incident", Integer.toString(incident.getFidIncidentCategory())); + params.put("fid_subincident", Integer.toString(incident.getFidIncidentSubCategory())); + params.put("etc_incident", incident.getEtcIncidentCategory()); + params.put("fid_time", Integer.toString(incident.getFidTimeCategory())); + params.put("fid_subtime", Integer.toString(incident.getFidTimeSubCategory())); + params.put("happened_from_datetime", incident.getFromDate()+" "+incident.getFromTime()); + params.put("happened_to_datetime", incident.getToDate()+" "+incident.getToTime()); + params.put("fid_suspect", Integer.toString(incident.getFidSuspectCategory())); + params.put("fid_subsuspect", Integer.toString(incident.getFidSuspectSubCategory())); + params.put("fid_weapon", Integer.toString(incident.getFidSuspectWeaponCategory())); + params.put("fid_subweapon", Integer.toString(incident.getFidSuspectWeaponSubCategory())); + params.put("etc_weapon", incident.getEtcSuspectWeaponCategory()); + params.put("fid_suspectcount", Integer.toString(incident.getFidSuspectCountCategory())); + params.put("etc_suspectcount", incident.getEtcSuspectCountCategory()); + params.put("fid_victim", Integer.toString(incident.getFidVictimCategory())); + params.put("fid_victimorigin", Integer.toString(incident.getFidVictimOriginCategory())); + params.put("etc_victimorigin", incident.getEtcVictimOriginCategory()); + params.put("fid_suspecttransportation", Integer.toString(incident.getFidSuspectTransportationCategory())); + params.put("etc_suspecttransportation", incident.getEtcSuspectTransportationCategory()); + params.put("fid_victimbelonging", Integer.toString(incident.getFidVictimBelongingCategory())); + params.put("etc_victimbelonging", incident.getEtcVictimBelongingCategory()); + params.put("fid_suspectcharacteristics", Integer.toString(incident.getFidSuspectCharacteristicsCategory())); + params.put("etc_suspectcharacteristics", incident.getEtcSuspectCharacteristicsCategory()); + params.put("fid_others", Integer.toString(incident.getFidOthersCategory())); + params.put("etc_others", incident.getEtcOthersCategory()); return params; } diff --git a/app/src/main/java/org/deke/risk/riskahead/SettingsActivity.java b/app/src/main/java/org/deke/risk/riskahead/SettingsActivity.java index 53e3a93..eaa4ea0 100644 --- a/app/src/main/java/org/deke/risk/riskahead/SettingsActivity.java +++ b/app/src/main/java/org/deke/risk/riskahead/SettingsActivity.java @@ -7,7 +7,6 @@ import android.util.Log; import android.util.Patterns; import android.view.View; import android.widget.TextView; -import android.widget.Toast; import com.android.volley.Request; import com.android.volley.Response; @@ -144,7 +143,7 @@ public class SettingsActivity extends BaseActivity { @Override protected void onResume() { super.onResume(); - result.setSelection(settingsAvtivityID,false); + navDrawer.setSelection(settingsAvtivityID,false); } @Override diff --git a/app/src/main/java/org/deke/risk/riskahead/SubscriptionsActivity.java b/app/src/main/java/org/deke/risk/riskahead/SubscriptionsActivity.java index 8a47c12..ac01f2d 100644 --- a/app/src/main/java/org/deke/risk/riskahead/SubscriptionsActivity.java +++ b/app/src/main/java/org/deke/risk/riskahead/SubscriptionsActivity.java @@ -19,7 +19,7 @@ public class SubscriptionsActivity extends BaseActivity { @Override protected void onResume() { super.onResume(); - result.setSelection(subscriptionsAvtivityID,false); + navDrawer.setSelection(subscriptionsAvtivityID,false); } @Override diff --git a/app/src/main/java/org/deke/risk/riskahead/ViewReportActivity.java b/app/src/main/java/org/deke/risk/riskahead/ViewReportActivity.java index 79ddf9a..b2a1723 100644 --- a/app/src/main/java/org/deke/risk/riskahead/ViewReportActivity.java +++ b/app/src/main/java/org/deke/risk/riskahead/ViewReportActivity.java @@ -20,6 +20,7 @@ import com.beardedhen.androidbootstrap.BootstrapLabel; import org.deke.risk.riskahead.helper.AppConfig; import org.deke.risk.riskahead.helper.AppController; import org.deke.risk.riskahead.helper.BaseActivity; +import org.deke.risk.riskahead.helper.IncidentReport; import org.deke.risk.riskahead.helper.SessionManager; import org.json.JSONException; import org.json.JSONObject; @@ -35,14 +36,12 @@ public class ViewReportActivity extends BaseActivity { private final static String mActivityTitle = "ViewReport"; private final static String TAG = ViewReportActivity.class.getSimpleName(); - private EditText txtTitle; - private EditText txtDescription; - private EditText txtCrimeCategory; - private EditText txtPosition; - private EditText txtDate; - private EditText txtTime; - private TextView txtPositionDetail; + private EditText txtIncidentCategory; + private EditText txtIncidentSubCategory; + private TextView txtPosition; + private BootstrapLabel scorelabel; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -51,13 +50,9 @@ public class ViewReportActivity extends BaseActivity { Intent intent = getIntent(); final Integer uid = intent.getIntExtra(BaseActivity.EXTRA_MESSAGE, 0); - txtTitle = (EditText) findViewById(R.id.input_viewreport_short); - txtDescription = (EditText) findViewById(R.id.input_viewreport_long); - txtCrimeCategory = (EditText) findViewById(R.id.input_viewreport_category); - txtDate = (EditText) findViewById(R.id.input_viewreport_date); - txtTime = (EditText) findViewById(R.id.input_viewreport_time); - txtPosition = (EditText) findViewById(R.id.input_viewreport_position); - txtPositionDetail = (TextView) findViewById(R.id.lbl_viewreport_position_detail); + txtIncidentCategory = (EditText) findViewById(R.id.txt_viewreport_incidentcategory); + txtIncidentSubCategory = (EditText) findViewById(R.id.txt_viewreport_incidentsubcategory); + txtPosition = (TextView) findViewById(R.id.txt_viewreport_position); scorelabel = (BootstrapLabel) findViewById(R.id.txt_viewreport_points); getIncident(uid); @@ -175,7 +170,6 @@ public class ViewReportActivity extends BaseActivity { }; } - private StringRequest getStringRequestGetIncidentWithPositionFromID(final Integer incidentid) { showDialog(); return new StringRequest(Request.Method.POST, AppConfig.URL_REGISTER, new Response.Listener() { @@ -190,54 +184,10 @@ public class ViewReportActivity extends BaseActivity { boolean error = jObj.getBoolean("error"); if (!error) { - JSONObject incident = jObj.getJSONArray("message").getJSONObject(0); + JSONObject jIncident = jObj.getJSONObject("msg"); + IncidentReport incident = new IncidentReport(jIncident); - txtTitle.setText(incident.getString("text_short")); - txtDescription.setText(incident.getString("text_long")); - txtCrimeCategory.setText(incident.getString("cat_name")); - - scorelabel.setText(jObj.getString("score")); - - String[] happened_at = incident.getString("happened_at").split(" "); - txtDate.setText(happened_at[0]); - txtTime.setText(happened_at[1].substring(0, 5)); - - Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault()); - - try { - List
addressList = geocoder.getFromLocation(incident.getDouble("latitude"), incident.getDouble("longitude"), 1); - if (addressList != null && addressList.size() > 0) { - Address address = addressList.get(0); - StringBuilder sb = new StringBuilder(); - - for (int i = 0; i < address.getMaxAddressLineIndex(); i++) { - if(address.getAddressLine(i) != null) sb.append(address.getAddressLine(i)).append("\n"); - } - - //if(address.getLocality() != null) sb.append(address.getLocality()).append("\n"); - //if(address.getPostalCode() != null) sb.append(address.getPostalCode()).append("\n"); - if(address.getCountryName() != null) sb.append(address.getCountryName()); - - txtPosition.setText(address.getLocality()); - txtPositionDetail.setText(sb.toString()); - } - } catch (IOException e) { - e.printStackTrace(); - } - - final String latitude = incident.getString("latitude"); - final String longitude = incident.getString("longitude"); - - findViewById(R.id.btn_viewreport_position).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - gotoMapActivity(latitude + ":" + longitude); - } - }); - - if(!incident.getString("fid_user").equals(user.get("uid"))){ - findViewById(R.id.layoutFooter).setVisibility(View.GONE); - } + initReport(incident); } else { String errorMsg = jObj.getString("error_msg"); @@ -262,7 +212,7 @@ public class ViewReportActivity extends BaseActivity { protected Map getParams() { // Posting parameters to login url Map params = new HashMap<>(); - params.put("tag", "getincidentfromid"); + params.put("tag", "getincidentfromincidentid"); params.put("uid", user.get(SessionManager.KEY_UID)); params.put("token", user.get(SessionManager.TOKEN)); params.put("incidentid", incidentid.toString()); @@ -274,6 +224,47 @@ public class ViewReportActivity extends BaseActivity { }; } + private void initReport(IncidentReport incident) { + scorelabel.setText(Integer.toString(incident.getVotedScore())); + txtIncidentCategory.setText(incident.getIncidentCategoryName(getApplicationContext())); + txtIncidentSubCategory.setText(incident.getIncidentSubCategoryName(getApplicationContext())); + + Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault()); + + try { + List
addressList = geocoder.getFromLocation(incident.getPosition().latitude,incident.getPosition().longitude, 1); + if (addressList != null && addressList.size() > 0) { + Address address = addressList.get(0); + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < address.getMaxAddressLineIndex(); i++) { + if(address.getAddressLine(i) != null) sb.append(address.getAddressLine(i)).append("\n"); + } + + if(address.getCountryName() != null) sb.append(address.getCountryName()); + + txtPosition.setText(sb.toString()); + } + } catch (IOException e) { + e.printStackTrace(); + } + + final String latitude = Double.toString(incident.getPosition().latitude); + final String longitude = Double.toString(incident.getPosition().longitude); + + findViewById(R.id.btn_viewreport_position).setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + gotoMapActivity(latitude + ":" + longitude); + } + }); + + String test = user.get(SessionManager.KEY_UID); + if(incident.getFidFromUser() != Integer.valueOf(test)){ + findViewById(R.id.layoutFooter).setVisibility(View.GONE); + } + } + public void makeUpvote(Integer uid) { String tag_string_req = "addvote"; StringRequest strReq = getStringRequestAddVote(uid, "1"); @@ -300,10 +291,10 @@ public class ViewReportActivity extends BaseActivity { if (!error) { showMessage("Voted! Score updated."); - BootstrapLabel scorelabel = (BootstrapLabel) findViewById(R.id.txt_viewreport_points); - scorelabel.setText(jObj.getString("points")); - showAd(); + JSONObject jPoints = jObj.getJSONObject("points"); + scorelabel.setText(Integer.toString(jPoints.getInt("upvoted")-jPoints.getInt("downvoted"))); + showAd(); } else { String errorMsg = jObj.getString("error_msg"); Log.e(TAG, "Error voting incident (Server returned error): " + errorMsg); diff --git a/app/src/main/java/org/deke/risk/riskahead/fragment/ProfileStatisticsFragment.java b/app/src/main/java/org/deke/risk/riskahead/fragment/ProfileStatisticsFragment.java index e0d8b92..01b3de0 100644 --- a/app/src/main/java/org/deke/risk/riskahead/fragment/ProfileStatisticsFragment.java +++ b/app/src/main/java/org/deke/risk/riskahead/fragment/ProfileStatisticsFragment.java @@ -35,16 +35,30 @@ public class ProfileStatisticsFragment extends Fragment { private View view; private ProfileActivity parent; + TextView points ; + TextView ranking ; + TextView posts ; + TextView txtMemberSince ; + @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_profile_stats, container, false); parent = (ProfileActivity)getActivity(); + points = (TextView) view.findViewById(R.id.txt_profile_points); + ranking = (TextView) view.findViewById(R.id.txt_profile_ranking); + posts = (TextView) view.findViewById(R.id.txt_profile_numberposts); + txtMemberSince = (TextView) view.findViewById(R.id.txt_profile_membersince); + + getProfileStatsForList(); + + return view; + } + + private void getProfileStatsForList() { StringRequest strReq = getStringRequestProfileStats(); String tag_string_req = "req_profilestats"; AppController.getInstance().addToRequestQueue(strReq, tag_string_req); - - return view; } private StringRequest getStringRequestProfileStats() { @@ -58,15 +72,12 @@ public class ProfileStatisticsFragment extends Fragment { JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); if (!error) { - TextView points = (TextView) view.findViewById(R.id.txt_profile_points); - TextView ranking = (TextView) view.findViewById(R.id.txt_profile_ranking); - TextView posts = (TextView) view.findViewById(R.id.txt_profile_numberposts); - TextView txtMemberSince = (TextView) view.findViewById(R.id.txt_profile_membersince); + jObj = jObj.getJSONObject("msg"); points.setText(jObj.getString("points")); ranking.setText(jObj.getString("rank")); - posts.setText(jObj.getString("posts")); + posts.setText(jObj.getString("numberOfPosts")); txtMemberSince.setText(parent.user.get("created_at")); } else { String errorMsg = jObj.getString("error_msg"); @@ -88,7 +99,6 @@ public class ProfileStatisticsFragment extends Fragment { @Override protected Map getParams() { - // Posting params to register url Map params = new HashMap<>(); params.put("tag", "getuserstats"); params.put("uid", parent.user.get(SessionManager.KEY_UID)); diff --git a/app/src/main/java/org/deke/risk/riskahead/fragment/ReportListFragment.java b/app/src/main/java/org/deke/risk/riskahead/fragment/ReportListFragment.java index 0b1364c..cc07c08 100644 --- a/app/src/main/java/org/deke/risk/riskahead/fragment/ReportListFragment.java +++ b/app/src/main/java/org/deke/risk/riskahead/fragment/ReportListFragment.java @@ -48,12 +48,10 @@ public class ReportListFragment extends Fragment{ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_reportlist, container, false); parent = (ProfileActivity)getActivity(); - Log.d(TAG,"ReportListActivated!"); + myListView = (ListView) view.findViewById(R.id.lv_reportlist_list); - String tag_string_req = "getincidentswithpositionfromid"; - StringRequest strReq = getStringRequestGetIncidentsWithPositionFromUserID(); - AppController.getInstance().addToRequestQueue(strReq, tag_string_req); + if(resultList == null || resultList.size() == 0) getIncidentsForList(); myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override @@ -65,25 +63,29 @@ public class ReportListFragment extends Fragment{ } } }); + return view; } + private void getIncidentsForList() { + String tag_string_req = "getincidentswithpositionfromid"; + StringRequest strReq = getStringRequestGetIncidentsWithPositionFromUserID(); + AppController.getInstance().addToRequestQueue(strReq, tag_string_req); + } private StringRequest getStringRequestGetIncidentsWithPositionFromUserID() { - parent.showDialog(); return new StringRequest(Request.Method.POST, AppConfig.URL_REGISTER, new Response.Listener() { @Override public void onResponse(String response) { Log.d(TAG, "Map positions response with ID: " + response); - parent.hideDialog(); try { JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); if (!error) { - JSONArray incidents = jObj.getJSONArray("message"); + JSONArray incidents = jObj.getJSONArray("msg"); resultList = new ArrayList<>(); for(int i=0;i parent, View view, int position, long id) { - int i = 0; + int i = 99; switch (((Spinner) viewFragment.findViewById(R.id.dd_reportwf_1_cat_main)).getSelectedItemPosition()) { case VIOLANCE_GENERAL: @@ -203,16 +201,9 @@ public class ReportWF_1_Fragment extends Fragment{ private void initLayerPosition(){ timeLayout = (RelativeLayout) viewFragment.findViewById(R.id.ll_pos); timeLayout.setVisibility(View.INVISIBLE); + ((ReportWFActivity)getActivity()).setMapButtonVisibility(false); - btnPositionSearch = (BootstrapButton) viewFragment.findViewById(R.id.btn_reportwf_position); txtPositionInformation = (TextView) viewFragment.findViewById(R.id.lbl_reportwf_position_detail); - - btnPositionSearch.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - mCallbackMapListener.onCallMap(); - } - }); } @Override @@ -225,6 +216,7 @@ public class ReportWF_1_Fragment extends Fragment{ if(incident.getPosition() != null){ timeLayout.setVisibility(View.VISIBLE); txtPositionInformation.setText(incident.getIncidentPositionDescription()); + ((ReportWFActivity)getActivity()).setMapButtonVisibility(true); } if(incident.getFidIncidentCategory() != 0){ @@ -235,7 +227,7 @@ public class ReportWF_1_Fragment extends Fragment{ crimeSubCategory.setSelection(incident.getFidIncidentSubCategory()); } - if(incident.getEtcIncidentCategory() != null){ + if(!incident.getEtcIncidentCategory().toString().equals("")){ crimeSubOther.setText(incident.getEtcIncidentCategory()); } } @@ -261,7 +253,6 @@ public class ReportWF_1_Fragment extends Fragment{ try { mCallbackFinished = (OnInputFinishedListener) activity; - mCallbackMapListener = (OnCallMapListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement all Listeners"); diff --git a/app/src/main/java/org/deke/risk/riskahead/fragment/ReportWF_2_Fragment.java b/app/src/main/java/org/deke/risk/riskahead/fragment/ReportWF_2_Fragment.java index 1c26093..59c29be 100644 --- a/app/src/main/java/org/deke/risk/riskahead/fragment/ReportWF_2_Fragment.java +++ b/app/src/main/java/org/deke/risk/riskahead/fragment/ReportWF_2_Fragment.java @@ -145,8 +145,8 @@ public class ReportWF_2_Fragment extends Fragment { viewFragment.findViewById(R.id.ll_report_to_time).setVisibility(View.INVISIBLE); viewFragment.findViewById(R.id.dd_reportwf_2_time_sub).setVisibility(View.INVISIBLE); - incident.setFromDate(new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime())); - incident.setFromTime(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime())); + inputDateFrom.setText(new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime())); + inputTimeFrom.setText(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime())); isMandatoryCategoryFilled = true; break; @@ -195,8 +195,6 @@ public class ReportWF_2_Fragment extends Fragment { checkIfFinished(); } - - incident.setFidTimeCategory(position); } diff --git a/app/src/main/java/org/deke/risk/riskahead/fragment/Top10Fragment.java b/app/src/main/java/org/deke/risk/riskahead/fragment/Top10Fragment.java index 9393b54..a895fc0 100644 --- a/app/src/main/java/org/deke/risk/riskahead/fragment/Top10Fragment.java +++ b/app/src/main/java/org/deke/risk/riskahead/fragment/Top10Fragment.java @@ -48,30 +48,33 @@ public class Top10Fragment extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_top10list, container, false); parent = (ProfileActivity)getActivity(); - Log.d(TAG,"Top10ListActivated!"); + myListView = (ListView) view.findViewById(R.id.lv_top10list); - StringRequest strReq2 = getStringRequestTop10(); - String tag_string_req2 = "req_top10"; - AppController.getInstance().addToRequestQueue(strReq2, tag_string_req2); + if(resultList == null || resultList.size() == 0) getTop10ForList(); return view; } + private void getTop10ForList() { + StringRequest strReq2 = getStringRequestTop10(); + String tag_string_req2 = "req_top10"; + AppController.getInstance().addToRequestQueue(strReq2, tag_string_req2); + } + private StringRequest getStringRequestTop10() { - parent.showDialog(); return new StringRequest(Request.Method.POST, AppConfig.URL_REGISTER, new Response.Listener() { @Override public void onResponse(String response) { Log.d(TAG, "Top 10 stats: " + response); - parent.hideDialog(); + try { JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); if (!error) { - JSONArray users = jObj.getJSONArray("top10"); + JSONArray users = jObj.getJSONArray("msg"); resultList = new ArrayList<>(); for(int i=0;i 0){ + if(this.votedScore < 0){ + return 0.0f; + }else if(this.votedScore < 1){ return 0.5f; - }else if(this.votedScore > 1){ + }else if(this.votedScore < 2){ return 1.0f; - }else if(this.votedScore > 2){ + }else if(this.votedScore < 3){ return 1.5f; - }else if(this.votedScore > 3){ + }else if(this.votedScore < 4){ return 2.0f; - }else if(this.votedScore > 4){ + }else if(this.votedScore < 5){ return 2.5f; - }else if(this.votedScore > 5){ + }else if(this.votedScore < 6){ return 3.0f; - }else if(this.votedScore > 6){ + }else if(this.votedScore < 7){ return 3.5f; - }else if(this.votedScore > 7){ + }else if(this.votedScore < 8){ return 4.0f; - }else if(this.votedScore > 8){ + }else if(this.votedScore < 9){ return 4.5f; - }else if(this.votedScore > 9){ - return 5.0f; }else{ - return 0f; + return 5.0f; } } @@ -289,7 +288,11 @@ public class IncidentReport implements ClusterItem { String returnString = ""; switch (this.fidTimeCategory){ case 1: - returnString = context.getResources().getStringArray(R.array.cat_time_main)[this.fidTimeCategory-1]; + if((this.fromDate != null) && !(this.fromDate.equals("0000-00-00"))){ + returnString = this.fromDate+" "+this.fromTime; + }else{ + returnString = context.getResources().getStringArray(R.array.cat_time_main)[this.fidTimeCategory-1]; + } break; case 2: returnString = context.getResources().getStringArray(R.array.cat_time_sub_periodical)[this.fidTimeSubCategory-1]; @@ -316,7 +319,12 @@ public class IncidentReport implements ClusterItem { } public String getSuspectString(Context context){ - return context.getResources().getStringArray(R.array.cat_suspect_main)[this.fidSuspectCategory-1]; + if(this.fidSuspectCategory > 0){ + return context.getResources().getStringArray(R.array.cat_suspect_main)[this.fidSuspectCategory-1]; + }else{ + return ""; + } + } public int getCategoryColor(){ diff --git a/app/src/main/java/org/deke/risk/riskahead/helper/SessionManager.java b/app/src/main/java/org/deke/risk/riskahead/helper/SessionManager.java index 3171f03..ea989ce 100644 --- a/app/src/main/java/org/deke/risk/riskahead/helper/SessionManager.java +++ b/app/src/main/java/org/deke/risk/riskahead/helper/SessionManager.java @@ -5,6 +5,8 @@ import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.util.Log; +import com.google.android.gms.maps.model.LatLng; + import java.util.HashMap; public class SessionManager { @@ -35,6 +37,11 @@ public class SessionManager { public static final String TOKEN = "accesskey"; public static final String KEY_IS_LOGGEDIN = "isLoggedIn"; + public static final String KEY_LOCATION_LAT = "location_latitude"; + public static final String KEY_LOCATION_LNG = "location_longitude"; + + public static final String KEY_LAST_NOTIFICATION = "lastNotificationTime"; + public SessionManager(Context context) { @@ -54,6 +61,25 @@ public class SessionManager { return status.getBoolean(KEY_IS_LOGGEDIN, false); } + public void setLocation(Long latitude, Long longitude){ + statusEditor.putLong(KEY_LOCATION_LAT, latitude); + statusEditor.putLong(KEY_LOCATION_LNG, longitude); + statusEditor.apply(); + } + + public LatLng getLocation(){ + return new LatLng(Double.longBitsToDouble(status.getLong(KEY_LOCATION_LAT, 0)), Double.longBitsToDouble(status.getLong(KEY_LOCATION_LNG, 0))); + } + + public void setLastNotification(String time){ + statusEditor.putString(KEY_LAST_NOTIFICATION, time); + statusEditor.apply(); + } + + public String getLastNotification(){ + return status.getString(KEY_LAST_NOTIFICATION, ""); + } + public void addUser(String uid, String username, String name, String surname, String email, String status, String provider_type, String created_at, String updated_at, String lastlogin_at, String token) { userDataEditor.putString(KEY_UID, uid); //UID diff --git a/app/src/main/res/anim/fade_in_anim.xml b/app/src/main/res/anim/fade_in_anim.xml index ee9288f..03a7fc8 100644 --- a/app/src/main/res/anim/fade_in_anim.xml +++ b/app/src/main/res/anim/fade_in_anim.xml @@ -8,6 +8,6 @@ android:repeatCount="0" /> --> - - + + \ No newline at end of file diff --git a/app/src/main/res/anim/fade_out_anim.xml b/app/src/main/res/anim/fade_out_anim.xml index 6c07221..3e3d9f9 100644 --- a/app/src/main/res/anim/fade_out_anim.xml +++ b/app/src/main/res/anim/fade_out_anim.xml @@ -8,6 +8,6 @@ android:repeatCount="0" /> --> - - + + \ No newline at end of file diff --git a/app/src/main/res/drawable/header2.jpg b/app/src/main/res/drawable/header2.jpg index 61a43f9..57a8cad 100644 Binary files a/app/src/main/res/drawable/header2.jpg and b/app/src/main/res/drawable/header2.jpg differ diff --git a/app/src/main/res/layout/activity_maps.xml b/app/src/main/res/layout/activity_maps.xml index 39a3418..1100926 100644 --- a/app/src/main/res/layout/activity_maps.xml +++ b/app/src/main/res/layout/activity_maps.xml @@ -1,6 +1,7 @@ - + tools:context=".MapsActivity" > + + + + + + diff --git a/app/src/main/res/layout/activity_report_wf.xml b/app/src/main/res/layout/activity_report_wf.xml index 0d685a4..3f98ee2 100644 --- a/app/src/main/res/layout/activity_report_wf.xml +++ b/app/src/main/res/layout/activity_report_wf.xml @@ -1,4 +1,5 @@ - + android:layout_gravity="center_horizontal" > + + + - + - + - + - + android:layout_below="@+id/til_viewreport_incidentcategory"> - + - + - - - - - + android:layout_below="@+id/til_viewreport_incidentsubcategory" /> - - + + android:layout_marginLeft="31dp" + android:layout_alignBaseline="@+id/btn_viewreport_position" + android:layout_alignBottom="@+id/btn_viewreport_position" + android:layout_toRightOf="@+id/lbl_viewreport_position" + android:layout_toEndOf="@+id/lbl_viewreport_position" + android:layout_marginStart="31dp" /> @@ -80,28 +79,17 @@ android:textColor="@color/bg_common" /> - + diff --git a/app/src/main/res/layout/fragment_reportwf_2.xml b/app/src/main/res/layout/fragment_reportwf_2.xml index eb066ea..19bd0ab 100644 --- a/app/src/main/res/layout/fragment_reportwf_2.xml +++ b/app/src/main/res/layout/fragment_reportwf_2.xml @@ -63,7 +63,6 @@ android:id="@+id/lbl_report_from_date" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:layout_below="@+id/dd_report_category" android:layout_marginTop="10dp" android:text="@string/lbl_report_from_date" /> @@ -111,7 +110,6 @@ android:id="@+id/lbl_report_to_date" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:layout_below="@+id/dd_report_category" android:layout_marginTop="10dp" android:text="@string/lbl_report_to_date" /> diff --git a/app/src/main/res/layout/fragment_reportwf_3.xml b/app/src/main/res/layout/fragment_reportwf_3.xml index 53065e3..214c8f1 100644 --- a/app/src/main/res/layout/fragment_reportwf_3.xml +++ b/app/src/main/res/layout/fragment_reportwf_3.xml @@ -57,7 +57,6 @@ diff --git a/app/src/main/res/layout/map_info_window.xml b/app/src/main/res/layout/map_info_window.xml index 542a8f5..18e6c0d 100644 --- a/app/src/main/res/layout/map_info_window.xml +++ b/app/src/main/res/layout/map_info_window.xml @@ -16,7 +16,7 @@ android:layout_marginRight="10dp" android:textColor="#a6000000" android:id="@+id/txt_infowindow_category" - android:text="Headerfffffffffffffffffffffffffffffffff" + android:text="Loading Header..." android:textSize="18dp" android:paddingLeft="30dp" android:typeface="serif" @@ -48,7 +48,7 @@ android:layout_height="wrap_content" android:typeface="serif" android:textColor="#b9000000" - android:text="subcategory" + android:text="Loading subcategory..." android:paddingTop="10dp" android:paddingLeft="5dp" android:id="@+id/txt_infowindow_subcategory" @@ -60,7 +60,7 @@ android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#b9000000" - android:text="subject" + android:text="Loading subject..." android:paddingLeft="5dp" android:id="@+id/txt_infowindow_subject" android:typeface="serif" /> @@ -69,7 +69,7 @@ android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#b9000000" - android:text="victim" + android:text="Loading victim..." android:paddingLeft="5dp" android:id="@+id/txt_infowindow_victim" android:typeface="serif" /> @@ -78,7 +78,7 @@ android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#b9000000" - android:text="time" + android:text="Loading time..." android:paddingLeft="5dp" android:paddingBottom="10dp" android:id="@+id/txt_infowindow_time" @@ -96,7 +96,7 @@ android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#b9000000" - android:text="username" + android:text="Loading username..." android:id="@+id/txt_infowindow_fromuser" android:typeface="serif" /> @@ -104,7 +104,7 @@ android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#b9000000" - android:text="points:" + android:text="Loading points..." android:id="@+id/txt_infowindow_points" android:typeface="serif" /> diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 5b4c518..0273f24 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -123,6 +123,8 @@ From time To date (yyyy-MM-dd) To time + Incident Category + Incident Subcategory Allgemeiner Vorfall/Situation