简体   繁体   中英

Accessing UI thread in Xamarin Android

My application sends and receives TCP strings. One of those strings is to make an object visible depending on the string. My current code gives System.NullReferenceException has been thrown Object reference not set to an instance of an object.

I can't find the right method to access, I guess as RunOnUI doesn't seem to access this right.

My current code:

Listener class: (Snippet of the full class, I can post more if needed).

public void ReadCallback(IAsyncResult ar)
{
    MainActivity ma = new MainActivity();
    String content = string.Empty;

    StateObject so = (StateObject)ar.AsyncState;
    Socket handle = so.workSocket;

    int bytesRead = handle.EndReceive(ar);

    if (bytesRead > 0)
    {
        so.sb.Append(System.Text.Encoding.ASCII.GetString(so.buffer, 0, bytesRead));
        content = so.sb.ToString();
    }
    if (content.IndexOf("0") > -1)
    {
        ma.RunOnUiThread(() =>
        {
            //This is where the received data is passed
            ma.SortData(content);
        });
        Send(handle, content);
    }
    else
    {
        handle.BeginReceive(so.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), so);
    }
}

And the code for SortData:

public void SortData(string data)
{
    if(data == "0")
    {
        txtmsg.Visibility = ViewStates.Invisible;        
    }
} //This is the only code that's called, the txtmsg.Visibility part is the error producer once called. 

You have to pass the Context to your class in a constructor

so you would add a constructor to your class like :

MainActivity mContext;

public YourClass(MainActivity context) {
       this.mContext = context;
}

and then call the method from your class like :

mContext.RunOnUiThread(() =>
     {
       //This is where the received data is passed
       mContext.SortData(content);
     });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM