Not refreshing custom renderer Xamarin forms maps - google-maps

I created a map with custom marker with real-time location update. But after adding a new pin to the map its not applying the custom renderer. If I zoomed-in or zoomed-out on the map its applying that custom renders for markers. Here is my code.
This Code is in Xamarin.Droid project
public class CustomMapRenderer : MapRenderer, IOnMapReadyCallback, GoogleMap.IInfoWindowAdapter
{
GoogleMap map;
List<Position> routeCoordinates;
List<CustomPin> customPins;
Action<CustomPin> onInfoWindowClicked;
public void OnMapReady(GoogleMap googleMap)
{
map = googleMap;
//map.InfoWindowClick += OnInfoWindowClick;
map.SetInfoWindowAdapter(this);
var polylineOptions = new PolylineOptions();
polylineOptions.InvokeColor(Android.Graphics.Color.Blue);
foreach (var position in routeCoordinates)
{
polylineOptions.Add(new LatLng(position.Latitude, position.Longitude));
}
map.AddPolyline(polylineOptions);
}
protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Xamarin.Forms.View> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
map.InfoWindowClick -= OnInfoWindowClick;
// Unsubscribe
}
if (e.NewElement != null)
{
var formsMap = (CustomMap)e.NewElement;
routeCoordinates = formsMap.RouteCoordinates;
customPins = formsMap.CustomPins;
onInfoWindowClicked = formsMap.OnInfoWindowClicked;
((Android.Gms.Maps.MapView)Control).GetMapAsync(this);
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (map != null)
{
map.Clear();
foreach (var pin in customPins)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Pin.Position.Latitude, pin.Pin.Position.Longitude));
marker.SetTitle(pin.Id.ToString());
marker.SetSnippet(pin.Pin.Address);
if(pin.UserType == global::Common.Models.UserType.Driver)
{
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.car));
}
else if (pin.UserType == global::Common.Models.UserType.Rider)
{
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.person));
}
map.AddMarker(marker);
}
}
}
void OnInfoWindowClick(object sender, GoogleMap.InfoWindowClickEventArgs e)
{
onInfoWindowClicked(GetCustomPin(e.Marker));
}
private CustomPin GetCustomPin(Marker marker)
{
return customPins.Find(x => x.Id.ToString() ==marker.Title.ToString());
}
public Android.Views.View GetInfoContents(Marker marker)
{
var inflater = Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as Android.Views.LayoutInflater;
if (inflater != null)
{
Android.Views.View view;
var customPin = GetCustomPin(marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
var infoImage = view.FindViewById<ImageView>(Resource.Id.markerInfoImage);
var infoTitle = view.FindViewById<TextView>(Resource.Id.markerInfoTitle);
var infoSummary = view.FindViewById<TextView>(Resource.Id.markerInfoSummary);
System.IO.Stream ims = Context.Assets.Open(customPin.Image);
// load image as Drawable
Drawable d = Drawable.CreateFromStream(ims, null);
// set image to ImageView
infoImage.SetImageDrawable(d);
//File file = new File(customPin.Image);
//var image = Android.Net.Uri.FromFile(file);
//var resource=ResourceManager.GetDrawableByName("driverLogActive_icon.png");
//infoImage.SetImageResource(resource);
//infoImag = customPin.Title;
infoTitle.Text = customPin.Title;
infoSummary.Text = customPin.MobileNo;
return view;
}
return null;
}
public Android.Views.View GetInfoWindow(Marker marker)
{
return null;
}
}
This code is in Xamarin.Forms project
public class CustomPin
{
public Pin Pin { get; set; }
public Guid Id { get; set; }
public string Title { get; set; }
public string MobileNo { get; set; }
public string Image { get; set; }
public string UserName { get; set; }
public UserType UserType { get; set; }
}
public class CustomMap : Map
{
public static readonly BindableProperty RouteCoordinatesProperty = BindableProperty.Create(nameof(RouteCoordinates), typeof(List<Position>), typeof(CustomMap), new List<Position>(), BindingMode.TwoWay);
public static readonly BindableProperty CustomPinsProperty = BindableProperty.Create(nameof(CustomPins), typeof(List<CustomPin>), typeof(CustomMap), new List<CustomPin>(), BindingMode.TwoWay);
public List<CustomPin> CustomPins
{
get { return (List<CustomPin>)GetValue(CustomPinsProperty); }
set { SetValue(CustomPinsProperty, value); }
}
public List<Position> RouteCoordinates
{
get { return (List<Position>)GetValue(RouteCoordinatesProperty); }
set { SetValue(RouteCoordinatesProperty, value); }
}
public Action<CustomPin> OnInfoWindowClicked;
public CustomMap()
{
RouteCoordinates = new List<Position>();
CustomPins = new List<CustomPin>();
}
}
This is how I use the custom map to render pin in Xamrin.Fomrs project
private void RenderPin(string longitudeCoordinate, string latitudeCoordinate,bool canMoveToLoacation, string lable,UserType userType,string mobileNo,string image,string userName)
{
double latitude = 0;
double longitude = 0;
double.TryParse(latitudeCoordinate, out latitude);
double.TryParse(longitudeCoordinate, out longitude);
var position = new Position(latitude, longitude);
var pin = new CustomPin
{
Pin = new Pin
{
Type = PinType.Place,
Position = position,
Label = lable,
},
Title = lable,
UserType = userType,
MobileNo = "Mobile No:" + mobileNo,
Image = "profile_images/" + image,
UserName = userName,
Id = Guid.NewGuid()
};
map.CustomPins.Add(pin);
map.Pins.Add(pin.Pin);
if (canMoveToLoacation)
{
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(latitude, longitude), Distance.FromKilometers(2)));
}
}

If you install the Xamarin.Forms.Maps pre-release (2.3.5.255-pre5), you can now just override the CreateMarker() method in MapRenderer. It's much more elegant, and it fixes this problem with pins not being updated when added after map creation.

Related

Web API , How to remove Slashes from web api json?

Here is the Json Result :
"[{\"EmpId\":1,\"Full_Name\":\"Parth Dave\",\"City\":\"\"},{\"EmpId\":2,\"Full_Name\":\"Chirag\",\"City\":\"\"},{\"EmpId\":3,\"Full_Name\":\"Jay\",\"City\":\"\"}]"
Here is my code:
public string GetProducts()
{
var empQuery = from emp in objEmployeeEntities.Employees
select new EmployeeClass() { EmpId = emp.EmpId, Full_Name = emp.Full_Name };
var settings = new JsonSerializerSettings() { ContractResolver = new NullToEmptyStringResolver() };
var str = JsonConvert.SerializeObject(empQuery.ToList(), settings);
return str;
}
public class NullToEmptyStringValueProvider : IValueProvider
{
PropertyInfo _MemberInfo;
public NullToEmptyStringValueProvider(PropertyInfo memberInfo)
{
_MemberInfo = memberInfo;
}
public object GetValue(object target)
{
object result = _MemberInfo.GetValue(target);
if (_MemberInfo.PropertyType == typeof(string) && result == null) result = "";
return result;
}
public void SetValue(object target, object value)
{
_MemberInfo.SetValue(target, value);
}
}
public class NullToEmptyStringResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
return type.GetProperties()
.Select(p =>
{
var jp = base.CreateProperty(p, memberSerialization);
jp.ValueProvider = new NullToEmptyStringValueProvider(p);
return jp;
}).ToList();
}
}

ObservableCollection not working the RaisePropertyChangeEvent

I am using MVVM light. Initially I add two items; after that I am adding two more new items in the list, and calling the RaisePropertyChanged event; but it's not updating the list view, it's showing old items only. What is the problem in my code?
My Model
public class ViewPeopleModel
{
public event PropertyChangedEventHandler PropertyChanged;
private string _imageURL;
public string ImageURL
{
get
{
return _imageURL;
}
set
{
_imageURL = value;
OnPropertyChanged("ImageURL");
}
}
public void OnPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
View Model
public class ViewPeopleViewModel : ViewModelBase
{
public ObservableCollection<ViewPeopleModel> ProfileList { get; set; }
public ViewPeopleViewModel()
{
ObservableCollection<ViewPeopleModel> _people = new ObservableCollection<ViewPeopleModel>();
_people.Add(new ViewPeopleModel { ImageURL = "url1" });
_people.Add(new ViewPeopleModel { ImageURL = "url2" });
ProfileList = _people;
RaisePropertyChanged("ProfileList");
}
public void AddNewPeople()
{
ObservableCollection<ViewPeopleModel> _people = new ObservableCollection<ViewPeopleModel>();
_people.Add(new ViewPeopleModel { ImageURL = "url5" });
_people.Add(new ViewPeopleModel { ImageURL = "url6" });
ProfileList = _people;
RaisePropertyChanged("ProfileList");
}
}
Try doing this in your AddNewPeople method
public void AddNewPeople()
{
ProfileList.Clear();
ProfileList.Add(new ViewPeopleModel{ ImageURL ="url5" });
ProfileList.Add(new ViewPeopleModel{ ImageURL ="url6" });
}

Google Place Autocomplete in Xamarin.Forms

Has anyone integrated Google Place Autocomplete using Xamarin.Forms? I am to use it on a map for location suggestions. I've only seen resources for Xamarin.Android and Xamarin.iOS but on the part of implementing the AutoCompleteView, that I also don't know. I would be very thankful if someone could guide me with this. Thank you!
Place autocomplete can be implemented by using the Google Place API, whenever user enter a character, matching location with the entered character will be fetched from the Google server and binding back in User Interface.
Here's the link how to use Google Map Place API in Xamarin form:
http://www.appliedcodelog.com/2015/05/google-place-api-with-autocomplete-in.html
Also, please read the Official Google Places API Web Service:
https://developers.google.com/places/web-service/autocomplete
For iOS
[assembly: ExportRenderer(typeof(CustomAutoCompleteLocation), typeof(CustomAutoCompleteRenderer))]
namespace Aesthetic.iOS.Renderer
{
public class CustomAutoCompleteProfileRenderer : EntryRenderer
{
IntPtr inptr;
string tx = "1";
CustomAutoCompleteLocation _view;
Place place;
UITextField textView;
public UIWindow Window
{
get;
set;
}
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
_view = (CustomAutoCompleteLocation)Element;
if (Control != null)
{
textView = (UITextField)Control;
textView.Font = UIFont.FromName("Lato-Light", textView.Font.PointSize);
textView.BorderStyle = UITextBorderStyle.Line;
textView.Layer.BorderWidth = 1f;
textView.Layer.CornerRadius = 0f;
// do whatever you want to the textField here!
UIView paddingView = new UIView(new RectangleF(10, 16, 10, 16));
textView.LeftView = paddingView;
textView.LeftViewMode = UITextFieldViewMode.Always;
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
var x = sender as CustomAutoComplete;
if (e.PropertyName == "IsFocused")
{
if (tx == "1")
{
Device.BeginInvokeOnMainThread(() =>
{
Window = new UIWindow(UIScreen.MainScreen.Bounds);
var controller = new LocationViewController();
Window.RootViewController = controller;
// make the window visible
Window.MakeKeyAndVisible();
controller.PlaceSelected1 += HandlePlaceSelection;
});
tx = "2";
}
else if (tx == "2") tx = "3";
else if (tx == "3") tx = "4";
else if (tx == "4") tx = "1";
}
}
private void HandlePlaceSelection(object sender, string locationData)
{
textView.Text = locationData;
Window.Hidden = true;
}
}
}
And this is location view controller
public partial class LocationViewController : UIViewController
{
public delegate void PlaceSelected(object sender, string locationData);
UITextField txtLocation;
public UIView backgroundView;
// UITextView txtLocation;
UIImageView googleAttribution;
UITableView tableViewLocationAutoComplete;
public event PlaceSelected PlaceSelected1;
public string strSampleString { get; set; }
LocationPredictionClass objAutoCompleteLocationClass;
string strAutoCompleteQuery;
LocationAutoCompleteTableSource objLocationAutoCompleteTableSource;
public LocationViewController() : base()
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
FnInitializeView();
FnClickEventInit();
}
void FnInitializeView()
{
backgroundView = new UIView(View.Frame);
backgroundView.BackgroundColor = UIColor.White;
View.AddSubview(backgroundView);
txtLocation = new UITextField();
txtLocation.Frame = new CoreGraphics.CGRect(20, 20, View.Frame.Width-20, 45.0f);
txtLocation.TranslatesAutoresizingMaskIntoConstraints = false;
txtLocation.ReturnKeyType = UIReturnKeyType.Done;
txtLocation.BackgroundColor = UIColor.FromRGB(221,221,221);
txtLocation.TextColor = UIColor.Black;
View.AddSubview(txtLocation);
txtLocation.BecomeFirstResponder();
tableViewLocationAutoComplete = new UITableView();
tableViewLocationAutoComplete.Frame = new CoreGraphics.CGRect(txtLocation.Frame.X, txtLocation.Frame.Height+ txtLocation.Frame.Y, View.Frame.Width, View.Frame.Height - txtLocation.Frame.Height - txtLocation.Frame.Y);
tableViewLocationAutoComplete.BackgroundColor = UIColor.White;
tableViewLocationAutoComplete.Source = objLocationAutoCompleteTableSource;
View.AddSubview(tableViewLocationAutoComplete);
tableViewLocationAutoComplete.Hidden = false;
txtLocation.ShouldReturn += (textField) => textField.ResignFirstResponder();
StringBuilder builderLocationAutoComplete = new StringBuilder(Constants.strPlacesAutofillUrl);
builderLocationAutoComplete.Append("?input={0}").Append("&key=").Append(Constants.strGooglePlaceAPILey);
strAutoCompleteQuery = builderLocationAutoComplete.ToString();
builderLocationAutoComplete.Clear();
builderLocationAutoComplete = null;
}
void FnClickEventInit()
{
txtLocation.EditingChanged += async delegate (object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(txtLocation.Text))
{
tableViewLocationAutoComplete.Hidden = true;
}
else
{
if (txtLocation.Text.Length > 2)
{
//Autofill
string strFullURL = string.Format(strAutoCompleteQuery, txtLocation.Text);
objAutoCompleteLocationClass = await RestRequestClass.LocationAutoComplete(strFullURL);
if (objAutoCompleteLocationClass != null && objAutoCompleteLocationClass.status == "OK")
{
if (objAutoCompleteLocationClass.predictions.Count > 0)
{
if (objLocationAutoCompleteTableSource != null)
{
objLocationAutoCompleteTableSource.LocationRowSelectedEventAction -= LocationSelectedFromAutoFill;
objLocationAutoCompleteTableSource = null;
}
tableViewLocationAutoComplete.Hidden = false;
objLocationAutoCompleteTableSource = new LocationAutoCompleteTableSource(objAutoCompleteLocationClass.predictions);
objLocationAutoCompleteTableSource.LocationRowSelectedEventAction += LocationSelectedFromAutoFill;
tableViewLocationAutoComplete.Source = objLocationAutoCompleteTableSource;
tableViewLocationAutoComplete.ReloadData();
}
else
tableViewLocationAutoComplete.Hidden = true;
}
else
{
tableViewLocationAutoComplete.Hidden = true;
}
}
}
};
}
void LocationSelectedFromAutoFill(Prediction objPrediction)
{
DismissViewController(true, null);
Console.WriteLine(objPrediction.description);
PlaceSelected1(this, objPrediction.description);
txtLocation.ResignFirstResponder();
}
}
public class RestRequestClass
{
static async Task<string> CallService(string strURL)
{
WebClient client = new WebClient();
string strResult;
try
{
strResult = await client.DownloadStringTaskAsync(new Uri(strURL));
}
catch
{
strResult = "Exception";
}
finally
{
client.Dispose();
client = null;
}
return strResult;
}
internal static async Task<LocationPredictionClass> LocationAutoComplete(string strFullURL)
{
LocationPredictionClass objLocationPredictClass = null;
LocationPredictionClass objLocationPredictClass12 = new LocationPredictionClass();
objLocationPredictClass12.predictions = new List<Prediction>();
string strResult = await CallService(strFullURL);
if (strResult != "Exception")
{
objLocationPredictClass = JsonConvert.DeserializeObject<LocationPredictionClass>(strResult);
}
foreach (Prediction objPred in objLocationPredictClass.predictions)
{
if (objPred.types[0] == "country")
{
objLocationPredictClass12.predictions.Add(objPred);
objLocationPredictClass12.status = "OK";
}
}
// string[] strPredictiveText = new string[data.Count];
//int index = 0;
// foreach (Prediction objPred in data)
// {
// strPredictiveText[index] = objPred.description;
// index++;
// }
return objLocationPredictClass12;
}
}
public class MatchedSubstring
{
public int length { get; set; }
public int offset { get; set; }
}
public class Term
{
public int offset { get; set; }
public string value { get; set; }
}
public class Prediction
{
public string description { get; set; }
public string id { get; set; }
public List<MatchedSubstring> matched_substrings { get; set; }
public string place_id { get; set; }
public string reference { get; set; }
public List<Term> terms { get; set; }
public List<string> types { get; set; }
}
public class LocationPredictionClass
{
public List<Prediction> predictions { get; set; }
public string status { get; set; }
}
public class Constants
{
public static string strGooglePlaceAPILey = "AIzaSyBXJntNIs2aAvKIRwrgCEwOGwnigbSWep8";
public static string strPlacesAutofillUrl = "https://maps.googleapis.com/maps/api/place/autocomplete/json";
}
public class LocationAutoCompleteTableSource : UITableViewSource
{
const string strCellIdentifier = "Cell";
readonly List<Prediction> lstLocations;
internal event Action<Prediction> LocationRowSelectedEventAction;
public LocationAutoCompleteTableSource(List<Prediction> arrItems)
{
lstLocations = arrItems;
}
public override nint RowsInSection(UITableView tableview, nint section)
{
return lstLocations.Count;
}
public override UIView GetViewForFooter(UITableView tableView, nint section)
{
return new UIView();
}
public override UITableViewCell GetCell(UITableView tableView, Foundation.NSIndexPath indexPath)
{
UITableViewCell cell = tableView.DequeueReusableCell(strCellIdentifier) ?? new UITableViewCell(UITableViewCellStyle.Default, strCellIdentifier);
cell.TextLabel.Text = lstLocations[indexPath.Row].description;
cell.TextLabel.Font = UIFont.SystemFontOfSize(12);
return cell;
}
public override void RowSelected(UITableView tableView, Foundation.NSIndexPath indexPath)
{
if (LocationRowSelectedEventAction != null)
{
LocationRowSelectedEventAction(lstLocations[indexPath.Row]);
}
tableView.DeselectRow(indexPath, true);
}
}
}

how to send the LatLng result of OnPostExecute() to url

I am using Googlemaps v2.
I have to send the values of latlng, i.e.: the routePoints to the server.
I am displaying the latlng in onlocationchanged().
I need to send these values to an URL.
Here is my code.
public class MapDetail extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener,
OnMapLongClickListener {
private static final int GPS_ERRORDIALOG_REQUEST = 9001;
private static final String TAG_SUCCESS = "successfully stored";
GoogleMap mMap;
LocationClient mLocationClient;
Marker marker;
LatLng ll;
LatLng point1;
LatLng cLocation, pLocation;
List<LatLng> routePoints;
private List<MarkerOptions> markerOptions = new ArrayList<MarkerOptions>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (serviceOk()) {
setContentView(R.layout.activity_map);
if (initMap()) {
// mMap.setMyLocationEnabled(true);
mLocationClient = new LocationClient(this, this, this);
mLocationClient.connect();
} else {
Toast.makeText(this, "Map Not Avialable !!", Toast.LENGTH_LONG)
.show();
}
} else {
setContentView(R.layout.activity_main);
}
routePoints = new ArrayList<LatLng>();
}
public boolean serviceOk() {
int isAvailable = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
} else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable,
this, GPS_ERRORDIALOG_REQUEST);
dialog.show();
} else {
Toast.makeText(this, "can not connect google play services",
Toast.LENGTH_LONG).show();
}
return false;
}
private boolean initMap() {
if (mMap == null) {
SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mMap = mapFrag.getMap();
if (mMap != null) {
}
}
return (mMap != null);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.activity:
Intent i = new Intent(this, ComInfo.class);
startActivity(i);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
}
#Override
public void onConnected(Bundle arg0) {
Toast.makeText(this, "Connected To Location Service", Toast.LENGTH_LONG)
.show();
LocationRequest request = LocationRequest.create();
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
request.setInterval(5000);
request.setFastestInterval(1000);
mLocationClient.requestLocationUpdates(request, this);
mMap.setOnMapLongClickListener(this);
}
#Override
public void onDisconnected() {
}
#Override
public void onLocationChanged(Location location) {
String msg = "Location:" + location.getLatitude() + ","
+ location.getLongitude();
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
drawCircle(location);
for (int i = 0; i < this.markerOptions.size(); i++) {
mMap.addMarker(markerOptions.get(i));
}
LatLng ll1 = new LatLng(location.getLatitude(), location.getLongitude());
routePoints.add(ll1);
for (int i = 0; i < routePoints.size(); i++) {
Polyline route = mMap.addPolyline(new PolylineOptions().width(5)
.color(Color.GREEN).geodesic(true).zIndex(10));
route.setPoints(routePoints);
}
new AttemptSave().execute();
}
private void drawCircle(Location location) {
mMap.clear();
LatLng currentPosition = new LatLng(location.getLatitude(),
location.getLongitude());
mMap.addCircle(new CircleOptions().center(currentPosition).radius(50)
.fillColor(0x330000FF).strokeColor(Color.BLUE).strokeWidth(3));
double latitude = location.getLatitude();
double longitude = location.getLongitude();
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)).zoom(15f).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
#Override
protected void onPause() {
mLocationClient.disconnect();
super.onPause();
}
#Override
protected void onResume() {
mLocationClient.connect();
super.onResume();
}
#Override
protected void onStop() {
mLocationClient.disconnect();
super.onStop();
}
#Override
public void onMapLongClick(LatLng point) {
this.point1 = point;
MarkerOptions moMarkerOptions = new MarkerOptions()
.position(point)
.title("se guarda el punto")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
Marker marker = mMap.addMarker(moMarkerOptions);
this.markerOptions.add(moMarkerOptions);
new AttemptSave().execute("test");
}
class AttemptSave extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args0) {
String res = sendJSON();
Log.d("InputStream", res);
return res;
}
private String sendJSON() {
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("MY_URL");
String json = "";
json = this.getJSONObject().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("data", json));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpclient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (IOException e) {
Log.d("InputStream", e.getLocalizedMessage()); // e.getLocalizedMessage());
}
return result;
}
private String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
private JSONObject getJSONObject() {
JSONObject obj = new JSONObject();
try {
obj.put("id", 1);
obj.put("lat", point1.latitude);
obj.put("long", point1.longitude);
obj.put("track", "");
} catch (JSONException e) {
e.printStackTrace();
}
return obj;
}
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
List<HashMap<String, String>> path = result.get(i);
for(int j=0;j<path.size();j++){
HashMap<String,String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
new Saveroute().execute();
}
// Adding all the points in the route to LineOptionslineOptions.addAll(points) lineOptions.width(2);lineOptions.color(Color.RED);
}
}
}
class Saveroute extends AsyncTask<String, String, String >{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}}
}
In onLocationChanged(Location location) you are not initializing the point1, do as the same way you are doing in onMapLongClick()
#Override
public void onLocationChanged(Location location) {
point1=new LatLng(location.getLatitude(),location.getLongitude());
...
}

store details in windows phone 8 using sqlite?

I want to store information from the NFC tag I read and store in the database and show it all in another page but I am having problem in using implementing sqlite.I cant add the information to the database using sqlite.
Below is my checkin class from where I read from the NFC tag
public partial class Checkin : PhoneApplicationPage
{
private ProximityDevice _device;
private long _subscriptionIdNdef;
public static double Latitud_do { get; set; }
public static double Longtitude_do { get; set; }
public static string latitude { get; set; }
public static string longtitude { get; set; }
public static string Floor_st { get; set; }
public static string Zone_st { get; set; }
History store = new History();
public Checkin()
{
InitializeProximityDevice();
InitializeComponent();
}
private void SetLogStatus(string newStatus)
{
Dispatcher.BeginInvoke(() => { if (LogStatus != null) LogStatus.Text = newStatus; });
}
private void SetFloorStatus(string newStatus)
{
Dispatcher.BeginInvoke(() => { if (FloorStatus != null) FloorStatus.Text = newStatus; });
}
private void ApplicationBarIconButton_Click(object sender, System.EventArgs e)
{
MessageBox.Show(" ");
}
private void InitializeProximityDevice()
{
_device = Windows.Networking.Proximity.ProximityDevice.GetDefault();
if (_device != null)
{
_subscriptionIdNdef = _device.SubscribeForMessage("NDEF", MessageReceivedHandler);
}
}
private void MessageReceivedHandler(ProximityDevice sender, ProximityMessage message)
{
var rawMsg = message.Data.ToArray();
var ndefMessage = NdefMessage.FromByteArray(rawMsg);
////// Loop over all records contained in the NDEF message
foreach (NdefRecord record in ndefMessage)
{
if (NdefTextRecord.IsRecordType(record))
{
// Convert and extract URI info
var textRecord = new NdefTextRecord(record);
string[] str = textRecord.Text.Split('|');
var Floor_st = str[0];
var Zone_st = str[1];
var latitude = str[2];
var longtitude = str[3];
Latitud_do = double.Parse(latitude);
Longtitude_do = double.Parse(longtitude);
SetLogStatus("Floor: " + Floor_st + " Zone: " + Zone_st );
SetFloorStatus("Longitude: " + latitude + " Longitude: " + longtitude);
//store.AddDb(Floor_st, Zone_st, Latitud_do, Longtitude_do);
}
}
}
}
Below here is the main dbhelper class for the main sqlite functions
public class DbHelper
{
SQLiteConnection dbConn;
public async Task<bool> onCreate(string DB_PATH)
{
try
{
if (!CheckFileExists(DB_PATH).Result)
{
using (dbConn = new SQLiteConnection(DB_PATH))
{
dbConn.CreateTable<historyTableSQlite>();
}
}
return true;
}
catch
{
return false;
}
}
private async Task<bool> CheckFileExists(string fileName)
{
try
{
var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
return true;
}
catch
{
return false;
}
}
//retrieve all list from the database
public ObservableCollection<historyTableSQlite> ReadHistory()
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
List<historyTableSQlite> myCollection = dbConn.Table<historyTableSQlite>().ToList<historyTableSQlite>();
ObservableCollection<historyTableSQlite> HistoryList = new ObservableCollection<historyTableSQlite>(myCollection);
return HistoryList;
}
}
// Insert the new info in the histrorytablesqlite table.
public void Insert(historyTableSQlite newcontact)
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
dbConn.RunInTransaction(() =>
{
dbConn.Insert(newcontact);
});
}
}
}
below is the class from where I read all the information
public class ReadAllContactsList
{
DbHelper Db_Helper = new DbHelper();
public ObservableCollection<historyTableSQlite> GetAllHistory()
{
return Db_Helper.ReadHistory();
}
}
}
And last is the class where I want to show all the information I have stored
ublic partial class History : PhoneApplicationPage
{
// string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
ObservableCollection<historyTableSQlite> DB_HistoryList = new ObservableCollection<historyTableSQlite>();
public History()
{
InitializeComponent();
}
private void ReadHistoryList_Loaded(object sender, RoutedEventArgs e)
{
ReadAllContactsList dbhistory = new ReadAllContactsList();
DB_HistoryList = dbhistory.GetAllHistory();//Get all DB contacts
ListData.ItemsSource = DB_HistoryList.OrderByDescending(i => i.Id).ToList();//Latest contact ID can Display first
}
public void AddInfo(object sender, RoutedEventArgs e)
{
DbHelper Db_helper = new DbHelper();
Db_helper.Insert(new historyTableSQlite(
));
}
}
I followed the following post but still struglling
http://bsubramanyamraju.blogspot.com/2014/08/windowsphone-8-sqlite-storing-data-in.html
Thank you for your help in advance