我认为我遇到了类似的问题:Return ArrayList and use it in another method problm。
在几个类中,ArrayList< ...>将使用“新”创建。在此List中,我存储了几个DataContainer(由另一个类定义)。
现在,如果我保存了所有数据类,我会通过“OnMessageReceived”将此List返回给我的Activity。
奇怪的是,有时它可以工作,但大多数情况下我得到一个空列表。
我压缩代码以获得更好的视图。如果我调试我可以看到数据是可访问的,直到它跳转到方法“public void messageReceived(final ArrayList _Container){...}”
这种回归是不可能的?
一些代码:
(1级)获取数据的方法:
public boolean run() {
try {
...
try {
....
while (mRun) {
if(in.ready()) {
...
...
mMessageListener.messageReceived(_ConvertData.GetMessage(new String(Puffer).substring(0,length)));
}
}
}
}
}
(第2类)
public ArrayList<DatenContainer> GetMessage(String message) {
Sensoren SensorName = Sensoren.NONE;
int _Length = 0;
int _ID = 0;
double _TimeStamp = 0;
int _NumberOfPackage = 0;
String _msg = "";
while (!message.isEmpty()) {
...
...
Container.add(new DatenContainer(_Length, _ID, _TimeStamp, _NumberOfPackage, _msg, SensorName));
}
catch (Exception e) {}
}
return Container;
}
(活动)
TCP_Client_Thread = new Thread() {
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
try {
// create a TCPClient object and
mTcpClient = new TCP_Client(new TCP_Client.OnMessageReceived() {
@Override
//here the messageReceived method is implemented
public void messageReceived(final ArrayList<DatenContainer> _Container) {
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
for (DatenContainer datenContainer : _Container) {
...
...
}
} catch (Exception e) {
Show_Toast(e.toString());
}
}
});
}
},Infos.getSERVERIP(),Infos.getSERVERPORT());
}
catch (Exception e) {}
}
答案 0 :(得分:0)
现在它有效。我忘记了同步方法。帮助我的人:)
@Override
//here the messageReceived method is implemented
public void messageReceived(final ArrayList<DatenContainer> _Container) {
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayList<DatenContainer> Container;
synchronized (_Container) {
Container = _Container;
}
try {
if (Container != null && !Container.isEmpty()) {
for(int i = 0; i < Container.size(); i++) {
DatenContainer datenContainer = (DatenContainer)Container.get(i);
switch (datenContainer.get_ActSensor()) {
case SPEED:
edt_3.setText(datenContainer.get_Data());
break;
case COG:
edt_4.setText(datenContainer.get_Data());
break;
default:
break;
}
}
}
}
catch (Exception e) {
Show_Toast(e.toString());
}
Container.clear();
}
});
}