2013-06-01 2 views
0

XPath를 사용하여 XML 내용을 ListView에 표시하기위한 간단한 Android 앱을 작성하고 있습니다. 내 코드는 아래에 있습니다. null 예외를 잡는 중입니다. 주위에 도와주세요 :(나는 구글과 다른 튜토리얼을 시도했지만 그들 중 누구도 내 문제 :(XPath로 XML 구문 분석하기

public class MainActivity extends ListActivity { 

ArrayList<String> mPeople = new ArrayList<String>(); 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    try { 
     parseData(); 
    } catch(Exception ex) { 
     Toast.makeText(this, "Exception: " + ex.getMessage(), Toast.LENGTH_LONG).show(); 
     System.out.println(ex.getMessage() +"=============="); 

    } 

    // pass adapter w/ data queried through XPath to ListView 
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mPeople); 
    setListAdapter(adapter); 
} 

private void parseData() throws Exception {  
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
DocumentBuilder db = dbf.newDocumentBuilder(); 

Document doc = db.parse(new URL("http://www.w3schools.com/xpath/books.xml").openStream()); 
// query XPath instance, this is the parser 
XPath xpath = XPathFactory.newInstance().newXPath(); 
// specify the xpath expression 
// String expression = " /bookstore/book/title "; 

XPathExpression e = xpath.compile("/bookstore/book/title"); 

// list of nodes queried 
NodeList nodes = (NodeList)e.evaluate(doc, XPathConstants.NODESET); 

Toast.makeText(this, "count: " + String.valueOf(nodes.getLength()),Toast.LENGTH_SHORT).show(); 
// if node found 
if(nodes != null && nodes.getLength() > 0) { 
    mPeople.clear(); 
    int len = nodes.getLength(); 
    for(int i = 0; i < len; ++i) { 
     // query value 
     Node node = nodes.item(i); 
     mPeople.add(node.getTextContent()); 
    } 
} 
} 
} 

나는 토스트 containg 예외입니다 무엇을 얻을 출력을 해결하기 위해 보이지 않는다 :. 널 내가 db.parse()에서 openStream()이 생각 . null를 반환 사람이 해결책을 발견하면 알려 주시기 바랍니다, 그것은 매우 감사하겠습니다 감사합니다

편집 :.. 여기 년대 로그 캣

06-01 10:25:42.586: I/System.out(1401): null============== 
06-01 10:25:45.721: I/Choreographer(1401): Skipped 210 frames! The application may be doing too much work on its main thread. 
06-01 10:25:47.226: I/Choreographer(1401): Skipped 1768 frames! The application may be doing too much work on its main thread. 
06-01 10:25:47.467: D/gralloc_goldfish(1401): Emulator without GPU emulation detected. 

답변

0

시도해보십시오. asynctask을 사용하여 parseData() 기능을 수행하고 oncreate.it 활동에서 asynctask.execute를 호출하면 문제가 해결 될 수 있습니다. U가 this-을 얻었습니다. 응용 프로그램이 OS에서 "ANR"로 처리 할 수 ​​있으므로 6 초 이상 걸릴 수 있으므로 주 스레드에서 네트워크 호출을하기 때문에 응용 프로그램이 주 스레드에서 너무 많은 작업을 수행하고있을 수 있습니다.

+0

나는 그것을했다. 그러나 사용하지 마십시오. –

+0

실제로 null이 반환되는이 줄 '문서 doc = db.parse (새 URL ("http://www.w3schools.com/xpath/books.xml") .openStream()); ' –

+0

매니페스트에 인터넷 사용 권한이 추가 되었습니까? –

관련 문제