Monotouch - EASession output stream gives null error

Looking for some help over here.

When i run this code (below), it crashes when i process it for the second time. it crashes with an object reference not set.. on the session.outputstream

var session= new EASession(accessory, "net.gebe"); 

session.OutputStream.Open();

the second time session.outputstream is null. Even when disposing session.

Richard

   public void PrintIt()
    {
     var _accessoryList = EAAccessoryManager.SharedAccessoryManager.ConnectedAccessories;

     accessory = null;

     foreach(var obj in _accessoryList)
     {
      if(obj.ProtocolStrings.Contains("net.gebe"))
      {
       accessory = obj;
       //break;
      }             
     }

     if(accessory == null)
     {          
      //tmg.InfoAlert ("No Printer");
      return;
     }


     var session= new EASession(accessory, "net.gebe"); 

     session.OutputStream.Open();

     string str2 = "HELLO THERE PRINTER 1 2 3 4 5";

     byte[] printdata2;

     ASCIIEncoding   encoding2 = new ASCIIEncoding();

     printdata2 = encoding2.GetBytes(str2); 

     uint nlen2 = Convert.ToUInt32 (str2.Length+1);

     session.OutputStream.Write(printdata2,nlen2 ); 

     session.OutputStream.Close ();

     session.Dispose ();
    }

Upvotes: 1

Views: 1020

Answers (2)

danmiser
danmiser

Reputation: 1083

I got mine working now. What I did:

  • Save the session as a variable in the class
  • Only create the session if session is null
  • You may not want to call session.OutputStream.Close() after every print. At least it's something to keep in mind while debugging for your situation.

This will allow for multiple print jobs on the same page without blowing up. session.OutputStream was not null in this case.

I also found that the ViewDidLoad/Unload events weren't great for detecting when the device becomes available/unavailable via the EAAccessoryDidConnectNotification and EAAccessory DidDisconnectNotification observers. Instead I used ViewDidAppear/ViewDidDisappear. In those methods, I tear down the session, and when I come back in to print a new job, the session gets created and OutputStream is assigned.

Lastly, I wasn't getting events fired for my device via session.OutputStream.OnEvent. Not sure if it's my device, a MonoTouch bug, or just a generic bug of mine yet.

UPDATE: Check out this nicely wrapped implementation of AccessoryAdapter

Upvotes: 1

Rolf Bjarne Kvinge
Rolf Bjarne Kvinge

Reputation: 19335

You need to list the external accessories you're going to use in your Info.plist.

There is some documentation on this on apple's site: http://developer.apple.com/library/ios/#featuredarticles/ExternalAccessoryPT/Introduction/Introduction.html#//apple_ref/doc/uid/TP40009502

Here is a screenshot of how to set this value in Info.plist: http://screencast.com/t/AYmOWjf8wkL

(This is from here: https://bugzilla.xamarin.com/show_bug.cgi?id=1635#c1)

Upvotes: 0

Related Questions