我正在尝试从 Web 获取 XML 数据并将这些数据显示到 ListView 中。但是当我运行项目时出现了问题。你能帮我解决这个问题吗?谢谢你。
XMLParser.java
public class XMLParser extends Activity {
public String getXmlFromUrl(String url) {
String xml = null;
try {
new Thread(new Runnable() {
public void run() {
try {
URL uri=new URL("http://api.androidhive.info/pizza/?format=xml");
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
System.out.println("done");
}
catch(Exception e) {
e.printStackTrace();
}
}
}).start();
//readfilethread.start();
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
System.out.println("here");
// HttpResponse httpResponse = httpClient.execute(httpPost);
//HttpEntity httpEntity = httpResponse.getEntity();
//xml = EntityUtils.toString(httpEntity);
} catch (Exception e) {
e.printStackTrace();
}
// return XML
return xml;
}
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
// return DOM
return doc;
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
AndroidXMLParsingActivity.java
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables..
static final String URL = "http://api.androidhive.info/pizza/?format=xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// -> menuItems
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// 2. Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
R.id.name, R.id.description, R.id.cost });
setListAdapter(adapter);
// selecting single ListView item
android.widget.ListView lv = getListView();
// listening to single list item click
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String description = ((TextView) view.findViewById(R.id.description)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleListItem.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_COST, cost);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
'
LOGCAT部分
08-25 08:34:10.211: E/AndroidRuntime(1700): FATAL EXCEPTION: main
08-25 08:34:10.211: E/AndroidRuntime(1700): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.uygulama/com.example.uygulama.AndroidXMLParsingActivity}: java.lang.NullPointerException
08-25 08:34:10.211: E/AndroidRuntime(1700): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.uygulama/com.example.uygulama.AndroidXMLParsingActivity}: java.lang.NullPointerException
08-25 08:34:10.211: E/AndroidRuntime(1700): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.uygulama/com.example.uygulama.AndroidXMLParsingActivity}: java.lang.NullPointerException
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.os.Handler.dispatchMessage(Handler.java:99)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.os.Looper.loop(Looper.java:137)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread.main(ActivityThread.java:5039)
....
08-25 08:34:10.341: I/System.out(1700): done