2012-10-16 10 views
7
public class XMLParser { 

    // constructor 
    public XMLParser() { 

    } 


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

     getset d1 = new getset(); 
     String d = d1.getData(); // text 
     String y = d1.getYear(); // year 
     String c = d1.getCircular(); 
     String p = d1.getPage(); 

     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
     nameValuePairs.add(new BasicNameValuePair("YearID", y)); 

     nameValuePairs.add(new BasicNameValuePair("CircularNo", c)); 

     nameValuePairs.add(new BasicNameValuePair("SearchText", d)); 
     nameValuePairs.add(new BasicNameValuePair("pagenumber", p)); 
     try { 

      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost(url); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      HttpResponse response = httpclient.execute(httppost); 

      HttpEntity entity = response.getEntity(); 

      responseBody = EntityUtils.toString(entity); 

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


    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) { 
      Log.e("Error: ", e.getMessage()); 

      // i m getting Exception here 

      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)); 
    } 
} 

Ricevo eccezioni in questa classe per l'analisi dei dati. Voglio stampare questo messaggio in un'altra classe che si estende da Activity. Per favore, dimmi come? Ho provato molto, ma non è in grado di fare ..Come impostare il messaggio quando ottengo l'eccezione

public class AndroidXMLParsingActivity extends Activity { 

    public int currentPage = 1; 
    public ListView lisView1; 
    static final String KEY_ITEM = "docdetails"; 
    static final String KEY_NAME = "heading"; 
    public Button btnNext; 
    public Button btnPre; 
    public static String url = "http://dev.taxmann.com/TaxmannService/TaxmannService.asmx/GetNotificationList"; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     // listView1 
     lisView1 = (ListView) findViewById(R.id.listView1); 

     // Next 
     btnNext = (Button) findViewById(R.id.btnNext); 
     // Perform action on click 
     btnNext.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       currentPage = currentPage + 1; 
       ShowData(); 
      } 
     }); 

     // Previous 
     btnPre = (Button) findViewById(R.id.btnPre); 
     // Perform action on click 
     btnPre.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       currentPage = currentPage - 1; 
       ShowData(); 
      } 
     }); 

     ShowData(); 
    } 

    public void ShowData() { 
     XMLParser parser = new XMLParser(); 
     String xml = parser.getXmlFromUrl(url); // getting XML 

     Document doc = parser.getDomElement(xml); // getting DOM element 

     NodeList nl = doc.getElementsByTagName(KEY_ITEM); 

     int displayPerPage = 5; // Per Page 
     int TotalRows = nl.getLength(); 
     int indexRowStart = ((displayPerPage * currentPage) - displayPerPage); 
     int TotalPage = 0; 
     if (TotalRows <= displayPerPage) { 
      TotalPage = 1; 
     } else if ((TotalRows % displayPerPage) == 0) { 
      TotalPage = (TotalRows/displayPerPage); 
     } else { 
      TotalPage = (TotalRows/displayPerPage) + 1; // 7 
      TotalPage = (int) TotalPage; // 7 
     } 
     int indexRowEnd = displayPerPage * currentPage; // 5 
     if (indexRowEnd > TotalRows) { 
      indexRowEnd = TotalRows; 
     } 

     // Disabled Button Next 
     if (currentPage >= TotalPage) { 
      btnNext.setEnabled(false); 
     } else { 
      btnNext.setEnabled(true); 
     } 

     // Disabled Button Previos 
     if (currentPage <= 1) { 
      btnPre.setEnabled(false); 
     } else { 
      btnPre.setEnabled(true); 
     } 

     // Load Data from Index 
     int RowID = 1; 
     ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>(); 
     HashMap<String, String> map; 

     // RowID 
     if (currentPage > 1) { 
      RowID = (displayPerPage * (currentPage - 1)) + 1; 
     } 

     for (int i = indexRowStart; i < indexRowEnd; i++) { 
      Element e = (Element) nl.item(i); 
      // adding each child node to HashMap key => value 
      map = new HashMap<String, String>(); 
      map.put("RowID", String.valueOf(RowID)); 
      map.put(KEY_NAME, parser.getValue(e, KEY_NAME)); 

      // adding HashList to ArrayList 
      menuItems.add(map); 

      RowID = RowID + 1; 

     } 

     SimpleAdapter sAdap; 
     sAdap = new SimpleAdapter(AndroidXMLParsingActivity.this, menuItems, 
       R.layout.list_item, new String[] { "RowID", KEY_NAME }, 
       new int[] { R.id.ColRowID, R.id.ColName }); 
     lisView1.setAdapter(sAdap); 
    } 

} 

Questa mia classe dove voglio stampare quel messaggio

+0

implementare un'interfaccia nel proprio XMLParser'. E imposta i risultati lì ... –

+0

Spero che il tuo problema sia stato risolto. Ho ragione? – Praveenkumar

risposta

1

È sufficiente passare il costruttore per la classe XMLParser e utilizzato che come costruttore. In alternativa, si può provare con l'uso di getApplicationContext() Si può semplicemente mostrare la Toast quando si ottenere un'eccezione come qui di seguito -

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()); 
    Toast.makeToast(con, e.toString(), Toast.Long).show(); // Will show the message of exception 
    return null; 
} catch (SAXException e) { 
    Log.e("Error: ", e.getMessage()); 
    Toast.makeToast(con, e.toString(), Toast.Long).show(); // Will show the message of exception 
    // i m getting Exception here 
    return null; 
} catch (IOException e) { 
    Log.e("Error: ", e.getMessage()); 
    Toast.makeToast(con, e.toString(), Toast.Long).show(); // Will show the message of exception 
    return null; 
} 

Aggiornamento

Va bene, basta passare il costruttore come sotto - Dove sei chiamando che XMLparser classe basta chiamare come qui di seguito -

.... 
XMLParser xml = new XMLParser(AndroidXMLParsingActivity.this); 
.... 

E, in XMLParser classe ci indicare il vostro costruttore come qui di seguito -

public class XMLParser { 

    Context con; 

    public XMLParser(Context context) { 

     con = context; 

    } 
...... 
} 

E, utilizzare questo con come costruzione nella classe XMLParser.

+0

Ma l'eccezione non sta per estendere la classe di attività come stamperò? – user1748932

+0

@ user1748932 Prova il codice aggiornato. E, prima, prova con 'getApplicationContext()' o passa il contesto alla tua classe 'parseXML' e usalo lì. – Praveenkumar

+0

che voglio sapere come passare il contesto alla classe parsexml – user1748932

1

Per mostrare Messaggio Classe non Activity dovrai passare attuale contesto di attività come:

public class XMLParser { 

Context context 
    // constructor 
    public XMLParser(Context conts) { 
    context =conts; 
    } 
///YOUR CODE 
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()); 
    Toast.makeToast(context, e.toString(), Toast.Long).show(); 
    return null; 
} catch (SAXException e) { 
    Log.e("Error: ", e.getMessage()); 
    Toast.makeToast(context, e.toString(), Toast.Long).show(); 
    // i m getting Exception here 
    return null; 
} catch (IOException e) { 
    Log.e("Error: ", e.getMessage()); 
    Toast.makeToast(context, e.toString(), Toast.Long).show(); 
    return null; 
} 
2

Si può semplicemente circondare il codice con un blocco Try/Catch come questo:

String xml; 
Document doc; 
NodeList nl; 

try { 

    xml = parser.getXmlFromUrl(url); // getting XML 
    doc = parser.getDomElement(xml); // getting DOM element 
    nl = doc.getElementsByTagName(KEY_ITEM); 
} catch (Exception e) { 
    Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show(); 
} 

In questo modo non è necessario apportare modifiche alla classe XMLParser e si può facilmente gestire eventuali eccezioni che si verificano durante l'analisi del codice nella classe principale stessa. Inoltre, per la visualizzazione dei messaggi di errore, Toast è la cosa migliore secondo me.

Spero che questo aiuti .. Grazie.

2

direi, aggiungere throws SAXException in XMLParser.getDomElement() metodo e non catturano SAXException in questo metodo come:

public Document getDomElement(String xml) throws SAXException { 

Catch the SAXException in AndroidXMLParsingActivity.ShowData() in cui si chiedono getDomElement() metodo e stampare il messaggio nel modo desiderato per esempio

public void ShowData() { 
    XMLParser parser = new XMLParser(); 
    String xml = parser.getXmlFromUrl(url); // getting XML 

    Document doc = null; 
    try{ 
      doc = parser.getDomElement(xml); // getting DOM element 
     }catch(SAXException sae){ 
     //print the desired message here 
     } 

     ....... 
     ....... 
} 
+0

Non è il momento in cui ho applicato questo, quindi AndroidOMLParsingActivity non è in grado di eseguire l'Eccezione – user1748932

+0

per favore dire alla tua email ti mando il codice sorgente il suo piccolo lavoro ma non so qui sto facendo male sto cercando di implementarlo negli ultimi 2 giorni non in grado per favore aiutatemi – user1748932

+0

non è lì per favore dimmi il tuo indirizzo e-mail manderò il codice sorgente completo in modo che tu possa capire dove sto sbagliando, per favore aiutami – user1748932

Problemi correlati