Search code examples
androidformsxamarinusbodt

Usb List Devices in Xamarin.Forms


I try to do list of usb devices, connected by serial odt with smartphone, within xamarin.forms. To do that I use this project https://github.com/anotherlab/UsbSerialForAndroid

How to do listview in shared project with devices from Project.Droid.MainActivity? I tried to do that with dependency service:

This is my Page1(where I want to have listview):

 public partial class Page1 : ContentPage {


    public Page1()
    {
        InitializeComponent();
        DependencyService.Get<Interface1>().moj();
       
    }

}

My interface:

    namespace SensDxMobileApp.Views.MainWindow {
   public interface Interface1 {
        void moj();
    }
}

And MyActivity(Droid project):

    [assembly: Xamarin.Forms.Dependency(typeofProject.Droid.MainActivity))]
    namespace Project.Droid {
    public class MainActivity: Interface
{
       protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            listView = new Android.Widget.ListView;
        }

      public async void moj()
            {
    
                adapter = new UsbSerialPortAdapter(this);
                
                listview.Adapter = adapter;
                listView.ItemClick += async (sender, e) =>
                {
                    await OnItemClick(sender, e);
                };
    
                 await PopulateListAsync();
    
                
                detachedReceiver = new UsbDeviceDetachedReceiver(this);
                RegisterReceiver(detachedReceiver, new IntentFilter(UsbManager.ActionUsbDeviceDetached));
                
            }
    }

But I have an error "Object reference not set to an instance of an object.", on " DependencyService.Get().moj()" in Page1();

Did someone do something similar? Thanks


Solution

  • If you going the DependencyService route, then you'll want to create a separate class that implements Interface1 and registering that as a dependency service. I don't think you can register the MainActivity as a DependencyService implementation.

    One problem that you are going to hit this is mostly async code and callbacks.

    You also shouldn't be newing up an Android ListView as a DependencyService call. That would be better suited as a custom renderer. As a DependencyService implementation, you would want the moj() method to return data that can be consumed by the Xamarin.Forms code. You would need more than just that method. You would need code to initialize the UsbSerialPort class, code to query the list of devices, and then invoke a callback that sends back that list, In theory anyway. I never tested that library with Forms.