簡體   English   中英

出現異常時如何設置消息

[英]How to set message when I get Exception

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

我在此類中獲取數據解析異常。 我想在從Activity擴展的另一個類中打印此消息。 你能告訴我如何嗎? 我嘗試了很多,但沒能做。

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

}

這是我想在其中打印消息的班級

您可以像下面這樣簡單地用Try/Catch塊包圍代碼:

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

這樣,您不必在XMLParser類中進行任何更改,並且可以輕松處理在主類本身中解析代碼時發生的任何異常。 而且,對於顯示錯誤消息,對我來說, Toast是最好的選擇。

希望這會有所幫助..謝謝。

我會說,在XMLParser.getDomElement()方法中添加throws SAXException ,並且在此方法中不要捕獲SAXException為:

  public Document getDomElement(String xml) throws SAXException {

在要調用getDomElement()方法的AndroidXMLParsingActivity.ShowData()中捕獲SAXException並以所需方式打印消息,例如

 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
      }

      .......
      .......
 }

只需將構造函數傳遞給XMLParser類,然后將其用作構造函數即可。 或者,您可以嘗試使用getApplicationContext() ,當遇到如下所示的異常時,可以簡單地顯示Toast

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

更新資料

好的,只需按照下面的方法傳遞構造函數-在調用XMLparser類的地方,就像下面這樣調用-

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

而且,在XMLParser類中,您可以像下面這樣提及您的構造函數-

public class XMLParser {

    Context con;

    public XMLParser(Context context) {

        con = context;

    }
......
}

並且,將此con用作XMLParser類中的構造函數。

為了顯示來自非活動類的消息,您需要將“當前活動上下文”傳遞為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM