0

I am using the following code to read an XML file named ContactFile that I saved in ResourceFile in C: directory

public class MainActivity extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        extract(null);
    }

    public static void extract(String argv[])
    {     
        try
        {
            File XmlFile = new File("C:\\ResourceFile\\ContactFile.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(XmlFile);
            doc.getDocumentElement().normalize();     
            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
            NodeList nList = doc.getElementsByTagName("ExtractContact");
            System.out.println("----------------------------");  

            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);
                System.out.println("\nCurrent Element :" + nNode.getNodeName());     
                if (nNode.getNodeType() == Node.ELEMENT_NODE)
                {
                    Element eElement = (Element) nNode;
                    System.out.println("id : " + eElement.getAttribute("id"));
                    System.out.println("Name : " + eElement.getElementsByTagName("name").item(0).getTextContent());
                    System.out.println("Phone Number : " + eElement.getElementsByTagName("phoneNumber").item(0).getTextContent());
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}   

The XML file has that form:

 <Document>
    <ExtractContact>
        <id></id>
        <name></name>
        <phoneNumber />
    </ExtractContact>
</Document>

I am getting this error:

E/Trace(1596): error opening trace file: No such file or directory (2)

Marya
  • 332
  • 2
  • 16
  • you can't access the file on the PC from the Android in such a way – nikis Mar 24 '14 at 11:51
  • you need to push the xml file using DDMS and better use android provided [XmlPullParser](http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html) – riteshtch Mar 24 '14 at 11:53
  • do you know about the json –  Mar 24 '14 at 11:58
  • my suggestion is better you convert the xml file to json –  Mar 24 '14 at 12:00
  • I am not supposed to use jsom in mu app !! @nikis and if the xml file is saved in the sdcard of my android device .How can I access to it – Marya Mar 24 '14 at 12:08

3 Answers3

0

I am not sure what you are doing with the line in android

File XmlFile = new File("C:\\ResourceFile\\ContactFile.xml");

Please have yours file at asset folder and than fetch from there!

do it as follows

InputStream is = getResources().getAssets().open("ContactFile.xml");
String result= convertStreamToString(is);

to fetch the file as string we can write convertStreamToString method as follows

public static String convertStreamToString(InputStream is)
            throws IOException {
            Writer writer = new StringWriter();
        char[] buffer = new char[2048];
        try {
            Reader reader = new BufferedReader(new InputStreamReader(is,
                    "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        String text = writer.toString();
        return text;
}

in case if the file is in sd card than read it as follows

File sdcard = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(sdcard,"file.txt");

//Read text from file
StringBuilder text = new StringBuilder();

try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;

    while ((line = br.readLine()) != null) {
        text.append(line);
        text.append('\n');
    }
}
catch (IOException e) {
    //You'll need to add proper error handling here
}
Jitesh Upadhyay
  • 5,244
  • 2
  • 25
  • 43
  • Which path do I have to put if the xml file is saved in the sdcard of the phone or the root directory ?? – Marya Mar 24 '14 at 12:12
  • just put ContactFile.xml in asset folder in yours android project and use the code what i have given to you!! – Jitesh Upadhyay Mar 25 '14 at 02:29
  • In fact ContactFile.xml is created in the sdcard of the phone so I can't put it some where else like you said ( asset folder for exemple ) .I need to read it from the sdcard – Marya Mar 25 '14 at 07:53
  • 1
    Than please do as follows File dir = Environment.getExternalStorageDirectory(); File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext"); – Jitesh Upadhyay Mar 25 '14 at 08:20
0

Here you can find how to read files from assets.

and here how to read from raw

Community
  • 1
  • 1
Guillermo Merino
  • 3,197
  • 2
  • 17
  • 34
0

I just changed the path of my file into "Environment.getExternalStorageDirectory(),ContactFile.xml" .

So it's now : File XmlFile = new File( Environment.getExternalStorageDirectory(),"newfile/contactFile/ContactFile.xml");

Now it works.

Marya
  • 332
  • 2
  • 16