-2
public boolean editXML(String newCar) {
    try {
        String myXMLfile = "res\\values\\cars.xml";

        DocumentBuilderFactory docFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(myXMLfile);

        Node string_array = doc.getElementsByTagName("string-array")
                .item(0);

        Element item = doc.createElement("item");
        item.setTextContent(newCar);
        string_array.appendChild(item);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(myXMLfile));
        transformer.transform(source, result);
        return true;
    } catch (Exception e) {
        return false;
    }
}

If I run a normal JAVA project, the function above works fine, but, if I run it in an android project it return false. Where is the problem? How to preview the e.printstacktrace in an android project so I can see what the exception says?

Student22b
  • 79
  • 3
  • 13

2 Answers2

2

First problem:

} catch (Exception e) {
    return false;
}

This silences any Exception the code is throwing and doesn't help you diagnose the problem. At least print the exception stacktrace to log, e.g.

} catch (Exception e) {
    android.util.Log.e("tag", "", e);
    return false;
}

Second problem:

String myXMLfile = "res\\values\\cars.xml";

Android resources are compiled to binary form in the build process. They are not available to your app this way. To read XML from resources, see e.g. Android : Reading XML from local resource (for testing).

Third problem: Who knows, fix the previous ones first.

Community
  • 1
  • 1
laalto
  • 150,114
  • 66
  • 286
  • 303
0

The stack trace can be viewed in the LogCat window. If it is not showing, in Eclipse, you have to go to Window > Show View > Other, then you should find Logcat under the Android section. For Android Studio, this question has pictures that could be better than any explanation :)

Hard to say where your parsing problem lies without the error trace ... To show the stack trace in the Logcat, add e.printStackTrace(); to your catch block.

Community
  • 1
  • 1
2Dee
  • 8,609
  • 7
  • 42
  • 53