I am using Xamarin android
I have Spinner , When I use the setAdapter function I get this error
Error 3 'Android.Widget.Spinner' does not contain a definition for 'setAdepter' and no extension method 'setAdepter' accepting a first argument of type 'Android.Widget.Spinner' could be found (are you missing a using directive or an assembly reference?)
This is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace FSF
{
[Activity(Label = "Request")]
public class RequestHolidayActivity : Activity
{
Spinner spinner_holidayType;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.RequestHoliday);
spinner_holidayType = FindViewById<Spinner>(Resource.Id.RequestHoliday_spinner_holidayT);
var items = new List<string>() { "first", "second", "third", "forth" };
var adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerItem, items);
spinner_holidayType.setAdepter(adapter);
}
}
}
I tried to solve it , but I didn't find a solution.
There is not SetAdapter method. Instead use the Adapter property and change your code to: spinner_holydayType.Adapter = adapter;
Related
I am currently busy with a Xamarin mobile application (only android now) and I am trying to show PDF files. I found a free plugin here: https://github.com/xamarin/docs-archive/tree/master/Recipes/xamarin-forms/Controls/display-pdf but I run into an issue.
When I go to the view I see the PDF controls, but not the PDF itself. (shows a gray screen). Here is a similar issue: display local PDF file in webview control - Displays Blank Pdf File but nothing is working.
I put the PDF file in the correct place with the correct options, see here:
And here you can see the view in the emulator:
I also tried the run the given demo project, but I get a lot of errors :(
Some help would be really appreciated!
CustomView:
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
namespace BizzTimeTest.ViewModels
{
public class CustomPDFWebView : WebView
{
public static readonly BindableProperty UriProperty = BindableProperty.Create(propertyName: "Uri",
returnType: typeof(string),
declaringType: typeof(CustomPDFWebView),
defaultValue: default(string));
public string Uri
{
get { return (string)GetValue(UriProperty); }
set { SetValue(UriProperty, value); }
}
}
}
Custom renderer:
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using BizzTimeTest.Droid;
using BizzTimeTest.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(CustomPDFWebView), typeof(CustomWebViewRenderer))]
namespace BizzTimeTest.Droid
{
[Obsolete]
public class CustomWebViewRenderer : WebViewRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
var customWebView = Element as CustomPDFWebView;
Control.Settings.AllowUniversalAccessFromFileURLs = true;
Control.LoadUrl(string.Format("file:///android_asset/pdfjs/web/viewer.html?file={0}", string.Format("file:///android_asset/Content/{0}", "test_pdf_file.pdf")));
}
}
}
}
xaml
<local:CustomPDFWebView x:Name="custom_pdf_viewer" IsVisible="false"
Uri="test_pdf_file.pdf" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" />
I have a UserHandler Singleton Class and I declared a variable like this
class UserHandler
{
...
public DatePickerDialog dialog = null;
...
}
Then in my MainActivity.cs file
using Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Support.Design.Widget;
using Android.Support.V7.App;
using Android.Text;
using Android.Views;
using Android.Widget;
using Java.Interop;
using Java.Lang;
using System;
using System.Collections.Generic;
using System.Globalization;
using AlertDialog = Android.Support.V7.App.AlertDialog;
using Exception = System.Exception;
class MainActivity
{
private readonly UserHandler U_Handler = UserHandler.GetInstance;
...
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.activity_main);
...
U_Handler.dialog = new DatePickerDialog(this);
...
}
When I run it on my device (Oppo, Android 8.1.0), it works normally but when I tried it on other device (Samsung, Android 6.0.1), it crashes and upon debugging, it shows this
**Java.Lang.NoSuchMethodError:** 'no non-static method "Landroid/app/DatePickerDialog;.<init>(Landroid/content/Context;)V"'
How to solve this?
Should I use 3rd party Libraries?
Because the constructor DatePickerDialog(Context context) was added in API level 24,when you run it in Samsung, Android 6.0.1,it will throw the Java.Lang.NoSuchMethodError exception.
You can make a judgment call and use the old API when the SDK version is less than 24, and use the new API when it is greater than 24.
The api you could look at DatePickerDialog
How to implement a VideoView into my Xamarin.Forms shared code class?
What I tried:
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using XamNative.ViewModels;
using XamNative.Droid;
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class VideoPage : ContentPage
{
public VideoPage ()
{
InitializeComponent ();
#if __ANDROID__
var linearLayout = new LinearLayout(Forms.Context);
linearLayout.LayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FillParent, LinearLayout.LayoutParams.WrapContent);
var _videoView = new VideoView(linearLayout.Context) { };
_videoView.SetMinimumHeight(300);
_videoView.SetMinimumWidth(300);
linearLayout.AddView(_videoView);
//MediaRecorder Code...
#endif
}
I think it has something to the with the VideoPage class inheriting from ContentPage, which is not the right inheritance.
The error is logged as "Application lost the surface".
I can implement a TextView this way, but not a VideoView
I would suggest using a Third Party Nuget as all the code is done for you.
You can either use:
Rox.Xamarin.Video Player: https://www.nuget.org/packages/Rox.Xamarin.Video/
Which is free.
Or a paid for component:
Octane.VideoPlayer: https://components.xamarin.com/view/video-player
I created a WCF service in Visual Studio 2012 that I intend to consume in Xamarin and have it save user registration information to a table in SQL server. The service works fine when debugging in Visual Studio, the data entries actually save to my table in SQL. I want to consume the service in Xamarin and here is my code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using ItusService;
using Android.App;
using Android.Locations;
using Android.OS;
using Android.Util;
using Android.Widget;
//some code here...
public static readonly EndpointAddress EndPoint = new EndpointAddress("http://192.168.1.155:12100/Service1.svc");
private Service1Client service;
protected override void OnCreate (Bundle bundle)
{
//some code here...
InitializeService1Client();
}
private void InitializeService1Client()
{
BasicHttpBinding binding = new BasicHttpBinding ();
service = new Service1Client(binding, EndPoint);
}
async void AddressButton_OnClick(object sender, EventArgs eventArgs)
{
//some code here...
UserLocation useraddress = new UserLocation ();
useraddress.ClientID = _client.Text = "ddsdfs";
useraddress.FullName = _name.Text = "dsffdf";
useraddress.LocationCoordinates = _locationText.Text;
useraddress.LocationAddress = _addressText.Text;
useraddress.DistressTime = _time.Text = "djdsk";
string result = service.ToString ();
_resultTxt.Text = result;
}
I don't know if there is something I am missing out because nothing is being saved to my SQL table from my Android device. I debug using both an emulator and my device, nothing has been saved using both. I have opened the port for listening, I have created a reference file using silverlight slsvc tool according to the Xamarin Walkthrough http://developer.xamarin.com/guides/cross-platform/application_fundamentals/web_services/walkthrough_working_with_WCF/ I have tried everything I possibly can. Please help.
The general pattern for calling a WCF method is something like this (this is general WCF and really has nothing to do with Xamarin or Android)
// create the client and bind it
client = new ServiceClient(binding, endpoint);
// specify the callback
client.GetLocationCompleted += OnGetLocationCompleted;
// make the request to your method, passing any required parameters
client.GetLocationAsync(useraddress);
because the WCF call is async, you need to provide a callback method (the naming of the EventArgs class will depend on how your service is defined)
public void OnGetLocationCompleted(object sender, GetLocationCompletedEventArgs args) {
// if something bad happend, args.Error will contain an exception
// otherwise args.Result will contain any return value from you method
}
I'm very new to MVVMCross & Xamarin, so it's very possible I'm missing something simple, but I have an Mvx.MvxGridView layout bound to a simple list of objects.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Mvx.MvxGridView
android:numColumns="5"
android:verticalSpacing="15dp"
android:horizontalSpacing="15dp"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
local:MvxBind="ItemsSource Bikes"
local:MvxItemTemplate="#layout/bikeassignmentview_bikeelement" />
</LinearLayout>
The view is pretty simple:
namespace Keiser.MPM.Screen.Droid.Views
{
using Android.App;
[Activity(Theme = "#style/Theme.FullScreen")]
public class BikeAssignmentView : BaseView
{
protected override void OnCreate(Android.OS.Bundle bundle)
{
base.OnCreate(bundle);
this.SetContentView(Resource.Layout.BikeAssignmentView_Page);
}
}
}
Same with the view model:
namespace Keiser.MPM.Screen.Core.ViewModels
{
using System.Collections.Generic;
using System.Windows.Input;
using Cirrious.CrossCore;
using Cirrious.MvvmCross.ViewModels;
using Keiser.MPM.Screen.Core.Models.Bikes;
public class BikeAssignmentViewModel : BaseViewModel
{
private IBikeManagerService _bikeManagerService;
private List<Bike> _bikes;
public List<Bike> Bikes { get { return _bikes; } }
public BikeAssignmentViewModel(IBikeManagerService bikeManagerService)
{
_bikeManagerService = bikeManagerService;
_bikes = _bikeManagerService.Bikes;
}
}
}
The service where the Bikes list is actually originating is nested all the way down in a service class:
namespace Keiser.MPM.Screen.Core.Models.Bikes
{
using System;
using System.Linq;
using System.Threading;
using System.Collections.Generic;
using Cirrious.CrossCore;
using Cirrious.CrossCore.Core;
using Cirrious.MvvmCross.ViewModels;
using Cirrious.MvvmCross.Plugins.Messenger;
using Core.Models.Settings;
public class BikeManagerService : MvxNotifyPropertyChanged, IBikeManagerService
{
public object BikesLocker = new object();
private List<Bike> _bikes = new List<Bike>();
public List<Bike> Bikes
{
get { return _bikes; }
set { _bikes = value; RaisePropertyChanged(() => Bikes); }
}
// --- Other boring code...
}
}
Here's the issue. The grid view won't populate dynamically at all if the list is empty when the view is loaded. If I enter the page with the list populated, it will load correctly, and the grids will be added for new objects added to the list, but it will not remove disposed grids from the list until I click on the screen a bit. The objects continue to update correctly until the object is disposed. Then the fields of the object stop working, but they don't disappear. Also, if the list ever goes back to empty, the view won't ever update again.
Am I missing something? Should I be invalidating the view or something? Any help or resources would be greatly appreciated!
[======================= Solution =======================]
The final solution was to convert the list to an observable collection:
Interface:
namespace Keiser.MPM.Screen.Core.Models.Helpers
{
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
public interface IObservableCollection<T>
: IList<T>
, INotifyPropertyChanged
, INotifyCollectionChanged
{
}
}
Class:
namespace Keiser.MPM.Screen.Core.Models.Helpers
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
public class SimpleObservableCollection<T>
: ObservableCollection<T>
, IObservableCollection<T>
{
public SimpleObservableCollection(List<T> source) : base(source) { }
protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
base.OnCollectionChanged(e);
}
}
}
All changes made to the Collection had to be done on the main UI thread, which began to degrade performance (I'm guessing from the continual context switching?). I ended up scrapping the Observable list and implementing an IEnumerable class which fires a message on changes and subscribing to the message in the view:
namespace Keiser.MPM.Screen.Droid.Views
{
using Android.App;
using Android.Widget;
using Cirrious.MvvmCross.Plugins.Messenger;
[Activity(Theme = "#style/Theme.FullScreen")]
public class BikeAssignmentView : BaseView
{
protected MvxSubscriptionToken _BikeListToken;
protected override void OnCreate(Android.OS.Bundle bundle)
{
base.OnCreate(bundle);
this.SetContentView(Resource.Layout.BikeAssignmentView_Page);
var gridView = FindViewById<GridView>(Resource.Id.gridview);
_BikeListToken = Cirrious.CrossCore.Mvx.Resolve<IMvxMessenger>().SubscribeOnMainThread<Core.Models.Bikes.BikesChangedMessage>(message =>
{
((BaseAdapter)gridView.Adapter).NotifyDataSetChanged();
});
}
}
}
Normal Mvvm and Data-Binding works using INotifyPropertyChanged
This means that when your Grid in the UI binds its ItemsSource to Bikes on the BikeAssignmentViewModel then it hooks into the PropertyChanged event on BikeAssignmentViewModel
Since you are firing RaisePropertyChanged from your Service and not from your ViewModel then the Grid never sees this change notification.
To work around this:
you could find a way to raise the RaisePropertyChange call from the ViewModel rather than the Service
you could find a way to bind the Grid to the Service rather as well as to the ViewModel (e.g. bind ItemsSource Service.Books)
If you're new to Data-Binding then it may also be worth reading up more about Data-Binding and for lists also learning about ObservableCollection and INotifyCollectionChanged