我正在尝试学习在Java中使用xml(Android平台,使用Eclipse和simple-xml-2.5.2)。 我一直在“Training.java”的“serial.read”行中得到一个奇怪的java.lang.StackOverflowError。 你能帮忙解决问题吗?它是一个xml定义错误吗?
我包含以下来源:
文件beacons.java:
package com.marcos.training;
import java.util.List;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
@Element
public class Beacons {
@ElementList(inline=true)
private List<Beacon> list;
@Element
private String id;
public String getId() {
return id;
}
public Integer getSize() {
return list.size();
}
public List<Beacon> getList() {
return list;
}
}
文件Beacon.java:
package com.marcos.training;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
@Root
public class Beacon {
@Attribute
protected String ssid;
@Element
protected String bssid;
public String getSsid() {
return ssid;
}
public String getBssid() {
return bssid;
}
}
File Training.java:
package com.marcos.training;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.content.res.Resources.NotFoundException;
public class Training extends Activity {
private final static String TAG = Training.class.getCanonicalName();
TextView textStatus;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textStatus = (TextView) findViewById(R.id.textStatus);
Serializer serial = new Persister();
try {
Beacons myBeacons;
try {
myBeacons = serial.read(Beacons.class, getResources().openRawResource(R.xml.beacons));
Log.i(TAG, "Number of Beacons: " + myBeacons.getSize());
} catch (NotFoundException e) {
Log.d(TAG, "Uncaught exception", e);
return;
} catch (Exception e) {
Log.d(TAG, "Uncaught exception", e);
return;
}
int len = myBeacons.getSize();
for (int i = 0; i < len; i++) {
Beacon b = myBeacons.getList().get(i);
textStatus.append("Beacon " + (i+1) + "\n");
textStatus.append(" SSID : " + b.getSsid() + "\n");
textStatus.append(" BSSID : " + b.getBssid() + "\n");
textStatus.append("\n");;
}
} catch (Exception e) {
Log.d(TAG, "Uncaught exception", e);
}
}
}
文件beacons.xml:
<?xml version="1.0" encoding="utf-8"?>
<beacons id="1">
<beacon ssid="north">
<bssid>01:02:03:04:05:06</bssid>
</beacon>
<beacon ssid="east">
<bssid>02:03:04:05:06:07</bssid>
</beacon>
<beacon ssid="south">
<bssid>03:04:05:06:07:08</bssid>
</beacon>
<beacon ssid="west">
<bssid>04:05:06:07:08:09</bssid>
</beacon>
</beacons>
答案 0 :(得分:2)
通过将您的XML文件放入资源的XML目录中,Android构建系统假设您希望将其编译成二进制格式并且它需要您。因此,当您访问该输入流,然后尝试将其视为文本XML表示时,它就不起作用。你有两个选择。
res\raw
目录。getResources().getXml(R.xml.beacons)
API并为您的特定XML创建拉解析器。有关详细信息,请参阅this link。