Qadir Hussain
Qadir Hussain

Reputation: 8856

How to get a XML file from assets via a thread in Android?

Here is my scenario.

I have MainActivity.java in which I am calling the thread like this

private void callXMLParserThread() {

    String filePath = "file:///android_asset/weather_conditions.xml";
    parserThread = new XMLParserThread(context, filePath);
    parserThread.start();

}

and here is my XMLParserThread.java

public class XMLParserThread extends Thread {

Context context;
String fileName;
XMLParser xmlParser;

public XMLParserThread(Context context, String fileName) {

    this.context = context;
    this.fileName = fileName;
}

@Override
public void run() {

    xmlParser = new XMLParser();

    String xmlResponse = null;
    try {
        xmlResponse = xmlParser.getXmlFromFile(context, fileName);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Log.d("xmlResponse", xmlResponse + "");

    super.run();
}

}

Notice: In run() method I'm calling the another method getXmlFromFile() resides in XMLParser.java

Now here is my getXmlFromFile() method.

public String getXmlFromFile(Context context, String fileName) throws IOException {

    Log.e("fileName", fileName);

    InputStream is = null;
    try {
        is = context.getAssets().open(fileName);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    BufferedInputStream bis = new BufferedInputStream(is);
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    int result = bis.read();
    while(result != -1) {
      byte b = (byte)result;
      buf.write(b);
      result = bis.read();
    }        
    return buf.toString();
}

Problem

When I execute the code it throws the java.io.FileNotFoundException: file:///android_asset/weather_conditions.xml at xml.parser.XMLParser.getXmlFromFile(XMLParser.java:43)

where the line no 43 is is = context.getAssets().open(fileName); in my getXmlFromFile() method

Also, I'm sure the file exists in the assets folder. Where am I making a mistake?

Upvotes: 0

Views: 1043

Answers (2)

Maxim Shoustin
Maxim Shoustin

Reputation: 77910

When you define path from assets, write only path of sub-folder of assets.

If you have xml file under:

assets/android_asset/weather_conditions.xml

so file path should be:

String filePath = "android_asset/weather_conditions.xml";

BTW, you have helper in your code:

is = context.getAssets().open(fileName);

context.getAssets() means open assets folder and find out path there.

Upvotes: 1

Yuichi Araki
Yuichi Araki

Reputation: 3458

If I'm not mistaken, you can just say as below without that "file:///..." part.

String filePath = "weather_conditions.xml";

Upvotes: 0

Related Questions