2

My if (httpResponse == null) block doesn't get to run. How It could be implemented before HttpResponse httpResponse = httpClient.execute(httpPost);

Please show me how it could be done.

    public class XMLParser {
    private Activity activity = null;
    // constructor
    public XMLParser(Activity act) {
        activity = act;
    }

    /**
     * Getting XML from URL making HTTP request
     * @param url string
     * */
    public String getXmlFromUrl(String url) {
        String xml = null;

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // return XML
        return xml;
    }

    /**
     * Getting XML DOM element
     * @param XML string
     * */
    public Document getDomElement(String xml){
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {

            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                doc = db.parse(is); 

            } catch (ParserConfigurationException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (SAXException e) {
                AlertDialog.Builder builder = new AlertDialog.Builder( activity ); //<<-- This part throws an exception " ThreadPoolExecutor "
                builder.setMessage( "Host not found" )
                        .setCancelable(false)
                        .setPositiveButton("Exit",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int id) {
                                        System.exit(0);
                                    }

                                });
                AlertDialog alert = builder.create();
                alert.show();
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (IOException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }

            return doc;
    }

    /** Getting node value
      * @param elem element
      */
     public final String getElementValue( Node elem ) {
         Node child;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                     if( child.getNodeType() == Node.TEXT_NODE  ){
                         return child.getNodeValue();
                     }
                 }
             }
         }
         return "";
     }

     /**
      * Getting node value
      * @param Element node
      * @param key string
      * */
     public String getValue(Element item, String str) {     
            NodeList n = item.getElementsByTagName(str);        
            return this.getElementValue(n.item(0));
        }
}
Android Novice
  • 536
  • 3
  • 14
  • 33

2 Answers2

2

When something goes wrong, execute will not return null but throw an exception. For instance, when the host is not found, it throws an UnknownHostException. This exception is a subclass of IOException.

Your code is designed to 'catch' IOException. But when this occurs, you only print a stacktrace (this can be seen in orange in your LogCat) and do nothing. So next, the 'return xml' statement is executed and your method ends.

So if you want to 'catch' the case where a host does not exist, you could rewrite it like below. To catch more errors you probably should work out the IOException catch block. Please see that you understand what happens and how exception handling works.

public String getXmlFromUrl(String url) {
    String xml = null;

    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);

        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);

    } catch (UnknownHostException e) {
        AlertDialog.Builder builder = new AlertDialog.Builder( activity );
        builder.setMessage( "Host not found" )
                .setCancelable(false)
                .setPositiveButton("Exit",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int id) {
                                System.exit(0);
                            }

                        });
        AlertDialog alert = builder.create();
        alert.show();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // return XML
    return xml;
}
Jochem
  • 2,995
  • 16
  • 18
  • My AlertDialog.Builder builder = new AlertDialog.Builder( activity ); throws an exception " ThreadPoolExecutor " – Android Novice Aug 26 '12 at 13:25
  • Thanks for accepting the answer. Now that you have changed your code, your question is a bit confusing (for others that find this page). Next time you should keep that in mind. Also, I see that you put the error code now in `SAXException`, which occurs if something goes wrong during XML parsing. Please realize that every catch block catches a different exception. – Jochem Aug 26 '12 at 19:38
  • Also `ThreadPoolExecutor` is not an Exception, it's probably the one throwing it or somewhere on the stack. – Jochem Aug 26 '12 at 19:45
-1

I don't think that a no-response from server creates a null response. Can you debug that an explore the value of httpResponse in runtime?

Jose L Ugia
  • 5,960
  • 3
  • 23
  • 26