0

我正在尝试从 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 文件我尝试了不同的方法但不起作用。谢谢 ...

我现在发现我必须在 while 循环中编写两行代码

    eventType = xpp.next();


    eventType = xpp.getEventType();

现在它工作正常!感谢帮助....

4

2 回答 2

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) {

            }
于 2013-03-01T07:56:08.443 回答
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();
    }
于 2013-03-01T07:58:17.077 回答