我正在尝试从sdcard读取xml文件,但它不起作用。加载了空白活动并且TextView为空。如果我删除代码来读取xml并只将文本设置为t.setText(“hello”);它工作正常
代码在这里。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sdcard1);
TextView t;
t=(TextView) findViewById(R.id.T1);
try{
File f = new File(Environment.getExternalStorageDirectory()+"/page1.xml");
InputStream fileIS = new FileInputStream(f);
// InputStreamReader input= new InputStreamReader(fileIS);
xpp.setInput(fileIS,"UTF-8");
eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT){
if(eventType == XmlPullParser.TEXT) {
t.setText(t.getText()+xpp.getText());
}
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
<?xml version="1.0" encoding="UTF-8"?>
<page1>
<Text1>Hello.</Text1>
<Text2>World!</Text2>
</page1>
和sdcard / page1.xml中的xml文件 我试过不同的方式,但没有工作。 谢谢...
我发现现在我必须在循环
内写两行代码 eventType = xpp.next();
eventType = xpp.getEventType();
现在它工作正常!谢谢你的帮助....
答案 0 :(得分:0)
Try below code -
File rootDir = null;
rootDir = Environment.getExternalStorageDirectory();
try {
File myFile = new File(rootDir.getAbsolutePath(), "Your file Name");
FileInputStream fIn = new FileInputStream(myFile);
} catch (Exception e) {
}
答案 1 :(得分:0)
尝试使用以下代码阅读文件:
File myFile = new File("/sdcard/page1.xml"); FileInputStream fIn = new FileInputStream(myFile); BufferedReader myReader = new BufferedReader( new InputStreamReader(fIn)); String aDataRow = ""; String aBuffer = ""; while ((aDataRow = myReader.readLine()) != null) { aBuffer += aDataRow + "\n"; Log.d("File Is DATA:===>",aBuffer.toString()); } myReader.close(); Toast.makeText(getBaseContext(), "Done reading SD 'page1.xml'", Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); }