我的应用程序发送和接收 TCP 字符串。这些字符串之一是根据该字符串使对象可见。我当前的代码给出System.NullReferenceException has been thrown Object reference not set to an instance of an object.
我找不到正确的访问方法,我猜想 RunOnUI 似乎没有访问此权限。
我当前的代码:
听众课程:(完整课程的片段,如果需要,我可以发布更多内容)。
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);
}
}
以及 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.
您必须在构造函数中将 Context 传递给您的类
所以你可以向你的类添加一个构造函数,例如:
MainActivity mContext;
public YourClass(MainActivity context) {
this.mContext = context;
}
然后从你的类中调用该方法,如下所示:
mContext.RunOnUiThread(() =>
{
//This is where the received data is passed
mContext.SortData(content);
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)