2

What got me to this point:

I wrote an XML web service that provides data from a CRM that is stored in a database. The purpose of the XML web service is so I can provide a limited set of data read-only to the outside world in a format that is easy for other applications to connect to and read from. (or so I thought).

My Specific Question:

I need to write an application in Android that can parse XML from this web service and present it to my user in a native application. What is the recommended way to connect to a web-site and pull it's XML down and parse it into an object?

Notes:

I cannot show you an example of the XML because the test server currently is not Internet facing (it will be soon enough). I am also not worried about the GUI development. I will tackle that after I get the data to the handset =).

2
  • 1
    Download the file with HTTP, then parse with a SAX Parser. Commented Apr 26, 2011 at 14:17
  • Thank you. I am reading up on SAX Parser now! Commented Apr 26, 2011 at 14:26

1 Answer 1

2

Here is some SAX code from one of our Android apps.

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
//. . .
public class MyXmlHandler extends DefaultHandler
{
    @Override
    public void startDocument()
    {
        Log.i(TAG,"Starting to parse document.");
    }
    @Override
    public void endDocument()
    {
            Log.i(TAG,"End of document.");
    }
    @Override
    public void startElement(String uri,String localName,String qName,Attributes attributes)
    {
        if(localName.equals("myxmltag"))
        {
                 //do something with myxmltag and attributes.
        }
    }    
}    
public void parseDocument()
{
    try {
         URL myxmlUri = new URL("file:///sdcard/appfolder/myxmldoc.xml");
         SAXParserFactory spf = SAXParserFactory.newInstance();
         SAXParser sp = spf.newSAXParser();
         XMLReader xr = sp.getXMLReader();
         MyXmlHandler myxmlhandler = new MyXmlHandler();
         xr.setContentHandler(myxmlhandler);
         InputSource inputs = new InputSource(myxmlUri.openStream());
         xr.parse(inputs);
         // . . . 

And the download code it has

private void downloadFile(String url, String destination) throws ParserConfigurationException, FileNotFoundException, SAXException, UnsupportedEncodingException, ClientProtocolException, IllegalStateException, IOException {
    if(isNetworkAvailable(this)){
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
        MultipartEntity reqEntity = new  MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        get.setHeader("user_id", user_id);
        reqEntity.addPart("user_id", new StringBody(user_id));
        HttpResponse response = client.execute(get);  
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
            String serverResponse = EntityUtils.toString(resEntity);
            BufferedWriter out = new BufferedWriter(new FileWriter(destination));
            out.write(serverResponse);
            out.close();
        }
    }
}

And isNetworkAvailable

public static boolean isNetworkAvailable(Context context)
{
    ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity == null) {
        Log.w("tag", "Connectivity Manager failed to retrieve.");
    } else {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
    }
    return false;
}

You probably want to edit downloadFile so there is some consequence if isNetworkAvailable returns false.

EDIT: I removed some code that may have been in your way. I gave everything a generic name that starts with "my" instead of what was in my code.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks. I have been reviewing an example put down by IBM and it is far more confusing than reading your code here.
It's simple. All you have to do is make a class that extends DefaultHandler, make overrides for what you want to use: startDocument, endDocument, startElement, endElement. Then instance, set the content handler, and parse! :) cheers
I will be working more on this project tonight. I will update if I get stuck on anything else. Thanks for your help adorablepuppy.
No problem. I'll check back for updates in case you get stuck.
Got this all working now in my first app reading from a custom XML web service. I still have a ton of work to do but the frame is up. I liked the isNetworkAvailable function you recommended, it's a great thing to check to enable cleaner use of my app.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.