I'm new at Android and trying to get a local XML file and get data and display it .
Here's my code:
public String GetXmlData()
{
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try
{
builder = builderFactory.newDocumentBuilder();
InputStream is = getAssets().open("words.xml");
Document document = builder.parse(new FileInputStream("C:\\Users\\Ocean\\AndroidStudioProjects\\Deneme1Project\\Deneme1\\build\\res\\assets\\words.xml"));
Element rootElement = document.getDocumentElement();
NodeList nodes = rootElement.getChildNodes();
for(int i=0; i<nodes.getLength(); i++){
Node node = nodes.item(i);
if(node instanceof Element)
{
//a child element to process
Element child = (Element) node;
title = child.getAttribute("title");
String author= child.getAttribute("author");
String year= child.getAttribute("year");
}
}
return title;
}
catch (Exception e)
{
e.printStackTrace();
return e.toString();
}
}
My first question where should I put this XML file? Inside res I created folder and named it assets an put inside it I have rs and r folders :S File not found Exception (File is there :P)
You don't need to create a folder named assets in res folder because there is already an assets folder in default project. If you put the file in default assets folder, you can call by:
getAssets().open("words.xml");
if you want to use another custom folder:
getAssets().open("myfiles/words.xml");
You could place your XML file in any of the below mentioned locations:
1) sdcard , And to access it
File wordsXML = new File(Environment.getExternalStorageDirectory() + "/SomeFolderName/" + "words.xml");
FileInputStream fis = new FileInputStream(wordsXML);
Note: you could edit the xml file even after installing the application
2) res/raw folder
FileInputStream fis =(FileInputStream) getResources.openRawResource(R.raw.words);
3) res/assets folder
InputStream is = (InputStream) getAssets().open("words.xml");
This points to your local computer, when you deploy an APK you can't reference.
Document document = builder.parse(new FileInputStream("C:\\Users\\Ocean\\AndroidStudioProjects\\Deneme1Project\\Deneme1\\build\\res\\assets\\words.xml"));
Try instead:
getAssets().open("words.xml");
Where words.xml is in your assets directory. This will work from an Activity
, or if you have a Context
you can call getAssets() on the context, ie context.getAssets()
.
Put your xml file in res/raw (if raw folder doesn't exists under res create it) folder (lets say its words.xml). After that call it like this:
FileInputStream fis =(FileInputStream) getResources.openRawResource(
R.raw.words);
Document document = builder.parse(new FileInputStream(fis));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.