应用程序应解析XML并输出到和ListView,但它似乎无法正常工作
我的代码
public class MainActivity extends AppCompatActivity {
ListView spiska;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spiska = (ListView) findViewById(R.id.spiska);
try {
MainActivity obj = new MainActivity ();
String[] arra = obj.run ("http://feeds.reuters.com/reuters/sportsNews?format=xml");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, arra);
spiska.setAdapter(adapter);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public String[] run (String url) throws Exception
{
String[] forlist = new String[100];
try {
DocumentBuilderFactory f =
DocumentBuilderFactory.newInstance();
DocumentBuilder b = f.newDocumentBuilder();
Document doc = b.parse(url);
// loop through each item
NodeList items = doc.getElementsByTagName("item");
for (int i = 0; i < items.getLength(); i++) {
Node n = items.item(i);
if (n.getNodeType() != Node.ELEMENT_NODE)
continue;
Element e = (Element) n;
// get the "title elem" in this item (only one)
NodeList titleList =
e.getElementsByTagName("title");
Element titleElem = (Element) titleList.item(0);
// get the "text node" in the title (only one)
Node titleNode = titleElem.getChildNodes().item(0);
forlist[i] = titleNode.getNodeValue();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return forlist;
}
}
android studio outputs
处理:com.example.javarulit,PID:15400 java.lang.NullPointerException:尝试调用虚方法&#39; java.lang.String java.lang.Object.toString()&#39;在空对象引用上
此代码适用于java
public class Main {
public static void main(String[] args) {
System.out.println("Hell o world");
try
{
Main obj = new Main ();
obj.run ("http://feeds.reuters.com/reuters/sportsNews?format=xml");
}
catch (Exception e)
{
e.printStackTrace ();
}
}
public void run (String url) throws Exception
{
String[] forlist = new String[100];
try
{
DocumentBuilderFactory f =
DocumentBuilderFactory.newInstance();
DocumentBuilder b = f.newDocumentBuilder();
Document doc = b.parse(url);
doc.getDocumentElement().normalize();
System.out.println ("Root element: " +
doc.getDocumentElement().getNodeName());
// loop through each item
NodeList items = doc.getElementsByTagName("item");
for (int i = 0; i < items.getLength(); i++)
{
Node n = items.item(i);
if (n.getNodeType() != Node.ELEMENT_NODE)
continue;
Element e = (Element) n;
// get the "title elem" in this item (only one)
NodeList titleList =
e.getElementsByTagName("title");
Element titleElem = (Element) titleList.item(0);
// get the "text node" in the title (only one)
Node titleNode = titleElem.getChildNodes().item(0);
forlist[i] = "\"" + titleNode.getNodeValue().toString() + "\"";
}
System.out.println(Arrays.toString(forlist));
}
catch (Exception e)
{
e.printStackTrace();
}
}
}