我希望能够在我的LINQ中模拟我的平均日期差异计算。
我的代码:
AverageTime = step.Average(x => (x.EndDate - x.StartDate).TotalSeconds))
由于存储库并不总是包含DbContext,例如当我运行测试时。 我尝试过使用
public class PickupActivity extends LocationUtils implements OnMapReadyCallback, AddressSearchAdapter.ClickListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private LatLng center;
private TextView pickupMarker;
private LinearLayout markerLayout, addressBox, confirmPickupLayout;
private EditText address, pincodeText, landmarkText;
private ImageView currentLocationButton;
private LatLng latLng, latLng1;
private JSONArray addressComponents, typesArray;
String formattedAddress;
String currentLatitude, currentLongitude;
private Toolbar toolbar;
private SharedPreferenceClass preferenceClass;
private String pincode, gPlaceId, city, country, state, premise, route, enteredText, pickupLat, pickupLong, currentGplaceId;
private AddressSearchAdapter mAdapter;
private RecyclerView mRecyclerView;
private ArrayList<com.packr.classes.Address> addressArrayList = new ArrayList<>();
private JSONObject locationObject, geometryObject;
private com.packr.classes.Address mAddress;
private int pickupToastVisible = 0;
private Boolean pickupLocationSet = false, isAddressTextEmpty = false;
private Button confirmPickupButton;
private Double a, b, x, y;
/**
* Represents a geographical location.
*/
protected Location mLastLocation;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pickup);
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
initialize();
onClick();
onSearchTextChanged();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setVisibility(View.GONE);
mRecyclerView.setLayoutManager(new MyLinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
mAdapter = new AddressSearchAdapter(getApplicationContext(), this);
mAdapter.setClickListener(this);
mRecyclerView.setAdapter(mAdapter);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Set Pickup Location");
setSupportActionBar(toolbar);
}
/**
* function to load map. If map is not created it will create it for you
* */
@Override
public void onResume() {
super.onResume();
}
public void initialize() {
confirmPickupLayout = (LinearLayout) findViewById(R.id.confirmPickupLayout);
preferenceClass = new SharedPreferenceClass(getApplicationContext());
pickupMarker = (TextView) findViewById(R.id.locationMarkertext);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
address = (EditText) findViewById(R.id.addressText);
currentLocationButton = (ImageView) findViewById(R.id.current_location);
addressBox = (LinearLayout) findViewById(R.id.addressBox);
pincodeText = (EditText) findViewById(R.id.pincodeText);
landmarkText = (EditText) findViewById(R.id.landmarkText);
confirmPickupButton = (Button) findViewById(R.id.confirmPickup);
}
public void onClick() {
}
public void onSearchTextChanged() {
address.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() == 0 || s == "") {
isAddressTextEmpty = true;
if (mRecyclerView.getVisibility() == View.VISIBLE) {
mRecyclerView.setVisibility(View.GONE);
}
}
if (s.length() < 16) {
mRecyclerView.setVisibility(View.VISIBLE);
enteredText = s.toString().replace(" ", "");
if (isAddressTextEmpty) {
sendAutocompleteJsonRequest();
}
}
final List<com.packr.classes.Address> filteredModelList = filter(addressArrayList, s.toString());
mAdapter.animateTo(filteredModelList);
mRecyclerView.scrollToPosition(0);
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
@Override
public void onMapReady(GoogleMap map) {
TouchableMapFragment mFragment;
mFragment = new TouchableMapFragment();
new MapStateListener(map,mFragment,this){
@Override
public void onMapTouched() {
// Map touched
L.m("touched");
}
@Override
public void onMapReleased() {
// Map released
L.m("released");
}
@Override
public void onMapUnsettled() {
// Map unsettled
L.m("unSettled");
}
@Override
public void onMapSettled() {
// Map settled
L.m("settled");
}
};
mMap = map;
map.setMyLocationEnabled(false);
currentLatitude = preferenceClass.getCurrentLatitude();
currentLongitude = preferenceClass.getCurrentLongitude();
a = Double.parseDouble(currentLatitude);
b = Double.parseDouble(currentLongitude);
latLng = new LatLng(Double.parseDouble(currentLatitude), Double.parseDouble(currentLongitude));
map.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory
.fromResource(R.drawable.current_location_marker)));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(15f).tilt(0).bearing(0).build();
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.moveCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
address.setText(preferenceClass.getPickupAddress());
pincodeText.setText(preferenceClass.getPickupPincode());
map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition arg0) {
if (confirmPickupLayout.getVisibility() == View.VISIBLE) {
confirmPickupLayout.setVisibility(View.GONE);
slideOutTowardsBottom();
}
center = mMap.getCameraPosition().target;
currentLatitude = String.valueOf(center.latitude);
currentLongitude = String.valueOf(center.longitude);
latLng1 = new LatLng(center.latitude, center.longitude);
Log.e("Coordinates", String.valueOf(center.latitude) + "," + String.valueOf(center.longitude) + latLng1);
pickupMarker.setText(" Set your Location ");
if (!pickupLocationSet) {
float[] distances = new float[1];
Location.distanceBetween(center.latitude, center.longitude, a, b, distances);
System.out.println("Distance: " + distances[0]);
if (distances[0] > 1000.0) {
sendJsonRequest();
L.m("called");
a = center.latitude;
b = center.longitude;
}
}
}
});
}
public void sendJsonRequest() {
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, getRequestUrl(), new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
//console test
parseJsonResponse(jsonObject);
if (formattedAddress == null) {
address.setText("Obtaining Address");
} else {
address.setText(formattedAddress);
}
Log.e("error", jsonObject.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
} else if (volleyError instanceof AuthFailureError) {
} else if (volleyError instanceof ServerError) {
} else if (volleyError instanceof NetworkError) {
} else if (volleyError instanceof ParseError) {
}
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
1000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
requestQueue.add(jsonObjectRequest);
}
public String getRequestUrl() {
return KEY_GEOCODE_URL +
currentLatitude + KEY_COMMA + currentLongitude +
KEY_SENSOR;
}
public void parseJsonResponse(JSONObject response) {
if (response != null && response.length() > 0) {
try {
JSONArray resultArray = response.getJSONArray(KEY_RESULTS);
if (resultArray.length() > 0) {
for (int i = 0; i < resultArray.length(); i++) {
JSONObject resultListObject = resultArray.getJSONObject(0);
formattedAddress = resultListObject.getString(KEY_FORMATTED_ADDRESS);
addressComponents = resultListObject.getJSONArray(KEY_ADDRESS_COMPONENTS);
gPlaceId = resultListObject.getString(KEY_PLACE_ID);
preferenceClass.savePickupGplaceId(gPlaceId);
}
if (addressComponents.length() > 0) {
for (int j = 0; j < addressComponents.length(); j++) {
JSONObject addressComponentsObject = addressComponents.getJSONObject(j);
typesArray = addressComponentsObject.getJSONArray(KEY_TYPES);
if ((typesArray.getString(0)).contentEquals(KEY_POSTAL_CODE)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
pincode = addressComponentsObject.getString(KEY_LONG_NAME);
pincodeText.setText(pincode);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public String getAutocompleteRequestUrl() {
return KEY_AUTOCOMPLETE_API.concat(enteredText);
}
public void sendAutocompleteJsonRequest() {
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, getAutocompleteRequestUrl(), new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
parseJSONResponse(jsonObject);
//Calling the Snackbar
Log.e("response", jsonObject.toString());
mAdapter.setAddressArrayList(addressArrayList);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
} else if (volleyError instanceof AuthFailureError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
//TODO
} else if (volleyError instanceof ServerError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
//TODO
} else if (volleyError instanceof NetworkError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
//TODO
} else if (volleyError instanceof ParseError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
//TODO
}
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
1000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
}
private void parseJSONResponse(JSONObject response) {
if (response != null && response.length() > 0) {
try {
JSONArray resultArray = response.getJSONArray(KEY_RESULTS);
if (resultArray.length() > 0) {
for (int i = 0; i < resultArray.length(); i++) {
JSONObject resultListObject = resultArray.getJSONObject(i);
formattedAddress = resultListObject.getString(KEY_FORMATTED_ADDRESS);
addressComponents = resultListObject.getJSONArray(KEY_ADDRESS_COMPONENTS);
gPlaceId = resultListObject.getString(KEY_PLACE_ID);
if (resultListObject.has(KEY_LOCATION) && !(resultListObject.isNull(KEY_LOCATION))) {
locationObject = resultListObject.getJSONObject(KEY_LOCATION);
if (locationObject.has(KEY_LATITUDE) && !(locationObject.isNull(KEY_LATITUDE))) {
currentLatitude = locationObject.getString(KEY_LATITUDE);
}
if (locationObject.has(KEY_LONGITUDE) && !(locationObject.isNull(KEY_LONGITUDE))) {
currentLongitude = locationObject.getString(KEY_LONGITUDE);
}
}
if ((resultListObject.has(KEY_GEOMETRY)) && !(resultListObject.isNull(KEY_GEOMETRY))) {
geometryObject = resultListObject.getJSONObject(KEY_GEOMETRY);
if (geometryObject.has(KEY_LOCATION) && !(geometryObject.isNull(KEY_LOCATION))) {
locationObject = geometryObject.getJSONObject(KEY_LOCATION);
if (locationObject.has(KEY_LATITUDE) && !(locationObject.isNull(KEY_LATITUDE))) {
currentLatitude = locationObject.getString(KEY_LATITUDE);
}
if (locationObject.has(KEY_LONGITUDE) && !(locationObject.isNull(KEY_LONGITUDE))) {
currentLongitude = locationObject.getString(KEY_LONGITUDE);
}
}
}
if (addressComponents.length() > 0) {
for (int j = 0; j < addressComponents.length(); j++) {
JSONObject addressComponentsObject = addressComponents.getJSONObject(j);
typesArray = addressComponentsObject.getJSONArray(KEY_TYPES);
if ((typesArray.getString(0)).contentEquals(KEY_CITY)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
city = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_COUNTRY)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
country = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_STATE)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
state = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_POSTAL_CODE)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
pincode = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_PREMISE)) {
premise = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_ROUTE)) {
route = addressComponentsObject.getString(KEY_LONG_NAME);
}
}
}
if (country.contentEquals("India") && city.contentEquals("Kolkata")) {
mAddress = new com.packr.classes.Address();
mAddress.setFormattedAddress(formattedAddress);
mAddress.setCity(city);
mAddress.setCountry(country);
mAddress.setPincode(pincode);
mAddress.setState(state);
mAddress.setStreet(premise);
mAddress.setRoute(route);
mAddress.setLatitude(currentLatitude);
mAddress.setLongitude(currentLongitude);
mAddress.setGplaceId(gPlaceId);
addressArrayList.add(mAddress);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private List<com.packr.classes.Address> filter(List<com.packr.classes.Address> models, String query) {
query = query.toLowerCase();
final List<com.packr.classes.Address> filteredModelList = new ArrayList<>();
for (com.packr.classes.Address model : models) {
final String text = model.getFormattedAddress().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
public void slideInFromBottom() {
Animation tvAnim = AnimationUtils.loadAnimation(this, R.anim.abc_slide_in_bottom);
confirmPickupLayout.startAnimation(tvAnim);
}
public void slideOutTowardsBottom() {
Animation tvAnim = AnimationUtils.loadAnimation(this, R.anim.abc_slide_out_bottom);
confirmPickupLayout.startAnimation(tvAnim);
}
// to check whether location services are enable or not
public static boolean isLocationEnabled(Context context) {
int locationMode = 0;
String locationProviders;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
try {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
return false;
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
} else {
locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
return !TextUtils.isEmpty(locationProviders);
}
}
@Override
public void itemClicked(View view, int position) {
hideKeyboard();
confirmPickupLayout.setVisibility(View.VISIBLE);
slideInFromBottom();
mRecyclerView.setVisibility(View.GONE);
pickupLat = addressArrayList.get(position).getLatitude();
pickupLong = addressArrayList.get(position).getLongitude();
preferenceClass.savePickupLatitude(currentLatitude);
preferenceClass.savePickupLongitude(currentLongitude);
String pincode = addressArrayList.get(position).getPincode();
currentGplaceId = addressArrayList.get(position).getGplaceId();
preferenceClass.savePickupGplaceId(currentGplaceId);
latLng = new LatLng(Double.parseDouble(pickupLat), Double.parseDouble(pickupLong));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(15f).tilt(0).bearing(0).build();
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
address.setText(formattedAddress);
if (pincode != null) {
pincodeText.setText(pincode);
}
}
public Boolean validationCheck() {
if (address.getText().length() == 0) {
L.t(getApplicationContext(), "Please provide a pickup address");
} else if (pincodeText.getText().length() != 6) {
L.t(getApplicationContext(), "Pincode must contain 6 digits");
} else if (landmarkText.getText().length() == 0) {
L.t(getApplicationContext(), "Please provide a landmark");
} else return true;
return false;
}
private void hideKeyboard() {
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
但实体框架不支持。
我想找到一种方法,我可以独立于DbContext执行此操作。有什么建议吗?