Android: RadLex – How to HTTP post to a URL, retrieve and parse xml, format and display results in a ListView, override back button, Async Tasks, Loading Dialogs, Webservices and more…

RadLex for android is a program that uses Stanford’s BioPortal Webservices to retrieve data about the RadLex Ontology / Lexicon / Dictionary.  It currently allows the user to navigate the tree structure from concept to concept starting at the root term.

This application requires full Internet access permissions and is dependent on Stanford BioPortal’s webservices http://bioportal.bioontology.org being operational.

RadLex is available for free download at the Android Market: https://market.android.com/details?id=radlex.wave

User Instructions: [Short Click] or tap on a concept, will navigate to its children or sub-terms.  [Long Click] or hold on a concept, will popup a dialog with a definition and other term details (if it has any).


package radlex.wave;
 
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
 
import org.apache.http.util.ByteArrayBuffer;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
 
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
//import android.sax.Element;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
 
import org.w3c.dom.*;
 
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException; 
 
import org.apache.http.util.ByteArrayBuffer;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
 
import android.app.Activity;
import android.os.Bundle;
//import android.sax.Element;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
 
import org.apache.http.util.ByteArrayBuffer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
 
public class dance extends Activity
{
	//initialize variables.
	public Boolean masterBool = false;
    protected TextView _displayLoadStat;
    protected Button _cancelButton;
 
    //This variable will contain the current ConceptID
    protected String ridPass="RID1";
    //two AsyncTasks _initTaskGoInto - navigates into a concept id
    //               _initTaskGetInfo - gets concept information
    protected InitTaskGoIntoConceptId _initTaskGoInto;
	protected InitTaskGetConceptInformation _initTaskGetInfo;   
 
    ArrayList> mylist = new ArrayList>();
    HashMap map = new HashMap();
 
    //Application Controls
    LinkedList mLinkedList = new LinkedList();
    ListView list;
	ListView titleList;
	TextView  tvMainText;
	Button myXbtn;
 
	AlertDialog.Builder builder;
 
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //some more code
    	builder = new AlertDialog.Builder(this);
        myXbtn = (Button) findViewById(R.id.myExitBtn);
        myXbtn.setBackgroundResource(android.R.drawable.ic_delete);
        myXbtn.setOnClickListener(exitClickListener);
        String myString ="";
        _displayLoadStat = ( TextView ) findViewById( R.id.percent_field );
       map = new HashMap();
	      String T = "Written by MantasCode.com";
	     String S ="RID1";
	     String U = "[Long Click]: Concept Information \n[Short Click]: Navigate Tree\n\n Click to continue   >";
	         map.put("name", T);
	         map.put("conceptId", S);
	        map.put("to", U +"");
	         mylist.add(map);
	         popLV(mylist);
        list.setOnItemClickListener(new OnItemClickListener()
        {
        	public void onItemClick(AdapterView<!--?--> parent, View view,int position, long id)
        	{
	        		 HashMap mapClicked = new HashMap();
	        		 mapClicked = (HashMap) list.getItemAtPosition(position);
	        		 String myString = "";
	        		 if ( !mapClicked.get("to").toString().equals("0 &gt;") )
	        		 {
	        			 ridPass = mapClicked.get("conceptId");
	        		        _initTaskGoInto = new InitTaskGoIntoConceptId();
	        		        _initTaskGoInto.execute( dance.this );
	        		 }
	        		 else
	        		 {
	        			 Toast.makeText(getApplicationContext(),  "There are no Sub-Classes to \""+  mapClicked.get("name")+"\"" ,Toast.LENGTH_SHORT).show();
	        		 }
        	}
        }); 
 
        list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
        {
            //@Override
            public boolean onItemLongClick(AdapterView<!--?--> av, View v, int pos, long id)
            {
            	 HashMap mapClicked = new HashMap();
        		 mapClicked = (HashMap) list.getItemAtPosition(pos);
 
        	        ridPass = mapClicked.get("conceptId");
    		        _initTaskGetInfo = new InitTaskGetConceptInformation();
    		        _initTaskGetInfo.execute( dance.this );
 
                return true;
            }
        });
    }
 
    private OnClickListener exitClickListener = new OnClickListener()
    {
        public void onClick(View v)
        {
        	System.out.println("exit!");
        	builder.setMessage("Are you sure you want to exit?")
        	       .setCancelable(false)
        	       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        	           public void onClick(DialogInterface dialog, int id) {
        	                dance.this.finish();
        	           }
        	       })
        	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
        	           public void onClick(DialogInterface dialog, int id) {
        	                dialog.cancel();
        	           }
        	       });
        	AlertDialog alert = builder.create();
        	alert.show();
        }
    };
 
    protected class CancelButtonListener implements View.OnClickListener
    {
                public void onClick(View v) {
                        _initTaskGoInto.cancel(true);
                }
    }
 
    public void populateList(String conceptId)
    {
    	String myString ="";
 
    	 try
         {
    		 mLinkedList.addLast(conceptId);
    		 mylist.clear();
    		 String t;
    		 //asdfasdf
         	URL url = new URL("http://rest.bioontology.org/bioportal/virtual/ontology/1057?conceptid="+conceptId+"&amp;apikey=b00d4c0c-f214-4de4-99c2-ffb1e8dada0c&amp;light=1");
             URLConnection urlConn = url.openConnection();
             InputStream is = urlConn.getInputStream();
             BufferedInputStream bis = new BufferedInputStream(is);
             ByteArrayBuffer baf = new ByteArrayBuffer(50);
             int current = 0;
             while((current = bis.read()) != -1)
             {
           	  baf.append((byte)current);
             }
             myString = new String(baf.toByteArray());
             tvMainText = (TextView) findViewById(R.id.headText);
             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    		  	DocumentBuilder db = dbf.newDocumentBuilder();
    		  	Document doc = stringToDom(myString);
    			doc.getDocumentElement().normalize();
    			System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
    			NodeList nList = doc.getElementsByTagName("classBean");
    			ArrayList resultElement = new ArrayList(); 
 
    		   ///////////////////////////////////////////////////
             NodeList listOfClassNodes = doc.getElementsByTagName("classBean");
             for(int s=1; s();
             	      String T = nameNode.item(0).getFirstChild().getNodeValue();
             	     String S =idNode.item(0).getFirstChild().getNodeValue();
             	     String U = iChildNode.item(0).getFirstChild().getNodeValue();
             	         map.put("name", T);
             	         map.put("conceptId", S);
             	        map.put("to", U +" &gt;");
             	         mylist.add(map);
             	         popLV(mylist);
             	}
             }
    		//PARSE the results into ArrayList
        		for (int temp = 0; temp &lt; nList.getLength(); temp++)
        		{
 			       Node nNode = nList.item(temp);
 			       if (nNode.getNodeType() == Node.ELEMENT_NODE)
 			       {
 			    	  // Toast.makeText(getApplicationContext(), nNode.getNodeType() ,Toast.LENGTH_LONG).show();
 			       }
 			    }                             //asdfasdf
        		titleList = (ListView) findViewById(R.id.listTitle);
 
        		// iterate over the LinkedList
    		    Iterator it = mLinkedList.iterator(); 
 
    		    String s ="";
 
    		    while (it.hasNext())
    		    {
    		      s += (String)it.next();
    		      System.out.println(s);
    		    }
         }
         catch(Exception e)
         {
         }
    }
 
    public static Document stringToDom(String xmlSource)
    throws SAXException, ParserConfigurationException, IOException
    {
    	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    	DocumentBuilder builder = factory.newDocumentBuilder();
    	return builder.parse(new InputSource(new StringReader(xmlSource)));
    }
 
    public void popLV(ArrayList&gt; mylist)
    {
    	list = (ListView) findViewById(R.id.SCHEDULE);
    	SimpleAdapter mSchedule = new SimpleAdapter(this, mylist, R.layout.row, new String[] {"name", "conceptId", "to"}, new int[] {R.id.TRAIN_CELL, R.id.FROM_CELL, R.id.TO_CELL});
    	list.setAdapter(mSchedule);
    }
 
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
        	if (mLinkedList.size()== 1)
        		return super.onKeyDown(keyCode, event);
        	mLinkedList.removeLast();
        	ridPass = mLinkedList.getLast().toString();
	        _initTaskGoInto = new InitTaskGoIntoConceptId();
	        _initTaskGoInto.execute( dance.this );
        	populateList(" "+ mLinkedList.getLast());
        	mLinkedList.removeLast();
    		mLinkedList.remove(mLinkedList.size()-1);
    		 Iterator it = mLinkedList.iterator();
    		 String s ="";
 		    while (it.hasNext())
 		    {
 		      s += (String)it.next();
 		    }
 		    tvMainText.setText(  s );
    		return false;
        }
        return super.onKeyDown(keyCode, event);
    }
 
    protected class InitTaskGoIntoConceptId extends AsyncTask
    {
    	ProgressDialog dialog = ProgressDialog.show(dance.this, "",
                "Loading. Please wait...", true);
 
                @Override
                protected String doInBackground( Context... params )
                {
                        String myString = "";
                        try
                        {
                   		 mLinkedList.addLast(ridPass);
                        	URL url = new URL("http://rest.bioontology.org/bioportal/virtual/ontology/1057?conceptid="+ridPass+"&amp;apikey=b00d4c0c-f214-4de4-99c2-ffb1e8dada0c&amp;light=1");
                            URLConnection urlConn = url.openConnection();
                          //XML COMES IN THROUGH THIS InputStream
                            InputStream is = urlConn.getInputStream();
                            //Buffer the stream to this thing
                            BufferedInputStream bis = new BufferedInputStream(is);
                            ByteArrayBuffer baf = new ByteArrayBuffer(50);
                            int current = 0;
                            while((current = bis.read()) != -1)
                            {
                          	  baf.append((byte)current);
                            }
                            myString = new String(baf.toByteArray());
                            tvMainText = (TextView) findViewById(R.id.headText);
                            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                   		  	DocumentBuilder db = dbf.newDocumentBuilder();
                   		  	Document doc = stringToDom(myString);
                   			doc.getDocumentElement().normalize();
                   			System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
                   			NodeList nList = doc.getElementsByTagName("classBean");
                           ArrayList resultElement = new ArrayList();
 
                            NodeList listOfClassNodes = doc.getElementsByTagName("classBean");
 
                            for(int s=1; s();
                            	      String T = nameNode.item(0).getFirstChild().getNodeValue();
                            	     String S =idNode.item(0).getFirstChild().getNodeValue();
                            	     String U = iChildNode.item(0).getFirstChild().getNodeValue();
                            	         map.put("name", T);
                            	         map.put("conceptId", S);
                            	        map.put("to", U +" &gt;");
                            	         mylist.add(map);
                            	       //  popLV(mylist);
                            	         list = (ListView) findViewById(R.id.SCHEDULE);
                            	         SimpleAdapter mSchedule = new SimpleAdapter(dance.this, mylist, R.layout.row, new String[] {"name", "conceptId", "children"}, new int[] {R.id.TRAIN_CELL, R.id.FROM_CELL, R.id.TO_CELL});
                            	}
                            }
                        }
                        catch(Exception e)
                        {
                        	  Toast.makeText(getApplicationContext(),"FAIL" ,Toast.LENGTH_LONG).show();
                        }
                        return "Loaded";
                }
 
                // -- gets called just before thread begins
                @Override
                protected void onPreExecute()
                {
                	mylist.clear();
                	_displayLoadStat.setText( "Loading.." );
                    _displayLoadStat.setTextColor( 0xFFFF0000 );
                	dialog.show();
                        super.onPreExecute();
                }
                @Override
                protected void onProgressUpdate(Integer... values)
                {
                        super.onProgressUpdate(values);
                        _displayLoadStat.setText( ( values[0] * 2 ) + "%");
                       _displayLoadStat.setTextSize( values[0] );
                }
                @Override
                protected void onCancelled()
                {
                        super.onCancelled();
                        _displayLoadStat.setTextColor( 0xFFFF0000 );
                }
                @Override
                protected void onPostExecute( String result )
                {
                	super.onPostExecute(result);
                	popLV(mylist);
        		    Iterator it = mLinkedList.iterator();
        		    String s ="";
        		    while (it.hasNext())
        		    {
        		      s += (String)it.next();
        		      System.out.println(s);
        		    }
 
        		    tvMainText.setText(  s );
                	System.out.println(result);
                        _displayLoadStat.setText( result );
                        _displayLoadStat.setTextColor( Color.GREEN );
                        dialog.dismiss();
                }
    }
 
    private static String getTagValue(String sTag, Element eElement){
	    NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
	    Node nValue = (Node) nlList.item(0); 
 
	    return nValue.getNodeValue();
	 }
 
    private static String getTagValue2(String sTag, Element eElement){
	    NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
	    Node nValue = (Node) nlList.item(1); 
 
	    return nValue.getNodeValue();
	 }
 
    protected class InitTaskGetConceptInformation extends AsyncTask
    {
    	ProgressDialog dialog = ProgressDialog.show(dance.this, "",   "Loading. Please wait...", true);
    	String messageInfo;
                @Override
                protected String doInBackground( Context... params )
                {
                	String myString2="";
                	messageInfo="";
            		 //!////////////////
            		 try
            	        {
            	        	System.out.println("starting 1 ");
            	        	URL url = new URL("http://rest.bioontology.org/bioportal/concepts/45589?conceptid="+ridPass+
            	        			"&amp;apikey=b00d4c0c-f214-4de4-99c2-ffb1e8dada0c");
            	            URLConnection urlConn = url.openConnection();
            	        	System.out.println("starting 2 ");
            	            InputStream is = urlConn.getInputStream();
            	        	System.out.println("starting 3 ");
            	            BufferedInputStream bis = new BufferedInputStream(is);
            	            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            	        	System.out.println("starting 4 ");
            	            int current = 0;
            	            while((current = bis.read()) != -1)
            	            {
            	          	  	baf.append((byte)current);
            	            }
            	            myString2 = new String(baf.toByteArray());
            	            myString2 = myString2.replaceFirst("", "");
            	            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            	   		  	DocumentBuilder db = dbf.newDocumentBuilder();
            	   		  	Document doc = stringToDom(myString2);
            	   			doc.getDocumentElement().normalize();
            	   			System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
            	   			NodeList nList = doc.getElementsByTagName("entry");
            	   			ArrayList resultElement = new ArrayList();
            	   			NodeList myCustomNodes = doc.getElementsByTagName("entry");
            	   			XPath xpath = XPathFactory.newInstance().newXPath();
            	   			XPathExpression expr = xpath.compile("success/data/classBean/relations/entry");
            	   			Object result = expr.evaluate(doc, XPathConstants.NODESET);
            	   			NodeList nodes = (NodeList) result;
            	   			System.out.println(nodes.getLength());
            	   			for (int i = 0; i &lt; nodes.getLength(); i++)
            	   			{
            	   			 	System.out.println("MANTAS!!!!"+i);
            	   				System.out.println(nodes.item(i).getNodeName());
            	   				Element myEle = (Element) nodes.item(i);
            	   			  if ( getTagValue("string",myEle).toString().equals(":DIRECT-TYPE") )
            	   			  {
            	   				  System.out.println("::DIRECT TYPE::");
            	   			  }
            	   			  //Preferred_name
            	   			if ( getTagValue("string",myEle).toString().equals("Preferred_name") )
            				  {
            					  System.out.println("::Pref Name::");
            					  System.out.println( nodes.item(i).getTextContent() );
            					  messageInfo+= nodes.item(i).getTextContent().trim().toUpperCase()+" \n ";
            				  }
            	   			if ( getTagValue("string",myEle).toString().equals("Definition") )
            	 			  {
            	 				  System.out.println("::Definition::");
            	 				  System.out.println( nodes.item(i).getTextContent() );
            					  messageInfo+= nodes.item(i).getTextContent()+" \n ";
            	 			  }
            	   			//Non-English_name
            	   			if ( getTagValue("string",myEle).toString().trim().equals("Non-English_name") )
            				  {
            					  System.out.println("::Non-English_name::");
            					  System.out.println( nodes.item(i).getTextContent() );
            					  messageInfo+= nodes.item(i).getTextContent()+" \n ";
            				  }
            	   			}
            		    }
            		    catch(Exception e)
            		    {System.out.println("BROKE BROKE BROKE BROKE BROKE BROKE BROKE BROKE BROKE BROKE BROKE BROKE");}
 
                        return "Loaded";
                }
 
                // -- gets called just before thread begins
                @Override
                protected void onPreExecute()
                {
                	//mylist.clear();
                	_displayLoadStat.setText( "Loading.." );
                    _displayLoadStat.setTextColor( 0xFFFF0000 );
 
                	dialog.show();
 
                        super.onPreExecute();
                }
                @Override
                protected void onProgressUpdate(Integer... values)
                {
                        super.onProgressUpdate(values);
 
                        _displayLoadStat.setText( ( values[0] * 2 ) + "%");
                       _displayLoadStat.setTextSize( values[0] );
                }
 
                @Override
                protected void onCancelled()
                {
                        super.onCancelled();
                        _displayLoadStat.setTextColor( 0xFFFF0000 );
                }
                @Override
                protected void onPostExecute( String result )
                {
                	super.onPostExecute(result);
                	AlertDialog.Builder builder = new AlertDialog.Builder(dance.this);
        	        builder.setMessage( messageInfo )
        	               .setCancelable(false)
 
        	               .setNegativeButton("Close", new DialogInterface.OnClickListener()
        	               {
        	                   public void onClick(DialogInterface dialog, int id) {
        	                        dialog.cancel();
        	                   }
        	               });
        	        AlertDialog alert = builder.create();
        	        alert.show();
 
                        _displayLoadStat.setText( result );
                        _displayLoadStat.setTextColor( Color.GREEN );
                        dialog.dismiss();
                }
    }
 
}

One thought on “Android: RadLex – How to HTTP post to a URL, retrieve and parse xml, format and display results in a ListView, override back button, Async Tasks, Loading Dialogs, Webservices and more…

Leave a Reply

Your email address will not be published. Required fields are marked *