Search code examples
androidhttpandroid-resourcesandroid-developer-api

How to load a resource file from url?


  • I have an application that loads a configuration.xml file from res/raw file using this line :

    Example:

        Resources resources = context.getResources();
        InputStream is = resources.openRawResource(ResourceIds.raw.configuration);
    
  • I want to put the configuration.xml file into a server folder (http url) and then i can load it like this :

    Example:

        Resources resources = context.getResources();
        InputStream is = resources.openRawResource(http://example.com/folder/configuration.xml);
    

Can you help me with this please?!


Solution

  • So if I'm understanding you, you need an input stream that reads your XML from a web server. That would look like this:

    InputStream is = new URL("http://example.com/folder/configuration.xml").openConnection().getInputStream();
    

    However there's much more to this, you can't do this on the main thread (see NetworkOnMainThreadException) and you have to be prepared that there is no internet connection or that it downloads slowly. So I don't know what you use this configuration for but for example you may have to have defaults and put a "please wait" message on the screen.