朋友們,我從SD卡上的xml文件中讀取信息時遇到了問題。代碼正在成功實施,但logcat上沒有顯示任何內容,也沒有異常彈出。請幫助我一樣。從SD卡上的XML文件讀取時發生的問題
public class History extends Activity
{
private ListView lstv;
static ArrayList<Records> arr;
@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
setContentView(R.layout.history);
try {
String path = Environment.getExternalStorageDirectory()+"/saved_images/history.xml";
File file = new File(path);
SAXParserFactory factory=SAXParserFactory.newInstance();
SAXParser parser=factory.newSAXParser();
XMLReader reader=parser.getXMLReader();
XMLHandler handler=new XMLHandler();
//parser.parse(stream,handler);
reader.parse(new InputSource(new InputStreamReader(new FileInputStream(file))));
arr=handler.getArray();
ArrayAdapter<Records> adpt=new ArrayAdapter<Records>(this, android.R.layout.simple_list_item_1,arr);
//lstv.setAdapter(adpt);
handler.startDocument();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
class XMLHandler extends DefaultHandler {
ArrayList<Records> array;
Records records ;
String strCurrentValue = null;
public ArrayList<Records> getArray() {
return array;
}
@Override
public void startDocument() throws SAXException {
super.startDocument();
array=new ArrayList<Records>();
}
@Override
public void startElement(String uri, String elementName, String qName,Attributes attributes) throws SAXException {
super.startElement(uri, elementName, qName, attributes);
if(elementName.equals("Record"))
{
records=new Records();
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
strCurrentValue=new String(ch, start, length);
}
@Override
public void endElement(String uri, String elementName, String qName)
throws SAXException {
super.endElement(uri, elementName, qName);
if(elementName.equals("date"))
{
records.date=strCurrentValue;
}else if(elementName.equals("cc"))
{
records.cc=strCurrentValue;
}
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
for(Records c:array)
{
Log.d("XmlHandler", c.toString());
}
}
}
}
我無法在日誌貓或屏幕上看到任何東西。請使用片段幫助我獲取相同的代碼。 謝謝
您應該避免從磁盤加載或/和在主線程上解析。如果您不想面對ANR,請嘗試使用AsyncTask。 – 2012-08-13 06:52:26