【发布时间】:2012-02-28 14:48:16
【问题描述】:
我正在编写 3 个类/活动,我希望(最终)能够使用股票 android 布局将解析的 XML 数据加载到 simpleListAdapter 中。
我的策略是 Activity A:启动 SAX 解析器,加载处理程序,从 Activity C 检索 ArrayList>,并将 ArrayList 加载到 simpleListAdapter。
Activity B 是处理程序(我知道它有效,因为我以前使用过它,没有问题)。
最后,Activity C 包含返回 Strings 的方法,这些方法由处理程序给定值,然后将这些字符串加载到一个 ArrayList> 中,然后通过 Intent 发送给 Activity A。
但出现的只是黑屏。
我正在使用的测试 XML 站点是 http://www.google.com/ig/api?weather=Boston+Massachusetts"
这是 Activity A + C 的代码(我知道处理程序有效)。
活动(A):
public class xmlparser extends ListActivity implements OnClickListener {
static final String XMLsite = "http://www.google.com/ig/api weather=Boston+Massachusetts";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@SuppressWarnings("unchecked")
@Override
try{
URL website = new URL(XMLsite);
//getting xmlreader to parse data
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
HandlingXMLStuff doingWork = new HandlingXMLStuff();
xr.setContentHandler(doingWork);
xr.parse(new InputSource(website.openStream()));
ArrayList<HashMap<String, String>> list =(ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("arraylist");
String[] from = { "name", "purpose" };
int[] to = { android.R.id.text1, android.R.id.text2 };
SimpleAdapter adapter = new SimpleAdapter(this, list,
android.R.layout.simple_list_item_2, from, to);
setListAdapter(adapter);
}catch(Exception e){
}
}
活动(C):
package com.school;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class XMLDataCollected extends Activity{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, xmlparser.class);
ArrayList<HashMap<String, String>> list = buildData();
intent.putExtra("arraylist", list);
startActivity(intent);
}
int temp = 0;
String city = null;
public void setCity(String c){
city = c;
}
public void setTemp(int t){
temp = t;
}
private ArrayList<HashMap<String, String>> buildData() {
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
list.add(putData(city, "temp"));
list.add(putData("city", "temp"));
list.add(putData("city", "temp"));
return list;
}
private HashMap<String, String> putData(String name, String purpose) {
HashMap<String, String> item = new HashMap<String, String>();
item.put("name", name);
item.put("purpose", purpose);
return item;
}
}
任何建议都会有所帮助。
附:我之前使用过这个 XML 过程将数据加载到 textview 中,所以我知道它至少能够解析 XML 标签并将它们设置在 Activity C 中的方法上,然后在 textview 中检索和设置字符串,但是我的最终目标是能够将信息加载到 simpleListAdapter 中。
谢谢
【问题讨论】:
-
你的代码一团糟。您不需要 3 个活动来解析站点中的 xml 并将其显示在
ListView中。 -
哇,非常感谢。
-
Here 是您遇到问题时需要遵循的方案。这不是一个 XML 解析演示,只是通过以下步骤屏幕。
标签: android xml-parsing saxparser listadapter