First i worked with this tutorial tutorial
to get latitude and longitude, but i get nothing, so this is my code :
[Activity(Label = "GetLocation", MainLauncher = true, Icon = "#drawable/icon")]
public class Activity1 : Activity, ILocationListener
{
private Location _currentLocation;
private LocationManager _locationManager;
private TextView _locationText;
private TextView _addressText;
private string _locationProvider;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
_addressText = FindViewById<TextView>(Resource.Id.address_text);
_locationText = FindViewById<TextView>(Resource.Id.location_text);
FindViewById<TextView>(Resource.Id.get_address_button).Click += AddressButton_OnClick;
InitializeLocationManager();
}
private void InitializeLocationManager()
{
_locationManager = (LocationManager)GetSystemService(LocationService);
var criteriaForLocationService = new Criteria
{
Accuracy = Accuracy.Fine
};
var acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true);
if (acceptableLocationProviders.Any())
{
_locationProvider = acceptableLocationProviders.First();
}
else
{
_locationProvider = String.Empty;
}
}
protected override void OnResume()
{
base.OnResume();
_locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);
}
protected override void OnPause()
{
base.OnPause();
_locationManager.RemoveUpdates(this);
}
private void AddressButton_OnClick(object sender, EventArgs eventArgs)
{
if (_currentLocation == null)
{
_addressText.Text = "Can't determine the current location.";
return;
}
new Thread(() =>
{
var addressText = "Unable to find a location.";
var geocoder = new Geocoder(this);
var addressList = geocoder.GetFromLocation(_currentLocation.Latitude, _currentLocation.Longitude, 50);
var address = addressList.FirstOrDefault();
if (address != null)
{
var deviceLocation = new StringBuilder();
for (var i = 0; i < address.MaxAddressLineIndex; i++)
{
deviceLocation.Append(address.GetAddressLine(i))
.AppendLine(",");
}
_addressText.Text = deviceLocation.ToString();
}
RunOnUiThread(() => { _addressText.Text = addressText; });
}).Start();
}
public void OnLocationChanged(Location location)
{
_currentLocation = location;
if (_currentLocation == null)
{
_locationText.Text = "Unable to determine your location.";
}
else
{
_locationText.Text = String.Format("{0},{1}", _currentLocation.Latitude, _currentLocation.Longitude);
}
}
public void OnProviderDisabled(string provider) { }
public void OnProviderEnabled(string provider) { }
public void OnStatusChanged(string provider, Availability status, Bundle extras) { }
}
So please if someone has any idea about what wrong with my code i will be very appreciative.
There is one spot in your code where you're updating the the UI _addressText.Text from a background thread. That could also account for why, when you click the button, you're not seeing any address updates. See below for a snippet of the one line of code:
if (address != null)
{
var deviceLocation = new StringBuilder();
for (var i = 0; i < address.MaxAddressLineIndex; i++)
{
deviceLocation.Append(address.GetAddressLine(i))
.AppendLine(",");
}
// Here you were updating the UI thread from the background:
RunOnUiThread(() => _addressText.Text = deviceLocation.ToString());
}
Related
I want to get the location changes by the method of OnLocationChanged, I used the OnMyLocationChanged before but I see that this method is already in disuse, but with the new meotodo it marks me error when assigning the mGoogleApiClient variable
namespace FuncionesAndroid.Droid
{
[Activity(Label = "MainMapa")]
public class MainMapa : Activity, IOnMapReadyCallback, IOnMyLocationClickListener, IOnMyLocationButtonClickListener, Android.Gms.Location.ILocationListener, GoogleApiClient.IConnectionCallbacks, GoogleApiClient.IOnConnectionFailedListener
{
private string _tag = "MainMapa";
GoogleMap mapa = null;
DataBase db = new DataBase();
private LocationRequest locationRequest;
static GoogleApiClient mGoogleApiClient;
public static int MILISEGUNDOS_POR_SECUNDOS = 1000;
public static int MINUTO = 60 * MILISEGUNDOS_POR_SECUNDOS;
//private IFusedLocationProviderApi locationProvider = LocationServices.FusedLocationApi;
public async void OnMapReady(GoogleMap googleMap)
{
mapa = googleMap;
googleMap.MyLocationEnabled = true;
googleMap.SetOnMyLocationButtonClickListener(this);
googleMap.SetOnMyLocationClickListener(this);
googleMap.SetMinZoomPreference(6.0F);
//Opcional
googleMap.SetLatLngBoundsForCameraTarget(new LatLngBounds(new LatLng(14.399838, -119.346947),new LatLng(30.706694, -83.355215)));
googleMap.UiSettings.ZoomControlsEnabled = true;
googleMap.UiSettings.CompassEnabled = true;
locationRequest = new LocationRequest();
locationRequest.SetInterval(MINUTO);
locationRequest.SetFastestInterval(15 * MILISEGUNDOS_POR_SECUNDOS);
locationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
try
{
mGoogleApiClient = new GoogleApiClient.Builder(this)
.AddConnectionCallbacks(this)
.AddOnConnectionFailedListener(this)
.AddApi(LocationServices.API)
.Build();
}
catch (Exception e)
{
Log.Debug(_tag, e.Message);
}
googleMap.MoveCamera(CameraUpdateFactory.ZoomIn());
CargarMarcadores();
CentrarMyUbicacion();
}
private void GuardarRutas(ArrayList rutas, int idInicio, int idFin)
{
foreach (ArrayList path in rutas)
{
foreach (Dictionary<String, Double> punto in path)
{
Model.Polyline polyline = new Model.Polyline()
{
id_inicio = idInicio,
id_fin = idFin,
lat = punto["lat"],
lon = punto["lon"]
};
db.InsertarDatoPolyline(polyline, this);
}
}
}
public void CargarMarcadores()
{
BitmapDrawable bitmapClienteDraw = (BitmapDrawable)GetDrawable(Resource.Mipmap.marker_map_us);
Bitmap bitmapCliente = bitmapClienteDraw.Bitmap;
Bitmap smallMarkerCliente = Bitmap.CreateScaledBitmap(bitmapCliente, 60, 90, false);
List<ClientesGps> clientesGps;
clientesGps = db.selectTablaClientesGps(this);
Location miUbicacion = ObtenerUbicacionActual();
foreach (ClientesGps cliente in clientesGps)
{
MarkerOptions clienteMarcador = new MarkerOptions()
.SetPosition(new LatLng(cliente.lat, cliente.lon))
.SetIcon(BitmapDescriptorFactory.FromBitmap(smallMarkerCliente))
.SetTitle(cliente.nombre);
mapa.AddMarker(clienteMarcador);
}
}
public void CentrarMyUbicacion()
{
LocationManager locationManager = (LocationManager)
GetSystemService(Context.LocationService);
Criteria criteria = new Criteria();
criteria.Accuracy = Accuracy.Fine;
Location Ubicación = locationManager.GetLastKnownLocation(locationManager.GetBestProvider(criteria, false));
if (Ubicación != null)
{
LatLng myUbicación = new LatLng(Ubicación.Latitude, Ubicación.Longitude);
mapa.AnimateCamera(CameraUpdateFactory.NewLatLngZoom(myUbicación,15.4F));
}
}
public Location ObtenerUbicacionActual()
{
LocationManager locationManager = (LocationManager)
GetSystemService(Context.LocationService);
Criteria criteria = new Criteria();
criteria.Accuracy = Accuracy.Fine;
Location Ubicación = locationManager.GetLastKnownLocation(locationManager.GetBestProvider(criteria, false));
return Ubicación;
}
public void DibujarRutas(ArrayList rutas, GoogleMap googleMap)
{
PolylineOptions polylineOptions = null;
foreach(ArrayList path in rutas)
{
polylineOptions = new PolylineOptions();
foreach(Dictionary<String, Double> punto in path)
{
double lat, lon;
lat = punto["lat"];
lon = punto["lon"];
polylineOptions.Add(new LatLng(lat, lon));
}
polylineOptions.InvokeWidth(15);
polylineOptions.InvokeColor(Color.Blue);
polylineOptions.Geodesic(true);
}
if(polylineOptions!=null)
{
googleMap.AddPolyline(polylineOptions);
}
else
{
Toast.MakeText(this, "Direcciones no encontradas", ToastLength.Short).Show();
}
}
private async Task<ArrayList> GetUrlAsync(LatLng origin,LatLng dest, String directionMode)
{
String str_origin = "origin=" + origin.Latitude + "," + origin.Longitude;
String str_dest = "destination=" + dest.Latitude + "," + dest.Longitude;
String mode = "mode=" + directionMode;
String parameters = str_origin + "&" + str_dest + "&" + mode;
String output = "json";
JObject json = await Servicios.Servicio.ObtenerRutaGoogleMaps(output, parameters, GetString(Resource.String.GoogleKey));
ArrayList routes = new ArrayList();
JArray jRoutes = null;
JArray jLegs = null;
JArray jSteps = null;
try
{
jRoutes = (JArray)json["routes"];
for (int i = 0; i < jRoutes.Count; i++)
{
jLegs = (JArray)jRoutes[i]["legs"];
ArrayList path = new ArrayList();
for (int j = 0; j < jLegs.Count; j++)
{
jSteps = (JArray)jLegs[j]["steps"];
for (int k = 0; k < jSteps.Count; k++)
{
String polyline = "";
polyline = (String)jSteps[k]["polyline"]["points"];
ArrayList list = decodePolyline(polyline);
for(int l = 0; l < list.Count; l++)
{
Dictionary<String, Double> hm = new Dictionary<string, Double>();
hm.Add("lat", ((LatLng)list[l]).Latitude);
hm.Add("lon", ((LatLng)list[l]).Longitude);
path.Add(hm);
}
}
routes.Add(path);
}
}
return routes;
}
catch (JsonReaderException e)
{
routes = null;
return routes;
}
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.MainMapa);
MapFragment mapFragment = (MapFragment)FragmentManager.FindFragmentById(Resource.Id.map);
mapFragment.GetMapAsync(this);
}
protected override void OnResume()
{
base.OnResume();
if(mGoogleApiClient.IsConnected)
{
RequestLocationUpdates();
}
}
protected override void OnStart()
{
base.OnStart();
mGoogleApiClient.Connect();
}
protected override void OnStop()
{
base.OnStop();
mGoogleApiClient.Disconnect();
}
private void RequestLocationUpdates()
{
LocationServices.FusedLocationApi.RequestLocationUpdates(mGoogleApiClient, locationRequest, this);
}
protected override void OnPause()
{
base.OnPause();
LocationServices.FusedLocationApi.RemoveLocationUpdates(mGoogleApiClient, this);
}
public void OnMyLocationClick(Location location)
{
Toast.MakeText(this, "My Ubicación actual", ToastLength.Short).Show();
}
public bool OnMyLocationButtonClick()
{
Toast.MakeText(this, "Centrando en ubicación actual", ToastLength.Short).Show();
return false;
}
public async void OnLocationChanged(Location location)
{
Toast.MakeText(this, location.ToString(),ToastLength.Short).Show();
}
public void OnConnectionFailed(ConnectionResult result)
{
//throw new NotImplementedException();
}
public void OnConnected(Bundle connectionHint)
{
RequestLocationUpdates();
}
public void OnConnectionSuspended(int cause)
{
//throw new NotImplementedException();
}
}
}
Likewise, I have seen some codes that are not in disuse, that do not use the Google AppClient, but do not explain the use or are not very well documented, if they have some better code I would appreciate it very much
The solution was very simple and silly, I read in another forum, when it comes to GoogleApiClient is normal to fail the first in Xamarin, the right thing is to clean and recompile the solution when it comes to it, thank you very much as you want to read !
I have using freshmvvm for my xamarin forms application. FreshTabbedNavigationContainer tabbed page is working fine with android. I have customized the android tabbed page font size, font color, image size. But in IOS I don't know how to change the tab bar from bottom to top like in android and how to change the size of the icon and font. Please anyone suggest me to done this. My tabbed page code is below,
var tabbedPage = new FreshTabbedNavigationContainer();
tabbedPage.AddTab<FirstPageModel>("One", "icon.png");
tabbedPage.AddTab<SecondPageModel>("Two", "icon.png");
await Application.Current.MainPage.Navigation.PushAsync(tabbedPage);
NavigationPage.SetHasNavigationBar(tabbedPage, false);
I have changed the tabbar scrollable using custom renderer for android like this,
public override void OnViewAdded(Android.Views.View child)
{
base.OnViewAdded(child);
var tabLayout = child as TabLayout;
if (tabLayout != null)
{
tabLayout.TabMode = TabLayout.ModeScrollable;
}
}
How to change the tab bar as scrollable for ios. In my tabbed page, the space between text and icon is zero. Please refer the screenshot.
Naxam's GitHub has sort of a similar implementation using a Customized version of Xamarin Forms TabbedPage, But since FreshTabbedNavigationContainer inherits from the same(TabbedPage) you can just use it instead and it should work like a charm.
public class TopTabbedPage : FreshTabbedNavigationContainer
{
public TopTabbedPage()
{
//BarBackgroundColor = Color.Blue;
//BarTextColor = Color.White;
}
public static readonly BindableProperty BarIndicatorColorProperty = BindableProperty.Create(
nameof(BarIndicatorColor),
typeof(Color),
typeof(TopTabbedPage),
Color.White,
BindingMode.OneWay);
public Color BarIndicatorColor
{
get { return (Color)GetValue(BarIndicatorColorProperty); }
set { SetValue(BarIndicatorColorProperty, value); }
}
public static readonly BindableProperty SwipeEnabledColorProperty = BindableProperty.Create(
nameof(SwipeEnabled),
typeof(bool),
typeof(TopTabbedPage),
true,
BindingMode.OneWay);
public bool SwipeEnabled
{
get { return (bool)GetValue(SwipeEnabledColorProperty); }
set { SetValue(SwipeEnabledColorProperty, value); }
}
}
And then the renderer would look something like this:
[assembly: ExportRenderer(typeof(TopTabbedPage), typeof(TopTabbedRenderer))]
namespace Naxam.Controls.Platform.iOS
{
using Platform = Xamarin.Forms.Platform.iOS.Platform;
using Forms = Xamarin.Forms.Forms;
public partial class TopTabbedRenderer :
UIViewController
{
public static void Init()
{
}
UIColor _defaultBarColor;
bool _defaultBarColorSet;
bool _loaded;
Size _queuedSize;
int lastSelectedIndex;
Page Page => Element as Page;
UIPageViewController pageViewController;
protected UIViewController SelectedViewController;
protected IList<UIViewController> ViewControllers;
protected IPageController PageController
{
get { return Page; }
}
protected TopTabbedPage Tabbed
{
get { return (TopTabbedPage)Element; }
}
protected TabsView TabBar;
private NSLayoutConstraint tabBarHeight;
public TopTabbedRenderer()
{
ViewControllers = new UIViewController[0];
pageViewController = new UIPageViewController(
UIPageViewControllerTransitionStyle.Scroll,
UIPageViewControllerNavigationOrientation.Horizontal,
UIPageViewControllerSpineLocation.None
);
TabBar = new TabsView
{
TranslatesAutoresizingMaskIntoConstraints = false
};
TabBar.TabsSelectionChanged += HandleTabsSelectionChanged;
}
public override void DidRotate(UIInterfaceOrientation fromInterfaceOrientation)
{
base.DidRotate(fromInterfaceOrientation);
View.SetNeedsLayout();
}
public override void ViewDidAppear(bool animated)
{
PageController.SendAppearing();
base.ViewDidAppear(animated);
}
public override void ViewDidDisappear(bool animated)
{
base.ViewDidDisappear(animated);
PageController.SendDisappearing();
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
View.AddSubview(TabBar);
AddChildViewController(pageViewController);
View.AddSubview(pageViewController.View);
pageViewController.View.TranslatesAutoresizingMaskIntoConstraints = false;
pageViewController.DidMoveToParentViewController(this);
var views = NSDictionary.FromObjectsAndKeys(
new NSObject[] {
TabBar,
pageViewController.View
},
new NSObject[] {
(NSString) "tabbar",
(NSString) "content"
}
);
View.AddConstraints(NSLayoutConstraint.FromVisualFormat("V:|-0-[tabbar]-0-[content]-0-|",
0,
null,
views));
View.AddConstraints(NSLayoutConstraint.FromVisualFormat("H:|-0-[tabbar]-0-|",
0,
null,
views));
View.AddConstraints(NSLayoutConstraint.FromVisualFormat("H:|-0-[content]-0-|",
0,
null,
views));
tabBarHeight = NSLayoutConstraint.Create(
TabBar,
NSLayoutAttribute.Height,
NSLayoutRelation.Equal,
1, 68
);
TabBar.AddConstraint(tabBarHeight);
if (pageViewController.ViewControllers.Length == 0
&& lastSelectedIndex >= 0 || lastSelectedIndex < ViewControllers.Count)
{
pageViewController.SetViewControllers(
new[] { ViewControllers[lastSelectedIndex] },
UIPageViewControllerNavigationDirection.Forward,
true, null
);
}
UpdateSwipe(Tabbed.SwipeEnabled);
pageViewController.DidFinishAnimating += HandlePageViewControllerDidFinishAnimating;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
PageController?.SendDisappearing();
if (Tabbed != null)
{
Tabbed.PropertyChanged -= OnPropertyChanged;
Tabbed.PagesChanged -= OnPagesChanged;
TabBar.TabsSelectionChanged -= HandleTabsSelectionChanged;
}
if (pageViewController != null)
{
pageViewController.WeakDataSource = null;
pageViewController.DidFinishAnimating -= HandlePageViewControllerDidFinishAnimating;
pageViewController?.Dispose();
}
}
base.Dispose(disposing);
}
protected virtual void OnElementChanged(VisualElementChangedEventArgs e)
{
ElementChanged?.Invoke(this, e);
}
UIViewController GetViewController(Page page)
{
var renderer = Platform.GetRenderer(page);
return renderer?.ViewController;
}
void OnPagePropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName != Page.TitleProperty.PropertyName)
return;
if (!(sender is Page page) || page.Title is null)
return;
TabBar.ReplaceItem(page.Title, Tabbed.Children.IndexOf(page));
}
void OnPagesChanged(object sender, NotifyCollectionChangedEventArgs e)
{
e.Apply((o, i, c) => SetupPage((Page)o, i), (o, i) => TeardownPage((Page)o, i), Reset);
SetControllers();
UIViewController controller = null;
if (Tabbed.CurrentPage != null)
{
controller = GetViewController(Tabbed.CurrentPage);
}
if (controller != null && controller != SelectedViewController)
{
SelectedViewController = controller;
var index = ViewControllers.IndexOf(SelectedViewController);
MoveToByIndex(index);
TabBar.SelectedIndex = index;
}
}
void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(TabbedPage.CurrentPage))
{
var current = Tabbed.CurrentPage;
if (current == null)
return;
var controller = GetViewController(current);
if (controller == null)
return;
SelectedViewController = controller;
var index = ViewControllers.IndexOf(SelectedViewController);
MoveToByIndex(index);
TabBar.SelectedIndex = index;
}
else if (e.PropertyName == TabbedPage.BarBackgroundColorProperty.PropertyName)
{
UpdateBarBackgroundColor();
}
else if (e.PropertyName == TabbedPage.BarTextColorProperty.PropertyName)
{
UpdateBarTextColor();
}
else if (e.PropertyName == TopTabbedPage.BarIndicatorColorProperty.PropertyName)
{
UpdateBarIndicatorColor();
}
else if (e.PropertyName == TopTabbedPage.SwipeEnabledColorProperty.PropertyName)
{
UpdateSwipe(Tabbed.SwipeEnabled);
}
}
public override UIViewController ChildViewControllerForStatusBarHidden()
{
var current = Tabbed.CurrentPage;
if (current == null)
return null;
return GetViewController(current);
}
void UpdateSwipe(bool swipeEnabled)
{
pageViewController.WeakDataSource = swipeEnabled ? this : null;
}
void Reset()
{
var i = 0;
foreach (var page in Tabbed.Children)
{
SetupPage(page, i++);
}
}
void SetControllers()
{
var list = new List<UIViewController>();
var titles = new List<string>();
for (var i = 0; i < Tabbed.Children.Count; i++)
{
var child = Tabbed.Children[i];
var v = child as VisualElement;
if (v == null)
continue;
var renderer = Platform.GetRenderer(v);
if (renderer == null) continue;
list.Add(renderer.ViewController);
titles.Add(Tabbed.Children[i].Title);
}
ViewControllers = list.ToArray();
TabBar.SetItems(titles);
}
void SetupPage(Page page, int index)
{
IVisualElementRenderer renderer = Platform.GetRenderer(page);
if (renderer == null)
{
renderer = Platform.CreateRenderer(page);
Platform.SetRenderer(page, renderer);
}
page.PropertyChanged -= OnPagePropertyChanged;
page.PropertyChanged += OnPagePropertyChanged;
}
void TeardownPage(Page page, int index)
{
page.PropertyChanged -= OnPagePropertyChanged;
Platform.SetRenderer(page, null);
}
void UpdateBarBackgroundColor()
{
if (Tabbed == null || TabBar == null)
return;
var barBackgroundColor = Tabbed.BarBackgroundColor;
if (!_defaultBarColorSet)
{
_defaultBarColor = TabBar.BackgroundColor;
_defaultBarColorSet = true;
}
TabBar.BackgroundColor = barBackgroundColor.ToUIColor();
}
void UpdateBarTextColor()
{
TabBar.TextColor = Tabbed.BarTextColor.ToUIColor();
}
void UpdateBarIndicatorColor()
{
TabBar.IndicatorColor = Tabbed.BarIndicatorColor.ToUIColor();
}
}
}
I have coded my behind code logic in xaml.cs file and now i want to move my code from code behind to ViewModel. How can this be done apart from code refactoring.
I am new to xamarin
Here is my Code behind
namespace _somename
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CareingtonFeeSchedule : ContentPage
{
private OneDentalFeeScheduleService oneDentalFeeScheduleService;
private ObservableCollection<ProviderSearchViewModel> _allGroups;
private ObservableCollection<ProviderSearchViewModel> _expandedGroups;
protected ObservableCollection<Grouping<string, FeeScheduleItem>> feeScheduleGroups;
protected ObservableCollection<FeeScheduleItem> feeScheduleItems;
private readonly AppViewModel AppViewModelInstance;
private Plugin.Geolocator.Abstractions.Position currentPosition;
private FeeScheduleModel feeScheduleDataResult;
public CareingtonFeeSchedule(AppViewModel appViewModel)
{
InitializeComponent();
AppViewModelInstance = appViewModel;
BindingContext = AppViewModelInstance;
AppViewModelInstance.IsActivityLoading = true;
LoadFeeeSchedule();
}
private void HeaderTapped(object sender, EventArgs args)
{
int selectedIndex = _expandedGroups.IndexOf(
((ProviderSearchViewModel)((Button)sender).CommandParameter));
_allGroups[selectedIndex].Expanded = !_allGroups[selectedIndex].Expanded;
UpdateListContent();
}
async Task OnHomeFeeScheduleTapped_TappedAsync(object sender, EventArgs args)
{
await Navigation.PushAsync(new AccLandPage(AppViewModelInstance));
}
private void ProviderBar_TextChanged(object sender, TextChangedEventArgs e)
{
var keyword = ProviderSearchBar.Text;
GroupedView.ItemsSource =
_expandedGroups.Where(s =>
s.Title.ToLower().Contains(keyword.ToLower()));
}
private void UpdateListContent()
{
_expandedGroups = new ObservableCollection<ProviderSearchViewModel>();
foreach (ProviderSearchViewModel group in _allGroups)
{
ProviderSearchViewModel newGroup = new ProviderSearchViewModel(group.Title, group.ShortName, group.Expanded);
if (group.Expanded)
{
foreach (Plan plan in group)
{
newGroup.Add(plan);
}
}
_expandedGroups.Add(newGroup);
}
GroupedView.ItemsSource = _expandedGroups;
}
public FeeScheduleModel FeeScheduleDataResult
{
protected set
{
feeScheduleDataResult = value;
OnPropertyChanged(nameof(FeeScheduleDataResult));
}
get => feeScheduleDataResult;
}
protected int feeScheduleCount;
public int FeeScheduleCount => feeScheduleCount;
private async Task<bool> LoadFeeeSchedule()
{
try
{
if (oneDentalFeeScheduleService == null)
{
oneDentalFeeScheduleService = new OneDentalFeeScheduleService("1dental.com");
}
var feeSchedRes = await oneDentalFeeScheduleService.GetFeeScheduleAsync(AppViewModelInstance.ZipCode, string.Empty, CancellationToken.None);
if (feeSchedRes?.Schedule?.Count > 0)
{
ConvertFeeScheuleDict(feeSchedRes.Schedule);
}
else FeeScheduleDataResult = null;
return true;
}
catch (Exception eX)
{
with the fee schedule lookup: \n{eX.Message}", "OK");
return false;
}
finally
{
AppViewModelInstance.IsActivityLoading = false;
actInd.IsRunning = false;
}
}
private void ConvertFeeScheuleDict(Dictionary<string, List<FeeScheduleItem>> feesche)
{
ObservableCollection<ProviderSearchViewModel> list = new ObservableCollection<ProviderSearchViewModel>();
ProviderSearchViewModel psm = null;
foreach (var item in feesche)
{
psm = new ProviderSearchViewModel(item.Key, "");
foreach (var valitem in item.Value)
{
Plan p = new Plan();
p.Code = valitem.Code;
p.CostDisplay = valitem.CostDisplay;
p.Description = valitem.ProcedureSecondary;
p.Name = valitem.Procedure;
psm.Add(p);
}
list.Add(psm);
}
_allGroups = list;
UpdateListContent();
}
private async void GetZipCode()
{
try
{
if (AppViewModelInstance.UserPosition == null)
{
try
{
var hasPermission = await Utils.CheckPermissions(Permission.Location);
if (!hasPermission)
{
await Navigation.PushAsync(new MainScreen());
return;
}
}
catch (Exception ex)
{
Debug.WriteLine($"Exception occurred while looking permission during Appearing event: {ex}");
}
var locator = CrossGeolocator.Current;
currentPosition = await locator.GetPositionAsync(new TimeSpan(0, 0, 0, 10, 0));
var addressList = await locator.GetAddressesForPositionAsync(currentPosition, null);
AppViewModelInstance.UserPosition = currentPosition;
foreach (var item in addressList)
{
AppViewModelInstance.ZipCode = item.PostalCode;
ZipCodeEntry.Text = item.PostalCode;
break;
}
}
else
{
var locator = CrossGeolocator.Current;
currentPosition = AppViewModelInstance.UserPosition;
var addressList = await locator.GetAddressesForPositionAsync(currentPosition, null);
foreach (var item in addressList)
{
AppViewModelInstance.ZipCode = item.PostalCode;
ZipCodeEntry.Text = item.PostalCode;
break;
}
}
LoadFeeeSchedule();
}
catch (Exception ex)
{
Debug.WriteLine($"Exception occurred while looking up location during Appearing event: {ex}");
}
}
private void ZipCodeEntry_Complete(object sender, EventArgs e)
{
if (sender != null)
{
AppViewModelInstance.ZipCode = ((Entry)sender).Text;
}
}
private void ZipCodeEntry_Changed(object sender, EventArgs e)
{
if (sender != null)
{
string _text = ((Entry)sender).Text; //Get Current Text
if (_text.Length > 5) //If it is more than your character restriction
{
_text = _text.Remove(_text.Length - 1); // Remove Last character
ZipCodeEntry.Text = _text; //Set the Old value
}
if (_text.Length == 5)
{
AppViewModelInstance.ZipCode = _text;
LoadFeeeSchedule();
}
}
}
public bool CanRefreshExecute(string tempVal = null)
{
if (AppViewModelInstance.IsRefreshing) return false;
var valToCheck = tempVal ?? AppViewModelInstance.ZipCode;
if (string.IsNullOrEmpty(valToCheck) || string.IsNullOrWhiteSpace(valToCheck)) return false;
bool isDigitString = true;
foreach (var c in valToCheck)
{
if (char.IsDigit(c)) continue;
isDigitString = false;
}
if (isDigitString) AppViewModelInstance.ZipCode = valToCheck;
return isDigitString;
}
private void GroupedView_ItemTapped(object sender, ItemTappedEventArgs e)
{
}
}
}
just export your code to the view model and set the view model as binding context of the Page. For example in the constructor:
//In the code behind
PageViewModel viewModel;
public Page()
{
this.BindingContext = viewModel = new PageViewModel();
//...
}
The ViewModel should implement INotifyPropertyChanged.
(Functions which are triggered by events have to stay in the code behind and access the view model through the ViewModel Property)
I am building a Xamarin.Android application for a Zebra TC-70 Android device. My main activity runs the scanner just fine the first time through. It gets the data from the scanner and then passes data to another activity just fine. If I cancel the new activity or complete my work and return to the first activity, the scanner does not re-initialize. Here is my code:
[Activity(Label = "MyApp", MainLauncher = true, Icon = "#mipmap/icon",
ScreenOrientation = ScreenOrientation.Portrait)]
public class MainActivity : AppCompatActivity, EMDKManager.IEMDKListener
{
//EMDK
private BarcodeManager _barcodeManager;
private EMDKManager _emdkManager;
private EditText _scanBarcodeEditText;
private Scanner _scanner;
void EMDKManager.IEMDKListener.OnClosed()
{
if(_emdkManager != null)
{
_emdkManager.Release();
_emdkManager = null;
}
}
void EMDKManager.IEMDKListener.OnOpened(EMDKManager p0)
{
_emdkManager = p0;
InitScanner();
}
protected override void OnResume()
{
base.OnResume();
var intent = new Intent(this, typeof(FpmsDataService));
BindService(intent, _dataServiceConnection, Bind.AutoCreate);
_scanBarcodeEditText.Text = string.Empty;
InitScanner();
}
protected override void OnPause()
{
base.OnPause();
UnbindService(_dataServiceConnection);
DeinitScanner();
if (_emdkManager != null)
{
_emdkManager.Release();
_emdkManager = null;
}
}
protected override void OnDestroy()
{
base.OnDestroy();
DeinitScanner();
if(_emdkManager != null)
{
_emdkManager.Release();
_emdkManager = null;
}
Log.Information("Destroyed FirePMS MainActivity");
Log.CloseAndFlush();
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Window.SetFlags(WindowManagerFlags.KeepScreenOn, WindowManagerFlags.KeepScreenOn);
SetContentView(Resource.Layout.Main);
_scanBarcodeEditText = FindViewById<EditText>(Resource.Id.MaintenanceScanBarcode_EditText);
//Initialize Scanner
var results = EMDKManager.GetEMDKManager(Application.Context, this);
}
private void InitScanner()
{
if(_emdkManager != null)
{
if(_barcodeManager == null)
{
try
{
//Get the feature object such as BarcodeManager object for accessing the feature.
_barcodeManager = (BarcodeManager)_emdkManager.GetInstance(EMDKManager.FEATURE_TYPE.Barcode);
_scanner = _barcodeManager.GetDevice(BarcodeManager.DeviceIdentifier.Default);
if (_scanner != null)
{
//Attach the Data Event handler to get the data callbacks.
_scanner.Data += Scanner_Data;
_scanner.Status += Scanner_Status;
_scanner.Enable();
}
else
{
Log.Error("Failed to enable scanner");
}
}
catch (ScannerException e)
{
Log.Error(e.Message);
}
catch (Exception ex)
{
Log.Error(ex.Message);
}
}
}
}
private void Scanner_Status(object sender, Scanner.StatusEventArgs e)
{
var state = e.P0.State;
if(state == StatusData.ScannerStates.Idle)
{
try
{
if (_scanner.IsEnabled &&
!_scanner.IsReadPending)
{
SetScannerConfig();
_scanner.Read();
}
}
catch (ScannerException e1)
{
Log.Error(e1.Message);
}
}
}
private void DeinitScanner()
{
if(_emdkManager != null)
{
if(_scanner != null)
{
try
{
_scanner.CancelRead();
_scanner.Disable();
_scanner.Data -= Scanner_Data;
_scanner.Status -= Scanner_Status;
_scanner.Release();
}
catch (ScannerException e)
{
Log.Error(e.Result.Description);
}
}
}
if (_barcodeManager != null)
{
_emdkManager.Release(EMDKManager.FEATURE_TYPE.Barcode);
}
_barcodeManager = null;
_scanner = null;
}
private void SetScannerConfig()
{
var config = _scanner.GetConfig();
config.SkipOnUnsupported = ScannerConfig.SkipOnUnSupported.None;
config.ScanParams.DecodeLEDFeedback = true;
config.ReaderParams.ReaderSpecific.ImagerSpecific.PicklistEx = ScannerConfig.PicklistEx.Hardware;
config.DecoderParams.Code39.Enabled = true;
config.DecoderParams.Code128.Enabled = false;
_scanner.SetConfig(config);
}
private void Scanner_Data(object sender, Scanner.DataEventArgs e)
{
var scanDataCollection = e.P0;
if((scanDataCollection != null) && (scanDataCollection.Result == ScannerResults.Success))
{
var scanData = scanDataCollection.GetScanData();
if (scanData[0].Data == null)
{
return;
}
RunOnUiThread(() => _scanBarcodeEditText.Text = scanData[0].Data);
RunOnUiThread(ProcessScan);
}
}
private void ProcessScan()
{
if (string.IsNullOrEmpty(_scanBarcodeEditText.Text))
{
Toast.MakeText(this, "You must scan or enter a barcode to begin", ToastLength.Long).Show();
return;
}
else
{
var intent = new Intent(this, typeof(SecondActivity));
intent.PutExtra("ScannedData",_scanBarcodeEditText.Text);
StartActivity(intent)
}
}
}
Any suggestions would be greatly appreciated. As I indicated, the process works just fine the first time, it's when I return to this activity that the scanner is no longer initialized and doesn't come back.
I suspect the EMDK is not being properly released before the activity is restarted. If you take a look at the following article, though using Java the principle is the same and the advice there is to release the EMDK in onStop(). See the note about managing the EMDK instance about half way down.
I am a developing an application (apk) it is nothing but a display of stored images & bitmap images (url).This is my first application & I am using code by watching different tutorials that i need to code over youtube and searching websites to get help.
Below here is the whole code for application.
namespace androidapk
{
[Activity(Label = "android", MainLauncher = true, Icon = "#drawable/icon")]
public class Activity : Android.App.Activity
{
private ImageView ImageContainer;
// private ImageView UrlContainer;
private int CurrentImage = 0;
// private int CurrentUrl = 0;
private Button nextClick;
private Button backClick;
int[] images = { Resource.Drawable.orange, Resource.Drawable.Icon, Resource.Drawable.images02, Resource.Drawable.buttonarrow, Resource.Drawable.images };
// string[] Urls = { "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRiFsZgrhpFIx496REDS7XimTQVo07W6zFwULlNFIO3OpgPNCMc,https://www.google.com.pk/imgres?imgurl=http%3A%2F%2Fpngimg.com%2Fupload%2Fwater_PNG3290.png&imgrefurl=http%3A%2F%2Fpngimg.com%2Fimg%2Fnature%2Fwater&docid=egiWzVBWw_5-bM&tbnid=geXqbWHLhH-PPM%3A&w=1280&h=798&bih=667&biw=1366&ved=0ahUKEwitguqNm8POAhWHWhQKHc_TBewQMwgxKAEwAQ&iact=mrc&uact=8" };
public Action<object, EventArgs> Click { get; private set; }
public int FindViewByIddemoImageview { get; private set; }
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
nextClick = (Button)FindViewById(Resource.Id.Btnup);
backClick = (Button)FindViewById(Resource.Id.Btnback);
ImageContainer = (ImageView)FindViewById(Resource.Id.demoImageView);
// UrlContainer = (ImageView)FindViewById();
//Android.Net.Uri url = Android.Net.Uri.Parse("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRiFsZgrhpFIx496REDS7XimTQVo07W6zFwULlNFIO3OpgPNCMc");
var imageBitmap = GetImageBitmapFromUrl("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRiFsZgrhpFIx496REDS7XimTQVo07W6zFwULlNFIO3OpgPNCMc");
RunOnUiThread(() => ImageContainer.SetImageBitmap(imageBitmap));
nextClick.Click += delegate {
NextImagePic();
// NextImageUrl();
};
backClick.Click += delegate {
BackImagePic();
};
//HapticFeedbackConstants
}
private Bitmap GetImageBitmapFromUrl(string url)
{
Bitmap imageBitmap = null;
using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}
return imageBitmap;
}
private void NextImagePic()
{
if (CurrentImage == 0)
{
RunOnUiThread(() => ImageContainer.SetImageResource(images[CurrentImage + 1]));
CurrentImage++;
}
else
{
if (CurrentImage < images.Count() - 1)
{
CurrentImage++;
RunOnUiThread(() => ImageContainer.SetImageResource(images[CurrentImage]));
}
else
{
Toast.MakeText(this, "This is last image.", ToastLength.Long).Show();
}
}
}
private void BackImagePic()
{
if (CurrentImage == 0)
{
RunOnUiThread(() => ImageContainer.SetImageResource(images[CurrentImage]));
Toast.MakeText(this, "This is first image.", ToastLength.Long).Show();
}
else
{
CurrentImage--;
RunOnUiThread(() => ImageContainer.SetImageResource(images[CurrentImage]));
}
}
}
}
i have displayed successfully images stored using arrays [] but i want to display multiple images in arrays using URL's I have displayed single image using single URL.