I want to set second label in info window on xamarin map. I use this example.
So exactly I want to set one variable who come from date base on info window like a second label:
public MapPage()
{
InitializeComponent();
DatabaseConnection();
CustomPin pin1 = new CustomPin
{
Type = PinType.Place,
Position = new Position(41.59043006333251, 24.766286971618303),
Name = "Xamarin",
Label = "р. Бяла",
Address = "гр. Смолян",
};
CustomPin pin2 = new CustomPin
{
Type = PinType.Place,
Position = new Position(41.56817473054596, 24.758451447799708),
Label = "р. Черна",
Name = "Xamarin",
Address = "гр. Смолян",
};
CustomPin pin3 = new CustomPin
{
Type = PinType.Place,
Position = new Position(41.48398466282902, 24.847715935872973),
Label = "р. Елховска",
Name = "Xamarin",
Address = "гр. Рудозем",
};
customMap.CustomPins = new List<CustomPin> {
pin1,
pin2,
pin3,
};
customMap.Pins.Add(pin1);
customMap.Pins.Add(pin2);
customMap.Pins.Add(pin3);
customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(41.567797926753485, 25.389703182725665), Distance.FromKilometers(70)));
}
try
{
Conn.Open();
string query = "SELECT * FROM sel_alert_level s;";
MySqlCommand myCommand = new MySqlCommand(query, Conn);
MySqlDataReader myReader;
myReader = myCommand.ExecuteReader();
try
{
while (myReader.Read())
{
var codeNum = myReader.GetInt32(4);
var level = myReader.GetInt32(3);
await DisplayAlert("Database Connection", "Connected .." + Environment.NewLine + myReader.GetInt32(0) + Environment.NewLine + myReader.GetString(1) + Environment.NewLine + myReader.GetString(2) + Environment.NewLine + myReader.GetInt32(3) + Environment.NewLine + myReader.GetInt32(4), "OK");
}
}
finally
{
myReader.Close();
Conn.Close();
}
}
I want var codeNum = myReader.GetInt32(4); to be on the pin info window.
In my android project in directory resource/layout I have two axml files for the info window:
XamarinMapInfoWindow.axml
and
MapInfoWindow.axml
Inside in both files I create a new TextView for the second label:
<TextView
android:id="#id/InfoWindowSubtitle2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="InfoWindowSubtitle2"
android:textColor="#android:color/black" />
On my CustomMapRenderer.cs file in android project I have method GetInfoContents in which I do not know how to submit the new label.
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");
}
if (customPin.Name.Equals("Xamarin"))
{
view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null);
}
else
{
view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
}
var infoTitle = view.FindViewById<TextView>(Resource.Id.InfoWindowTitle);
var infoSubtitle = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle);
var infoSubtitle2 = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle2);
if (infoTitle != null)
{
infoTitle.Text = marker.Title;
}
if (infoSubtitle != null)
{
infoSubtitle.Text = marker.Snippet;
}
if (infoSubtitle2 != null)
{
infoSubtitle2.Text = marker.Snippet;
}
return view;
}
return null;
}
So
` if (infoSubtitle2 != null)
{
infoSubtitle2.Text = marker.Snippet;
}`
is not the correct code. Before this method in the same page I have CreateMarker method who add a new lines on the marker and here I also don't understand how to submit the new line:
protected override MarkerOptions CreateMarker(Pin pin)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
marker.SetTitle(pin.Label);
marker.SetSnippet(pin.Address);
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.green));
return marker;
}
Finally I create a new object in the Pin class for Alert Level who will come from data base.
namespace CustomRenderer
{
public class CustomPin : Pin
{
public string Name { get; set; }
public string Url { get; set; }
public int CodeNum { get; set; }
public int AlertLevel { get; set; }
}
}
My main question is how to put var level = myReader.GetInt32(3); like a second Label on InfoWindow ?
You could get the CustomPin with the GetCustomPin method in the custom renderer like the sample in your above link.
CustomPin GetCustomPin(Marker annotation)
{
var position = new Position(annotation.Position.Latitude, annotation.Position.Longitude);
foreach (var pin in customPins)
{
if (pin.Position == position)
{
return pin;
}
}
return null;
}
and in your public Android.Views.View GetInfoContents(Marker marker) method:
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");
}
if (customPin.Name.Equals("Xamarin"))
{
view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null);
}
else
{
view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
}
CustomPin pin = GetCustomPin(marker);
int CodeNum = pin.CodeNum; //get the pin,then get the codenum and alertlevel
string AlertLevel = pin.AlertLevel;
var infoTitle = view.FindViewById<TextView>(Resource.Id.InfoWindowTitle);
var infoSubtitle = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle);
var infoSubtitle2 = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle2);
var infoSubtitle3 = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle3);// create the third TextView in your xml
if (infoTitle != null)
{
infoTitle.Text = marker.Title;
}
if (infoSubtitle != null)
{
infoSubtitle.Text = marker.Snippet;
}
if (infoSubtitle2 != null)
{
infoSubtitle2.Text = CodeNum +"";
}
if (infoSubtitle3 != null)
{
infoSubtitle3.Text = AlertLevel;
}
return view;
}
return null;
}
Update :
public partial class YouPage: ContentPage
{
public YouPage()
{
InitializeComponent();
}
protected async override void OnAppearing()
{
base.OnAppearing();
... //you get the data from MySql,if you have several data,you need a loop
var codeNum = xxx;
var level = xxx;
CustomPin pin = new CustomPin();
pin.CodeNum = codeNum;
pin.AlertLevel = level ;
yourcustomMap.Pins.Add(pin);
}
Related
I have a master and content page and I have created an eventhandler on a master page that runs through the content page. And it calls twice. Why i dont understand so please help. even i have handled proper postback
When i call function sendmail() it is calling multiple time. please help where i am going to wrong
Master Page Code
namespace Report_Server
{
public partial class ssrs : System.Web.UI.MasterPage
{
public delegate string NoArgEventHandler(string mailid);
public static event NoArgEventHandler sendMail ;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
mailLabel.Visible = false;
mailaddress.Visible = true;
btnSendMail.Enabled = true;
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "mailModal", "$('#mailModal').modal();", true);
//upModal.Update();
}
protected void btnSendMail_Click(object sender, EventArgs e)
{
//ScriptManager.RegisterStartupScript(Page, Page.GetType(), "mailModal", "$('#mailModal').modal('hide');", true);
mailLabel.Visible = true;
mailaddress.Visible = false;
btnSendMail.Enabled = false;
mailLabel.Text = "Sending, Please Wait";
string message = sendMail(mailaddress.Text);
mailLabel.Text = message;
//Type cstype = this.GetType();
//// Get a ClientScriptManager reference from the Page class.
//ClientScriptManager cs = Page.ClientScript;
//// Check to see if the startup script is already registered.
//if (!cs.IsStartupScriptRegistered(cstype, "PopupScript"))
//{
// String cstext = string.Format("alert('{0}');",message);
// cs.RegisterStartupScript(cstype, "PopupScript", cstext, true);
//}
//string display = "Message Pop-up!";
//ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + display + "');", true);
}
}
}
Content Page code
namespace Report_Server.Reports.Vouchers.Pages
{
public partial class Sales_Invoice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ssrs.sendMail += new ssrs.NoArgEventHandler(sendmail);
ReportViewer ReportViewer1 = (ReportViewer)this.Master.FindControl("ReportViewer1");
ReportViewer1.LocalReport.ReportPath = "Reports/Vouchers/Reports/Sale_Invoice_2.rdlc";
var dc = new dsserp.reportlib.Vouchers();
var mst = new dsserp.reportlib.Masters();
TextBox mailaddress = (TextBox)Page.Master.FindControl("mailaddress");
getParams();
try
{
ReportViewer1.ProcessingMode = ProcessingMode.Local;
ReportViewer1.LocalReport.DataSources.Clear();
requestparam.bill = dc.getSalesInvoice(requestparam.sdt, requestparam.edt, requestparam.dist_id, requestparam.acc_code, requestparam.from_no, requestparam.to_no, requestparam.page_no, requestparam.so_code);
if (mailaddress != null)
mailaddress.Text = requestparam.bill[0].d_email;
requestparam.branch = mst.getBranch();
ReportDataSource rds = new ReportDataSource();
rds.Name = "DataSet1";
rds.Value = requestparam.bill;
ReportViewer1.LocalReport.DataSources.Add(rds);
ReportDataSource rd2 = new ReportDataSource();
rd2.Name = "DataSet2";
rd2.Value = requestparam.branch;
ReportViewer1.LocalReport.DataSources.Add(rd2);
ReportParameter[] p = new ReportParameter[13];
p[0] = new ReportParameter("firm_id", requestparam.firm_id.ToString());
p[1] = new ReportParameter("branch_id", requestparam.branch_id);
p[2] = new ReportParameter("div_id", requestparam.div_id);
p[3] = new ReportParameter("sdt", requestparam.sdt.ToShortDateString());
p[4] = new ReportParameter("edt", requestparam.edt.ToShortDateString());
p[5] = new ReportParameter("dist_id", requestparam.dist_id == null ? "null" : requestparam.dist_id.ToString());
p[6] = new ReportParameter("acc_code", requestparam.acc_code == null ? "null" : requestparam.acc_code.ToString());
p[7] = new ReportParameter("from_no", string.IsNullOrEmpty(requestparam.from_no) ? "null" : requestparam.from_no);
p[8] = new ReportParameter("to_no", string.IsNullOrEmpty(requestparam.to_no) ? "null" : requestparam.to_no);
p[9] = new ReportParameter("page", requestparam.page_no == null ? "-1" : requestparam.page_no.ToString());
p[10] = new ReportParameter("ismail", "2");
p[11] = new ReportParameter("UserId", requestparam.UserId);
p[12] = new ReportParameter("so_code", requestparam.so_code == null ? "null" : requestparam.so_code.ToString());
ReportViewer1.LocalReport.SetParameters(p);
ReportViewer1.LocalReport.Refresh();
}
catch (Exception ex)
{
Response.Write(ex.Message);
Response.Write(ex.InnerException);
}
}
}
protected string sendmail(string mailid)
{
if (requestparam.mailSent == false)
{
string message = "Somthing Went Wrong";
var mailViewer1 = new ReportViewer();
mailViewer1.LocalReport.ReportPath = "Reports\\Vouchers\\Reports\\Sale_Invoice_2.rdlc";
ReportDataSource rds = new ReportDataSource();
rds.Name = "DataSet1";
rds.Value = requestparam.bill;
mailViewer1.LocalReport.DataSources.Add(rds);
ReportDataSource rd2 = new ReportDataSource();
rd2.Name = "DataSet2";
rd2.Value = requestparam.branch;
mailViewer1.LocalReport.DataSources.Add(rd2);
ReportParameter[] p = new ReportParameter[13];
p[0] = new ReportParameter("firm_id", requestparam.firm_id.ToString());
p[1] = new ReportParameter("branch_id", requestparam.branch_id);
p[2] = new ReportParameter("div_id", requestparam.div_id);
p[3] = new ReportParameter("sdt", requestparam.sdt.ToShortDateString());
p[4] = new ReportParameter("edt", requestparam.edt.ToShortDateString());
p[5] = new ReportParameter("dist_id", requestparam.dist_id == null ? "null" : requestparam.dist_id.ToString());
p[6] = new ReportParameter("acc_code", requestparam.acc_code == null ? "null" : requestparam.acc_code.ToString());
p[7] = new ReportParameter("from_no", string.IsNullOrEmpty(requestparam.from_no) ? "null" : requestparam.from_no);
p[8] = new ReportParameter("to_no", string.IsNullOrEmpty(requestparam.to_no) ? "null" : requestparam.to_no);
p[9] = new ReportParameter("page", "1");
p[10] = new ReportParameter("ismail", "1");
p[11] = new ReportParameter("UserId", requestparam.UserId);
p[12] = new ReportParameter("so_code", requestparam.so_code == null ? "null" : requestparam.so_code.ToString());
//TextBox mailaddress = (TextBox)Page.Master.FindControl("mailaddress");
//Label mailLabel = (Label)Page.Master.FindControl("mailLabel");
message = "Something Went Wrong";
bool smtpFound = false;
var mst = new dsserp.reportlib.Masters();
var Branch = requestparam.branch[0];
smptuser user = new smptuser();
try
{
user.displayName = Branch.smtp_displyname;
user.hostName = Branch.smtp_host;
user.userId = Branch.smtp_UserId;
user.Password = password.DecryptPass(Branch.smtp_Password);
user.mailAddress = Branch.smtp_mailAddress;
user.Port = Convert.ToInt32(Branch.smtp_port);
if (user.Port > 0)
smtpFound = true;
if (smtpFound)
{
var emailFound = string.IsNullOrEmpty(mailid) == false;
if (emailFound)
{
string filename = requestparam.from_no;
if (requestparam.from_no != requestparam.to_no)
{
filename = filename + "-" + requestparam.to_no;
}
string body = "Dear Sir/Maa'm" + "\r\n" + "\r\n" + "A copy of the invoice " + filename + " has been attached for your reference.";
var _file = Path.Combine(Path.GetTempPath(), filename + ".pdf");
export export = new export();
mailViewer1.LocalReport.SetParameters(p);
export.toFile(mailViewer1.LocalReport, _file);
message = mail.send(_file, mailid, "Invoice No:" + filename, body, user); //"Success:sent"
}
else
message = " Email Address Not Found, Please try again";
}
else
message = "No SMTP Server Found";
}
catch (Exception ex)
{
message = "No SMTP Server Found";
}
if (message == "sent")
message = "Successfuly mail sent";
requestparam.response= message;
}
return requestparam.response;
}
public void getParams()
{
string conn = ConfigurationManager.ConnectionStrings["ReportServerEntities"].ConnectionString;
requestparam.firm_id = Convert.ToInt32(Request.QueryString["firm_id"]);
requestparam.branch_id = Request.QueryString["branch_id"];
requestparam.div_id = Request.QueryString["div_id"];
requestparam.sdt = Convert.ToDateTime(Request.QueryString["sdt"]);
requestparam.edt = Convert.ToDateTime(Request.QueryString["edt"]);
requestparam.dist_id = null;
if (!string.IsNullOrEmpty(Request.QueryString["dist_id"]))
requestparam.dist_id = Convert.ToInt32(Request.QueryString["dist_id"]);
requestparam.acc_code = null;
if (!string.IsNullOrEmpty(Request.QueryString["acc_code"]))
requestparam.acc_code = Convert.ToInt32(Request.QueryString["acc_code"]);
requestparam.from_no = Request.QueryString["from_no"];
requestparam.to_no = Request.QueryString["to_no"];
requestparam.UserId = Request.QueryString["User"];
requestparam.page_no = null;
if (!string.IsNullOrEmpty(Request.QueryString["page_no"]))
requestparam.page_no = Convert.ToInt32(Request.QueryString["page_no"]);
requestparam.so_code = null;
if (!string.IsNullOrEmpty(Request.QueryString["so_code"]))
requestparam.so_code = Convert.ToInt32(Request.QueryString["so_code"]);
properties.connectionstring = conn;
properties.firm_id = requestparam.firm_id;
properties.branch_id = requestparam.branch_id;
properties.div_id = requestparam.div_id;
}
public static class requestparam
{
public static int firm_id { get; set; }
public static string branch_id { get; set; }
public static string div_id { get; set; }
public static string from_no { get; set; }
public static string to_no { get; set; }
public static string UserId { get; set; }
public static DateTime sdt { get; set; }
public static DateTime edt { get; set; }
public static int? dist_id { get; set; }
public static int? acc_code { get; set; }
public static int? page_no { get; set; }
public static int? so_code { get; set; }
public static int? ismail { get; set; }
public static List<Voucher.salesInvoice> bill { get; set; }
public static List<Master.Branch> branch { get; set; }
public static bool mailSent { get; set; }
public static string response { get; set; }
}
}
}
I'm attempting to make a google map using Xamarin forms, the pins displays correctly and zooms in onto the user. It displays the inital map when the page starts, but when moving or zooming the map doesn't change and becomes grids if you zoom in enough. I can see my pin on the grid and everything, but I would like the map to load along with the pin.
public partial class IssueMap2 : ContentPage
{
public UIIssueVM Issue { get; set; }
public GeoLocation Location { get; set; }
public bool AllowPinMovment { get; set; }
private ExtendedMap.ExtendedMap map;
public Xamarin.Forms.Maps.Position OrgIssueLocation { get; set; }
bool IsGettingLocation = false;
bool bMapCtrlReady = false;
IGeolocator Locator;
public IssueMap2(UIIssueVM Issue, GeoLocation location)
{
AllowPinMovment = false;
this.Issue = Issue;
this.Location = location;
Title = "Map";
OrgIssueLocation = new Xamarin.Forms.Maps.Position(Issue.Latitude, Issue.Longitude);
Locator = CrossGeolocator.Current;
if (Locator.DesiredAccuracy != 100)
Locator.DesiredAccuracy = 100;
if (Device.RuntimePlatform != Device.WinPhone)
{
InitializeComponent();
map = new ExtendedMap.ExtendedMap()
{
IsShowingUser = true,
HeightRequest = 100,
WidthRequest = 960,
VerticalOptions = LayoutOptions.FillAndExpand
};
map.LongTap += OnMapLongTap;
map.Ready += MapCtrlReady;
slMap.Children.Add(map);
}
}
public void MapCtrlReady(object sender, EventArgs args)
{
bMapCtrlReady = true;
}
public void OnMapLongTap(object sender, ExtendedMap.TapEventArgs args)
{
if (AllowPinMovment == false)
return;
if (Issue == null)
return;
var pos = args.Position;
// Update Issue
Issue.Latitude = pos.Latitude;
Issue.Longitude = pos.Longitude;
Issue.Changed = true;
// Update Pin
map.Pins.Clear();
AddPin(pos, Issue.Title, Issue.Description);
}
protected void AddPin(Xamarin.Forms.Maps.Position pos, String Title, String Desc)
{
// MAP pin does not like it if labels are empty
if (Title.Length == 0)
Title = "-";
if (Desc.Length == 0)
Desc = "-";
var pin = new Pin
{
Type = PinType.Place,
Position = pos,
Label = Title,
Address = Desc
};
map.Pins.Add(pin);
}
protected override void OnAppearing()
{
if (Device.RuntimePlatform == Device.WinPhone)
{
aActIndicator.IsRunning = false;
aActIndicator.IsVisible = false;
if (Issue.IsNew == false)
{
var position = new Xamarin.Forms.Maps.Position(Issue.Latitude, Issue.Longitude);
AddPin(position, Issue.Title, Issue.Description);
MoveToPinLocation();
}
else // Issue is new
{
// Move to main location
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(Location.Latitude, Location.Longitude), Distance.FromMiles(1)));
// Get current location for new item
OnGetLocation();
}
}
}
protected override async void OnDisappearing()
{
if (Locator.IsListening)
{
await Locator.StopListeningAsync();
}
// Map controller crashes sometimes if we are to quick with exiting
await Task.Delay(500);
while (bMapCtrlReady == false)
{
await Task.Delay(500);
}
}
void OnButtonCenter(object sender, EventArgs args)
{
MoveToPinLocation();
}
void MoveToPinLocation()
{
double KmDistace = 0.5;
if (Issue != null)
{
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(Issue.Latitude, Issue.Longitude), Distance.FromKilometers(KmDistace)));
}
else
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(Location.Latitude, Location.Longitude), Distance.FromKilometers(KmDistace)));
}
void OnButtonMainLocation(object sender, EventArgs args)
{
double KmDistace = 0.5;
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(Location.Latitude, Location.Longitude), Distance.FromKilometers(KmDistace)));
}
void OnButtonGetLocation(object sender, EventArgs args)
{
OnGetLocation();
}
async void OnGetLocation()
{
if (IsGettingLocation == true)
return; // already getting location
try
{
if (Locator.IsListening == true)
{
await Locator.StopListeningAsync();
}
if (Locator.IsGeolocationAvailable == false)
{
lbPosText.Text = "GeoLocation is not available.";
this.ForceLayout();
return;
}
if (Locator.IsGeolocationEnabled == false)
{
lbPosText.Text = "GeoLocation is not enabled.";
this.ForceLayout();
return;
}
IsGettingLocation = true;
IsBusy = true;
slCommands.IsVisible = false;
aActIndicator.IsVisible = true;
aActIndicator.IsRunning = true;
lbPosText.Text = "Searching for GPS location...";
this.ForceLayout();
TimeSpan timeSpan = TimeSpan.FromTicks(120 * 1000);
var position = await Locator.GetPositionAsync(timeSpan);
// Update Issue Position
Issue.Latitude = position.Latitude;
Issue.Longitude = position.Longitude;
Issue.Changed = true;
// Update Pin Postion
var pos = new Xamarin.Forms.Maps.Position(Issue.Latitude, Issue.Longitude);
map.Pins.Clear();
AddPin(pos, Issue.Title, Issue.Description);
UpdateGPSLocationText();
aActIndicator.IsRunning = false;
aActIndicator.IsVisible = false;
IsGettingLocation = false;
IsBusy = false;
slCommands.IsVisible = true;
this.ForceLayout();
// Center map around pin
MoveToPinLocation();
}
catch (Exception /*ex*/)
{
aActIndicator.IsRunning = false;
aActIndicator.IsVisible = false;
IsGettingLocation = false;
IsBusy = false;
slCommands.IsVisible = true;
lbPosText.Text = "Unable to find position!";
lbPosText.IsVisible = true;
this.ForceLayout();
}
}
void UpdateGPSLocationText()
{
String text = String.Format("{0} x {1}", Issue.Longitude, Issue.Latitude);
lbPosText.Text = text;
}
}
}
Android extended map renderer
[assembly: ExportRenderer(typeof(ExtendedMap.ExtendedMap), typeof(ExtendedMapRenderer))]
namespace ExtendedMap.Android
{
public class ExtendedMapRenderer : MapRenderer, IOnMapReadyCallback
{
private GoogleMap _map;
public ExtendedMapRenderer()
{
}
public ExtendedMapRenderer(IntPtr javaReference, JniHandleOwnership jniHandleOwnership)
{
int x = 0;
x++;
}
private void InvokeOnMapReadyBaseClassHack(GoogleMap googleMap)
{
System.Reflection.MethodInfo onMapReadyMethodInfo = null;
Type baseType = typeof(MapRenderer);
foreach (var currentMethod in baseType.GetMethods(System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.DeclaredOnly))
{
if (currentMethod.IsFinal && currentMethod.IsPrivate)
{
if (string.Equals(currentMethod.Name, "OnMapReady", StringComparison.Ordinal))
{
onMapReadyMethodInfo = currentMethod;
break;
}
if (currentMethod.Name.EndsWith(".OnMapReady", StringComparison.Ordinal))
{
onMapReadyMethodInfo = currentMethod;
break;
}
}
}
if (onMapReadyMethodInfo != null)
{
onMapReadyMethodInfo.Invoke(this, new[] { googleMap });
}
}
void IOnMapReadyCallback.OnMapReady(GoogleMap googleMap)
{
InvokeOnMapReadyBaseClassHack(googleMap);
_map = googleMap;
if (_map != null)
{
_map = googleMap;
this.NativeMap = googleMap;
_map.MapClick += googleMap_MapClick;
_map.MapLongClick += googleMap_MapLongClick;
((ExtendedMap)Element).OnReady();
}
}
protected override void OnElementChanged(ElementChangedEventArgs<Map> e)
{
if (_map != null)
_map.MapClick -= googleMap_MapClick;
base.OnElementChanged(e);
if (Control != null)
((MapView)Control).GetMapAsync(this);
}
private void googleMap_MapClick(object sender, GoogleMap.MapClickEventArgs e)
{
((ExtendedMap)Element).OnTap(new Position(e.Point.Latitude, e.Point.Longitude));
}
private void googleMap_MapLongClick(object sender, GoogleMap.MapLongClickEventArgs e)
{
((ExtendedMap)Element).OnLongTap(new Position(e.Point.Latitude, e.Point.Longitude));
}
}
}
I would double check the Google Maps API key on the manifest of your application!
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzr3yCpVgSOXvTgri29nC6KqFbdO73QmoVQWEw" />
As well as your SHA-1 key of your keystore on the Google API Credential Dashboard.
I am having some problems with my Xamarin XAML page and its viewmodel.
I have written the code with a bunch of methods which are executed via commands from the XAML.
Functionally its all working as desired. However, the view is not refreshing when the methods have finished executing. So despite inserting things and removing things from my observable collections (via an API call update), and having a notifypropertychanged event, the page doesn't reload.
Any ideas?
ViewModel (Some properties omitted to fit the character limit for a post)
namespace TechsportiseApp.ViewModels
{
public class ResultsProcessViewModel : INotifyPropertyChanged
{
public ICommand AddTimingCommand { get; set; }
public ICommand AddScanCommand { get; set; }
public ICommand DeleteTimingCommand { get; set; }
public ICommand DeleteScanCommand { get; set; }
public ICommand PublishCommand { get; set; }
public ICommand LoadResultsCommand { get; set; }
public ICommand MissingFinisherCommand { get; set; }
public ICommand MissingTimingCommand { get; set; }
public int RaceId { get; set; }
public DateTime RaceDate { get; set; }
//public ResultsViewModel(Race race)
public ResultsProcessViewModel(Race race)
{
AddTimingCommand = new Command(AddTiming);
AddScanCommand = new Command(AddScan);
DeleteTimingCommand = new Command<int>(DeleteTiming);
DeleteScanCommand = new Command<int>(DeleteScan);
PublishCommand = new Command<string>(Publish);
LoadResultsCommand = new Command<int>(LoadResults);
MissingFinisherCommand = new Command(MissingFinisher);
MissingTimingCommand = new Command(MissingTiming);
Invalid = false;
AddTimingVisibility = false;
AddScanVisibility = false;
AddVisibility = true;
PublishProvisionalVisibility = false;
PublishFinalVisibility = false;
IsBusy = false;
RaceId = race.Id;
RaceDate = race.RaceDate;
RaceStartTime = Convert.ToDateTime(race.RaceStartTime);
Scans = ScansAPI.GetScans(RaceId);
Timings = TimingsAPI.GetTimings(RaceId);
Entries = EntriesAPI.GetEntries(RaceId);
LoadResults(RaceId);
}
ObservableCollection<Result> _results;
public ObservableCollection<Result> Results
{
get
{
return _results;
}
set
{
if (_results != value)
{
_results = value;
OnPropertyChanged("Results");
}
}
}
ObservableCollection<Scan> _scans;
public ObservableCollection<Scan> Scans
{
get
{
return _scans;
}
set
{
if (_scans != value)
{
_scans = value;
OnPropertyChanged("Scans");
}
}
}
ObservableCollection<Timing> _timings;
public ObservableCollection<Timing> Timings
{
get
{
return _timings;
}
set
{
if (_timings != value)
{
_timings = value;
OnPropertyChanged("Timings");
}
}
}
ObservableCollection<RaceEntry> _entries;
public ObservableCollection<RaceEntry> Entries
{
get
{
return _entries;
}
set
{
if (_entries != value)
{
_entries = value;
OnPropertyChanged("Entries");
}
}
}
ObservableCollection<Race> _races;
public ObservableCollection<Race> Races
{
get
{
try
{
var racelist = RacesAPI.GetRaces();
var sortedracelist = new ObservableCollection<Race>(racelist.OrderBy(c => c.Name));
var racecount = racelist.Count();
if (racecount == 0)
{
RaceCountZero = true;
}
else
{
RaceCountZero = false;
}
return racelist;
}
catch
{
Invalid = true;
ValidationError = "Error getting Race List. No internet connection available.";
}
return _races;
}
set
{
if (_races != value)
{
_races = value;
OnPropertyChanged("Races");
}
}
}
string _aboveBelow;
public string AboveBelow
{
get { return _aboveBelow; }
set
{
if (_aboveBelow == value)
return;
_aboveBelow = value;
OnPropertyChanged("AboveBelow");
}
}
string _aboveBelowPosition;
public string AboveBelowPosition
{
get { return _aboveBelowPosition; }
set
{
if (_aboveBelowPosition == value)
return;
_aboveBelowPosition = value;
OnPropertyChanged("AboveBelowPosition");
}
}
string _addHH;
public string AddHH
{
get { return _addHH; }
set
{
if (_addHH == value)
return;
_addHH = value;
OnPropertyChanged("AddHH");
}
}
string _addMM;
public string AddMM
{
get { return _addMM; }
set
{
if (_addMM == value)
return;
_addMM = value;
OnPropertyChanged("AddMM");
}
}
string _addSS;
public string AddSS
{
get { return _addSS; }
set
{
if (_addSS == value)
return;
_addSS = value;
OnPropertyChanged("AddSS");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var changed = PropertyChanged;
if (changed != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
void AddTiming()
{
AddScanVisibility = false;
AddTimingVisibility = !AddTimingVisibility;
}
void AddScan()
{
AddScanVisibility = !AddScanVisibility;
AddTimingVisibility = false;
}
void MissingFinisher()
{
//Do stuff when deleting a scan. It needs to do all this in the observable collection. Then when we submit, we'll update all scans, timings etc with whats in the collection
Task.Run(() =>
{
try
{
var scancount = Scans.Count();
Device.BeginInvokeOnMainThread(() => IsBusy = true);
var IsThereConnection = GlobalFunctions.CheckForInternetConnection();
if (IsThereConnection == false)
throw new Exception("You cannot add a scan whilst you are offline");
else if (string.IsNullOrEmpty(MissingBib))
throw new Exception("You must enter a bib number");
else if (string.IsNullOrEmpty(AboveBelow))
throw new Exception("You must choose if you are adding the bib above or below");
else if (string.IsNullOrEmpty(AboveBelowPosition))
throw new Exception("You must enter the position you are inserting " + AboveBelow);
else if (Convert.ToInt32(AboveBelowPosition) > scancount)
throw new Exception("The position you have chosen to insert above or below does not exist. Please enter a valid value");
else if (Convert.ToInt32(AboveBelowPosition) < 1)
throw new Exception("The position you have chosen to insert above or below does not exist. Please enter a valid value");
//We are good to go
else
{
var InsertedSequence = new int();
var abovebelow = Scans.SingleOrDefault(i => i.Position == Convert.ToInt32(AboveBelowPosition));
var abposition = Convert.ToInt32(AboveBelowPosition);
if (AboveBelow == "Above")
{
InsertedSequence = abovebelow.Sequence + 5;
}
else if (AboveBelow == "Below")
{
InsertedSequence = abovebelow.Sequence - 5;
}
else
{
return;
}
//Need to add resequencing and reallocation of position numbers
var scan = new ScanPost
{
RaceId = RaceId,
BibNumber = MissingBib,
Sequence = InsertedSequence,
Position = abposition,
Reorder = true,
Status = 0
};
var createscan = ScansAPI.CreateScan(scan);
if (createscan.Code != "Created")
throw new Exception("Error creating scan");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
ValidationError = ex.Message;
Invalid = true;
});
return;
}
finally
{
Device.BeginInvokeOnMainThread(() => IsBusy = false);
LoadResults(RaceId);
OnPropertyChanged("Results");
}
});
}
void MissingTiming()
{
Task.Run(() =>
{
try
{
var timingcount = Timings.Count();
Device.BeginInvokeOnMainThread(() => IsBusy = true);
var IsThereConnection = GlobalFunctions.CheckForInternetConnection();
if (IsThereConnection == false)
throw new Exception("You cannot add a timing whilst you are offline");
//We are good to go
else
{
if (AddHH == "") { AddHH = "0"; }
if (AddMM == "") { AddMM = "0"; }
if (AddSS == "") { AddSS = "0"; }
var ManualEndTime = RaceStartTime.AddHours(Convert.ToDouble(AddHH))
.AddMinutes(Convert.ToDouble(AddMM))
.AddSeconds(Convert.ToDouble(AddSS));
var timing = new TimingPost
{
RaceId = RaceId,
StartTime = RaceStartTime,
EndTime = ManualEndTime,
Reorder = true,
Position = 0,
Status = 0
};
var createtiming = TimingsAPI.CreateTiming(timing);
if (createtiming.Code != "Created")
throw new Exception("Error creating timing");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
ValidationError = ex.Message;
Invalid = true;
});
return;
}
finally
{
Device.BeginInvokeOnMainThread(() => IsBusy = false);
Device.BeginInvokeOnMainThread(() => LoadResults(RaceId));
Device.BeginInvokeOnMainThread(() => OnPropertyChanged("Results"));
}
});
}
void DeleteTiming(int timingid)
{
//Do stuff when deleting a timing. It needs to do all this in the observable collection. Then when we submit, we'll update all scans, timings etc with whats in the collection
Task.Run(() =>
{
try
{
Device.BeginInvokeOnMainThread(() => IsBusy = true);
var IsThereConnection = GlobalFunctions.CheckForInternetConnection();
if (IsThereConnection == false)
throw new Exception("You cannot delete a timing whilst you are offline");
//We are good to go
else
{
var deletetiming = TimingsAPI.DeleteTiming(timingid);
if (deletetiming.Code != "NoContent")
throw new Exception("Error deleting timing");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
ValidationError = ex.Message;
Invalid = true;
});
return;
}
finally
{
Device.BeginInvokeOnMainThread(() => IsBusy = false);
LoadResults(RaceId);
OnPropertyChanged("Timings");
Device.BeginInvokeOnMainThread(() => LoadResults(RaceId));
Device.BeginInvokeOnMainThread(() => OnPropertyChanged("Timings"));
}
});
}
void DeleteScan(int scanid)
{
//Do stuff when deleting a scan. It needs to do all this in the observable collection. Then when we submit, we'll update all scans, timings etc with whats in the collection
Task.Run(() =>
{
try
{
Device.BeginInvokeOnMainThread(() => IsBusy = true);
var IsThereConnection = GlobalFunctions.CheckForInternetConnection();
if (IsThereConnection == false)
throw new Exception("You cannot delete a scan whilst you are offline");
//We are good to go
else
{
var deletetiming = TimingsAPI.DeleteTiming(scanid);
if (deletetiming.Code != "NoContent")
throw new Exception("Error deleting scan");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
ValidationError = ex.Message;
Invalid = true;
});
return;
}
finally
{
Device.BeginInvokeOnMainThread(() => IsBusy = false);
LoadResults(RaceId);
OnPropertyChanged("Results");
}
});
}
void Publish(string status)
{
Task.Run(() =>
{
try
{
var publish = new Publish();
publish.RaceId = RaceId;
publish.ResultStatus = status;
Device.BeginInvokeOnMainThread(() => IsBusy = true);
var IsThereConnection = GlobalFunctions.CheckForInternetConnection();
if (IsThereConnection == false)
throw new Exception("You cannot publish results whilst you are offline");
//We are good to go
else
{
var publishrace = RacesAPI.PublishRace(publish);
if (publishrace.Code != "NoContent")
throw new Exception("Error publishing race");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
ValidationError = ex.Message;
Invalid = true;
});
return;
}
finally
{
Device.BeginInvokeOnMainThread(() => IsBusy = false);
LoadResults(RaceId);
OnPropertyChanged("Results");
}
});
}
void LoadResults(int raceid)
{
var results = new ObservableCollection<Result>();
//Start with the timings
foreach (Timing timing in Timings)
{
var result = new Result();
//Basic details
result.RaceId = RaceId;
result.RaceDate = RaceDate;
result.Status = "Processing";
//Timing Data
result.TimingId = timing.Id;
result.TimingPosition = timing.Position;
result.TimingStatus = timing.Status;
result.StartTime = timing.StartTime;
result.EndTime = timing.EndTime;
var elapsed = result.EndTime - result.StartTime;
string elapsedhours = elapsed.Hours.ToString();
string elapsedminutes = elapsed.Minutes.ToString();
string elapsedseconds = elapsed.Seconds.ToString();
string elapsedmillis;
if (elapsed.Milliseconds.ToString().Length > 2)
{
elapsedmillis = elapsed.Milliseconds.ToString().Substring(0, 2);
}
else
{
elapsedmillis = elapsed.Milliseconds.ToString();
}
if (elapsedhours.Length == 1) { elapsedhours = "0" + elapsedhours; }
if (elapsedminutes.Length == 1) { elapsedminutes = "0" + elapsedminutes; }
if (elapsedseconds.Length == 1) { elapsedseconds = "0" + elapsedseconds; }
if (elapsedmillis.Length == 1) { elapsedmillis = "0" + elapsedmillis; }
if((elapsedhours == "00"))
{
result.Elapsed = elapsedminutes + ":" + elapsedseconds + "." + elapsedmillis;
}
else
{
result.Elapsed = elapsedhours + ":" + elapsedminutes + ":" + elapsedseconds + "." + elapsedmillis;
}
results.Add(result);
}
//Add in the scans
foreach (Result result1 in results)
{
var scan = Scans.FirstOrDefault(p => p.Position == result1.TimingPosition);
if (scan != null)
{
result1.ScanId = scan.Id;
result1.ScanPosition = scan.Position;
result1.ScanStatus = scan.Status;
result1.ScanBibNumber = scan.BibNumber;
}
else
{
result1.ScanId = 0;
result1.ScanPosition = 0;
result1.ScanStatus = 99;
result1.ScanBibNumber = "UNKNOWN";
}
}
//Add any scans which there are no times for (Higher than count)
var timingscount = Timings.Count();
var notimescans = new ObservableCollection<Scan>();
foreach (Scan scan in Scans)
{
if (scan.Position > timingscount)
{
var newresult = new Result();
newresult.RaceId = RaceId;
newresult.RaceDate = RaceDate;
newresult.Status = "Processing";
newresult.ScanId = scan.Id;
newresult.ScanPosition = scan.Position;
newresult.ScanStatus = scan.Status;
newresult.ScanBibNumber = scan.BibNumber;
newresult.TimingId = 0;
newresult.TimingPosition = 99999;
newresult.TimingStatus = 99;
newresult.StartTime = RaceStartTime;
newresult.EndTime = RaceStartTime;
var elapsed = newresult.EndTime - newresult.StartTime;
string elapsedhours = elapsed.Hours.ToString();
string elapsedminutes = elapsed.Minutes.ToString();
string elapsedseconds = elapsed.Seconds.ToString();
string elapsedmillis = elapsed.Milliseconds.ToString();
if (elapsedhours.Length == 1) { elapsedhours = "0" + elapsedhours; }
if (elapsedminutes.Length == 1) { elapsedminutes = "0" + elapsedminutes; }
if (elapsedseconds.Length == 1) { elapsedseconds = "0" + elapsedseconds; }
if (elapsedmillis.Length == 1) { elapsedmillis = "0" + elapsedmillis; }
if ((elapsedhours == "00"))
{
newresult.Elapsed = elapsedminutes + ":" + elapsedseconds + "." + elapsedmillis;
}
else
{
newresult.Elapsed = elapsedhours + ":" + elapsedminutes + ":" + elapsedseconds + "." + elapsedmillis;
}
results.Add(newresult);
}
}
//Then add in the entries
foreach (Result result2 in results)
{
var entry = Entries.FirstOrDefault(p => p.BibNumber == result2.ScanBibNumber);
if (entry != null)
{
result2.EntryId = entry.Id;
result2.FirstName = entry.FirstName;
result2.LastName = entry.LastName;
result2.FormattedName = entry.FirstName + " " + entry.LastName.ToUpper();
result2.Gender = entry.Gender;
result2.DateOfBirth = entry.DateOfBirth;
result2.Club = entry.Club;
result2.Team = entry.Team;
result2.EntryBibNumber = entry.BibNumber;
}
else
{
result2.EntryId = 0;
result2.FirstName = "Unknown";
result2.LastName = "ATHLETE";
result2.Gender = "Unknown";
result2.DateOfBirth = DateTime.Now;
result2.Club = "";
result2.Team = "";
result2.EntryBibNumber = "Unknown";
}
}
var sortedresults = new ObservableCollection<Result>(results.OrderBy(c => c.TimingPosition));
Results = sortedresults;
OnPropertyChanged("Results");
}
}
}
Hello someone could help me please, I am making an application in Xamarin android as a project at school, but I have doubts with a checkbox and RecyclerView, what happens is that it assumes that the user can select one or more item within the RecyclerView and when push a poton that btnagregar save all the item name having the Checked property to true in a mysql database
MenuItemA.cs
RecyclerView mRecyclerView;
RecyclerView.LayoutManager mLayoutManager;
RecycleAdapter mAdapter;
List<ItemAli> alilist;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate (bundle);
new I18N.West.CP1250();
new I18N.CJK.CP50220();
int idC = Convert.ToInt32(Intent.GetStringExtra("idc") ?? "Data not available");
SetContentView(Resource.Layout.RecyclerItem);
alilist = new List<ItemAli>();
try
{
string connsqlstring = "";
MySqlConnection sqlconn = new MySqlConnection(connsqlstring);
sqlconn.Open();
DataSet ds = new DataSet();
string queryString = "SELECT `IdAli`, `NombreA`, `Precio`, `Imagen`, `Tiempo` FROM `alimentos` as Item WHERE `IdCategoria` = " + idC;
MySqlDataAdapter adapter = new MySqlDataAdapter(queryString, sqlconn);
adapter.Fill(ds, "Item");
foreach (DataRow row in ds.Tables["Item"].Rows)
{
alilist.Add(new ItemAli { AliID = (row[0]).ToString(), Name = row[1].ToString(), Quantity = 0, Price = Convert.ToDecimal(row[2]), ImageId = row[3].ToString(), Time = row[4].ToString(), AddToOrder = false});
}
sqlconn.Close();
}
catch
{
Toast.MakeText(this, "La categoria esta vacia", ToastLength.Short).Show();
}
Button btnagregar = FindViewById<Button>(Resource.Id.btanadir);
mRecyclerView = FindViewById<RecyclerView>(Resource.Id.rvitem);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.SetLayoutManager(mLayoutManager);
mAdapter = new RecycleAdapter(this,alilist);
mAdapter.ItemClick += OnItemClick;
mAdapter.SpinnerItemSelectionChanged += SpinnerItemSelectionChangedEvent;
mRecyclerView.SetAdapter(mAdapter);
btnagregar.Click += delegate
{
};
}
void OnItemClick(object sender, string IdAlimento)
{
var a = new Intent(this, typeof(ActividadDetAli));
a.PutExtra("idA", IdAlimento);
StartActivity(a);
}
void SpinnerItemSelectionChangedEvent(object sender, AdapterView.ItemSelectedEventArgs e)
{
Spinner spinner = (Spinner)sender;
var itemPosition = Convert.ToInt32 (spinner.Tag);
var currentquantity = alilist[itemPosition].Quantity;
var selectedQuantity = Convert.ToInt32( spinner.GetItemAtPosition (e.Position).ToString());
if (currentquantity != selectedQuantity) {
alilist [itemPosition].Quantity = selectedQuantity;
mAdapter.NotifyItemChanged (itemPosition);
}
}
}
RecycleAdapter.cs
public class VegeViewHolder: RecyclerView.ViewHolder
{
public ImageView Image { get; set; }
public TextView Name { get; set; }
public Spinner Quantity { get; set; }
public TextView Price { get; set; }
public TextView TotalAmount { get; set; }
public CheckBox cbx { get; set; }
public string idA { get; set; }
public VegeViewHolder(View itemView, Action<string> itemlistner, Action<object,AdapterView.ItemSelectedEventArgs> spinnerItemSelected )
:base(itemView)
{
Image = itemView.FindViewById<ImageView> (Resource.Id.list_image);
Name = itemView.FindViewById<TextView> (Resource.Id.Name);
Price = itemView.FindViewById<TextView> (Resource.Id.Price);
Quantity = itemView.FindViewById<Spinner> (Resource.Id.spinner1);
TotalAmount = itemView.FindViewById<TextView> (Resource.Id.total);
cbx = itemView.FindViewById<CheckBox>(Resource.Id.cbc);
itemView.Click += (sender, e) => itemlistner (idA);
Quantity.ItemSelected+= new EventHandler<AdapterView.ItemSelectedEventArgs> (spinnerItemSelected);
}
}
public class RecycleAdapter:RecyclerView.Adapter
{
public event EventHandler<string> ItemClick;
public event EventHandler<AdapterView.ItemSelectedEventArgs> SpinnerItemSelectionChanged;
public List<ItemAli> Items;
Activity Context;
List<string> _quantity = new List<string> ();
public RecycleAdapter (Activity context, List<ItemAli> list)
{
this.Items = list;
this.Context = context;
PopulateSpinnerDropDownValues ();
}
void PopulateSpinnerDropDownValues()
{
_quantity.Add ("0");
_quantity.Add ("1");
_quantity.Add ("2");
_quantity.Add ("3");
_quantity.Add ("4");
_quantity.Add ("5");
_quantity.Add ("6");
_quantity.Add ("7");
_quantity.Add ("8");
_quantity.Add ("9");
_quantity.Add("10");
_quantity.Add("11");
_quantity.Add("12");
_quantity.Add("13");
_quantity.Add("14");
_quantity.Add("15");
}
public override RecyclerView.ViewHolder
OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.From(parent.Context).
Inflate(Resource.Layout.list_items, parent, false);
VegeViewHolder vh = new VegeViewHolder(itemView, OnClick,spinner_ItemSelected);
return vh;
}
public override int ItemCount
{
get { return Items != null ? Items.Count : 0; }
}
void OnClick(string IdAlimento)
{
if (ItemClick != null)
ItemClick (this, IdAlimento);
}
private void spinner_ItemSelected (object sender, AdapterView.ItemSelectedEventArgs e)
{
if (SpinnerItemSelectionChanged != null)
SpinnerItemSelectionChanged (sender, e);
}
public Bitmap GetBitmapFromUrl(string url)
{
using (WebClient webClient = new WebClient())
{
byte[] bytes = webClient.DownloadData(url);
if (bytes != null && bytes.Length > 0)
{
return BitmapFactory.DecodeByteArray(bytes, 0, bytes.Length);
}
}
return null;
}
public override void OnBindViewHolder(RecyclerView.ViewHolder viewHolder, int position)
{
var item = Items[position];
var vh = viewHolder as VegeViewHolder;
var spinnerPos = 0;
var adapter =new ArrayAdapter<String>(Context, Android.Resource.Layout.SimpleSpinnerItem, _quantity);
adapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem);
vh.Name.Text = item.Name;
vh.Price.Text = string.Format("Precio: ${0}",item.Price);
vh.ItemView.Tag = position;
if (item.Quantity > 0) {
spinnerPos = adapter.GetPosition (item.Quantity.ToString ());
vh.TotalAmount.Text = string.Format ("${0}", item.Price * item.Quantity);
} else {
vh.TotalAmount.Text = "";
}
vh.Quantity.Tag = position;
vh.Quantity.Adapter = adapter;
vh.Quantity.SetSelection(spinnerPos);
Bitmap bitmap = GetBitmapFromUrl(item.ImageId);
vh.Image.SetImageBitmap(bitmap);
vh.idA = item.AliID +"°"+ item.ImageId + "°" + item.Name + "°" + item.Price + "°" + item.Time;
vh.cbx.Checked = item.AddToOrder;
}
}
}
Im having trouble with this call logs of the device.
The code is not returning the logs at all, It's giving false data.
Code:
public void ReadCalls()
{
try {
Android.Content.Context myContext = Android.App.Application.Context;
string myDateToCheck = myServiceRef.myTimeToCheck("CallLog");
if (myDateToCheck==null || myDateToCheck=="")
{myDateToCheck = "0";}
ICursor cursor = myContext.ContentResolver.Query( Android.Net.Uri.Parse ("content://call_log/calls"), null, "Date > ?", new string[]{myDateToCheck }, "Date ASC");
if (cursor.MoveToFirst ()) {
while (!cursor.IsAfterLast ) {
if (cursor.GetLong (cursor.GetColumnIndex (CallLog.Calls.Date)) > long.Parse (myDateToCheck)) {
string Number = cursor.GetString (cursor.GetColumnIndex (CallLog.Calls.Number));
string Name = cursor.GetString (cursor.GetColumnIndex (CallLog.Calls.CachedName));
if (Name == null || Name == "") {
Name = "Unknown";
}
string Date = cursor.GetString (cursor.GetColumnIndex (CallLog.Calls.Date));
string Duration = cursor.GetString (cursor.GetColumnIndex (CallLog.Calls.Duration));
string Type = cursor.GetString (cursor.GetColumnIndex (CallLog.Calls.Type));
if (Number == "0") {
Number = "Unknown";
} else if (Number == "-1") {
Number = "Unknown";
}
long num = long.Parse (Date);
Java.Text.SimpleDateFormat simpleDateFormat = new Java.Text.SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
DateTime dateTime = new DateTime (1970, 1, 1).AddMilliseconds ((double)num);
dateTime = dateTime.AddMilliseconds (simpleDateFormat.TimeZone.GetOffset (num));
if (Type == "1") {
Type = "Outgoing";
} else if (Type == "2") {
Type = "Incoming";
} else if (Type == "3") {
Type = "Missed Call";
}
// now need to write it to a database
MyCallLog myLine = new MyCallLog {
TheNumber = Number ,
TheName = Name ,
TheTime = dateTime.ToString() ,
TheDirection = Type ,
TheDuration = Duration
};
string output = Newtonsoft.Json.JsonConvert.SerializeObject (myLine );
myServiceRef.myDatabaseConnection (output);
} else {
break;
}
cursor.MoveToNext ();
}
}
}catch{
}
}
The number is always "-1".
The name is always blank,
and its always an outgoing call.
It gives a datestamp but not accurate.
//static class to convert milisecond to datetime
static class ConvertToDate
{
static readonly DateTime UnixEpochStart = DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc); //Coverting date in to universal
public static DateTime ToDateTimeFromEpoch(this long epochTime)
{
DateTime result = UnixEpochStart.AddMilliseconds(epochTime);
return result;
}
}
Above code might help you. I am also new to Xamarin and above code gives me the appropriate date time. Please let me know if you have any queries.
public class ContactsAdapter : BaseAdapter
{
Activity activity;
List<Contact> contactList;
public ContactsAdapter(Activity activity)
{
this.activity = activity;
FillContacts();
}
void FillContacts()
{
var uri = calllog.ContentUri;
//var uri = ContactsContract.Contacts.ContentUri;
string[] projection = {
calllog.Number,
calllog.Date,
calllog.Duration,
calllog.Type,
calllog.CachedName,
calllog.CachedPhotoId
};
// CursorLoader introduced in Honeycomb (3.0, API11)
var loader = new CursorLoader(activity, uri, projection, null, null, null);
var cursor = (ICursor)loader.LoadInBackground();
contactList = new List<Contact>();
if (cursor.MoveToFirst())
{
do
{
contactList.Add(new Contact
{
Number = cursor.GetString(cursor.GetColumnIndex(projection[0])),
Date = cursor.GetLong(cursor.GetColumnIndex(projection[1])),
Duration = cursor.GetString(cursor.GetColumnIndex(projection[2])),
Type = cursor.GetString(cursor.GetColumnIndex(projection[3])),
Name = cursor.GetString(cursor.GetColumnIndex(projection[4])),
PhotoId = cursor.GetString(cursor.GetColumnIndex(projection[5]))
});
} while (cursor.MoveToNext());
}
}
public override int Count
{
get { return contactList.Count; }
}
public override Java.Lang.Object GetItem(int position)
{
return null;
}
public override long GetItemId(int position)
{
return 0;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
var view = convertView ?? activity.LayoutInflater.Inflate(Resource.Layout.CallLogItems, parent, false);
var callNum = view.FindViewById<TextView>(Resource.Id.NumTxtVw);
var callType = view.FindViewById<ImageView>(Resource.Id.TypeIndicatImgVw);
var calldate = view.FindViewById<TextView>(Resource.Id.CallTime);
var name = view.FindViewById<TextView>(Resource.Id.CallerNameTxtVw);
var contactImg = view.FindViewById<ImageView>(Resource.Id.ContactImgVw);
callNum.Text = contactList[position].Number;
calldate.Text = ConvertToDate.ToDateTimeFromEpoch(contactList[position].Date).ToString();// ToDateTimeFromEpoch(contactList[position].Date).ToString();
if (string.IsNullOrWhiteSpace(contactList[position].Name))
{
name.Text = "Unkown";
}
else
{
name.Text = contactList[position].Name;
}
if (contactList[position].PhotoId == null)
{
contactImg = view.FindViewById<ImageView>(Resource.Id.ContactImgVw);
contactImg.SetImageResource(Resource.Drawable.contactimg);
}
else
{
contactImg = view.FindViewById<ImageView>(Resource.Id.ContactImgVw);
contactImg.SetImageResource(Resource.Drawable.contactimg);
}
if (contactList[position].Type == "1")
{
var contactImage = view.FindViewById<ImageView>(Resource.Id.TypeIndicatImgVw);
contactImage.SetImageResource(Resource.Drawable.incoming);
}
else
if (contactList[position].Type == "2")
{
var contactImage = view.FindViewById<ImageView>(Resource.Id.TypeIndicatImgVw);
contactImage.SetImageResource(Resource.Drawable.outgoing);
}
else
if (contactList[position].Type == "3")
{
var contactImage = view.FindViewById<ImageView>(Resource.Id.TypeIndicatImgVw);
contactImage.SetImageResource(Resource.Drawable.misssedcall);
}
else
if (contactList[position].Type == "4")
{
var contactImage = view.FindViewById<ImageView>(Resource.Id.TypeIndicatImgVw);
contactImage.SetImageResource(Resource.Drawable.voicemail);
}
else
if (contactList[position].Type == "5")
{
var contactImage = view.FindViewById<ImageView>(Resource.Id.TypeIndicatImgVw);
contactImage.SetImageResource(Resource.Drawable.reject);
}
else
if (contactList[position].Type == "6")
{
var contactImage = view.FindViewById<ImageView>(Resource.Id.TypeIndicatImgVw);
contactImage.SetImageResource(Resource.Drawable.blocked);
}
return view;
}
}