我有这个 .xml 文件,其中包含国家及其国家代码。这是它的样子:
<?xml version="1.0" encoding="UTF-8"?>
<landen>
<land>
<naam>Afghanistan</naam>
<code>AF</code>
</land>
<land>
<naam>Albani�</naam>
<code>AL</code>
</land>
<land>
<naam>Algerije</naam>
<code>DZ</code>
</land>
<land>
</landen>
现在我希望人们从列表中选择一个国家。我虽然 AlertDialog 会很好地显示所有内容。
我从 xml 文件中获取值的方式是这样的:
protected ArrayList<Land> getLanden() {
ArrayList<Land> lijst = new ArrayList<Land>();
try {
DocumentBuilder builder =DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(getAssets().open("landenlijst.xml"));
NodeList nl = doc.getElementsByTagName("land");
for (int i=0;i<nl.getLength();i++) {
Node node = nl.item(i);
Land land = new Land();
land.land = Xml.innerHtml(Xml.getChildByTagName(node, "naam"));
land.landcode = Xml.innerHtml(Xml.getChildByTagName(node, "code"));
lijst.add(land);
}
Log.d("Gabug","Klaar met parsen");
Log.d("Gabug","Landen: " + lijst);
} catch (Exception e) {
e.printStackTrace();
}
return lijst;
}
我用它来制作我的 AlertDialog:
public void KiesLandMenu(){
ArrayList<Land> alleLanden = getLanden();
final CharSequence[] items = alleLanden.toArray(new CharSequence[alleLanden.size()]);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Kies land");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item){
case 0:
break;
case 1:
break;
case 2:
break;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
我不知道这是否有效,因为 DDMS 在我记录它时会返回一些字节码或其他东西。之后它因为 ArrayStoreException 而强制关闭。
现在我的问题是;这是最好的方法吗?如果是,我该如何修复 ArrayStoreException?如果不是,有什么更好的方法让我的用户选择一个国家(可能是一个全新的视图)?此外,我如何注册某人点击的国家/地区?
编辑:
我稍微更改了下面的示例代码,现在我得到一个 NullPointerException ..
public void KiesLandMenu(){
ArrayAdapter<Land> arrAdapter;
ArrayList<Land> alleLanden = getLanden();
arrAdapter = new ArrayAdapter<Land>(this, android.R.layout.simple_list_item_single_choice, alleLanden);
ListView list = (ListView)findViewById(R.layout.lijstview);
list.setAdapter(arrAdapter);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> list, View view, int position,
long id) {
Log.e("item clicked", String.valueOf(position));
}
});
}
NullPointerException 位于list.setAdapter(arrAdapter);