我正在使用 sax xmlparser,但无法通过 toast 打印结果。我得到一个空指针异常。我找到了一个使用 textview 数组的示例,但我想使用 toast。来自 android people 的原始代码工作正常,但如果我在自己的项目中应用相同的代码,它每次都会失败。
主.java >
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.Toast;
public class Main extends Activity {
String strGK = null;
String strHWW = null;
String strHak5 = null;
CheckBox GK;
CheckBox HWW;
CheckBox Hak5;
SitesList sitesList = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void getUrl(View v) {
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL("http://websitethatcontains/feed");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Parsing Exception = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getName().size(); i++) { /** <- the prob. seems to be here */
Toast.makeText(getApplicationContext(), sitesList.getName().get(i), Toast.LENGTH_LONG).show();
}
}
}