2012-10-16 25 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)); 
    } 
} 

Tôi nhận được Ngoại lệ trong lớp này để phân tích dữ liệu. Tôi muốn in thư này trong một lớp khác mở rộng từ Hoạt động. Bạn có thể vui lòng cho tôi biết làm thế nào? Tôi đã cố gắng nhiều nhưng không thể làm được ..Cách đặt thông báo khi tôi nhận Ngoại lệ

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

} 

lớp học của tôi này, nơi tôi muốn In rằng thông điệp

+0

triển khai giao diện trong 'XMLParser' của bạn. Và đặt kết quả ở đó ... –

+0

Tôi hy vọng vấn đề của bạn đã được giải quyết. Tôi có đúng không? – Praveenkumar

Trả lời

1

Đơn giản chỉ cần vượt qua constructor cho lớp XMLParser của bạn và sử dụng rằng có như constructor của bạn. Hoặc, bạn có thể thử với việc sử dụng getApplicationContext() Bạn chỉ có thể hiển thị các Toast khi bạn nhận được một ngoại lệ như dưới đây -

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

Cập nhật

Được rồi, chỉ cần vượt qua các nhà xây dựng theo dưới đây - Anh đang ở đâu gọi đó XMLparser lớp chỉ cần gọi như dưới đây -

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

Và, trong XMLParser lớp có đề cập đến constructor của bạn như dưới đây -

public class XMLParser { 

    Context con; 

    public XMLParser(Context context) { 

     con = context; 

    } 
...... 
} 

Và sử dụng số con làm người xây dựng của bạn trong lớp XMLParser.

+0

Nhưng ngoại lệ không đến trong việc mở rộng Lớp học hoạt động như thế nào tôi sẽ in? – user1748932

+0

@ user1748932 Hãy thử mã cập nhật. Và, trước tiên hãy thử với 'getApplicationContext()' hoặc chuyển ngữ cảnh tới lớp 'parseXML' của bạn và sử dụng nó ở đó. – Praveenkumar

+0

mà tôi muốn biết làm thế nào để vượt qua bối cảnh để parsexml lớp – user1748932

1

Đối với cho thấy tin nhắn từ Hoạt động lớp Non bạn sẽ cần phải vượt qua hiện tại Hoạt động Bối cảnh như:

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

Bạn chỉ có thể đặt mã của bạn với một khối Try/Catch như thế này:

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

Bằng cách này bạn không phải thực hiện bất kỳ thay đổi nào trong lớp học XMLParser của mình và bạn có thể dễ dàng xử lý mọi ngoại lệ xảy ra trong khi phân tích cú pháp mã của bạn trong chính lớp đó. Ngoài ra, để hiển thị thông báo lỗi, Toast là điều tốt nhất theo tôi.

Hy vọng điều này sẽ giúp .. Cảm ơn.

2

Tôi xin nói, thêm throws SAXException trong XMLParser.getDomElement() phương pháp và không bắt SAXException trong phương pháp này như sau:

public Document getDomElement(String xml) throws SAXException { 

Săn SAXException trong AndroidXMLParsingActivity.ShowData() nơi bạn đang gọi getDomElement() phương pháp và in thông điệp theo cách mong muốn ví dụ

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

Không có nó khi tôi trieed để áp dụng này AndAndroidXMLParsingActivity không thể Pic ngoại lệ – user1748932

+0

xin vui lòng cho ur email tôi sẽ gửi u mã nguồn công việc nhỏ của nó nhưng tôi không biết ở đây im làm sai im cố gắng thực hiện nó từ 2 ngày qua không thể để làm plz giúp tôi – user1748932

+0

nó không có xin vui lòng cho tôi biết id email ur tôi sẽ gửi mã nguồn hoàn chỉnh để u có thể hiểu nơi im làm sai xin vui lòng giúp tôi – user1748932

Các vấn đề liên quan