简体   繁体   English

调用引发异常的方法

[英]Call a method that throws exception

I am writing an app to pull and display content from an atom feed. 我正在编写一个应用程序,以从原子供稿中提取和显示内容。 The method for that works, but I get the error " Unhandled exception: java.lang.Exception " when I try to call the method " showFeed() " in onNavigationItemSelected . 该方法有效,但是当我尝试在onNavigationItemSelected调用方法“ showFeed() ”时,出现错误“ Unhandled exception: java.lang.Exception ”。

package com.myapp;
import java.net.URL;
import java.util.Iterator;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

// ... 

public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {
        case R.id.navigation_home:
            showFeed();
    }
}

// ...

public void showFeed() throws Exception {

    URL url = new URL("http://feeds.feedburner.com/javatipsfeed");
    XmlReader xmlReader = null;

    try {

        xmlReader = new XmlReader(url);
        SyndFeed feeder = new SyndFeedInput().build(xmlReader);
        System.out.println("Title Value " + feeder.getAuthor());

        for (Iterator iterator = feeder.getEntries().iterator(); iterator.hasNext();) {
            SyndEntry syndEntry = (SyndEntry) iterator.next();
            System.out.println(syndEntry.getTitle());
        }
    } finally {
        if (xmlReader != null)
            xmlReader.close();
    }

}

I want to call this method in onNavigationItemSelected . 我想在onNavigationItemSelected调用此方法。

Your showFeed method is throwing Exception, 您的showFeed方法引发Exception,

public void showFeed() throws Exception

This has to be caught using try-catch block or thrown further from the caller method which is onNavigationItemSelected 必须使用try-catch块将其捕获,或者将其从onNavigationItemSelected的调用方方法中onNavigationItemSelected

So either catch it like this, 所以要么抓住它,

 case R.id.navigation_home:
try{
            showFeed();
} catch (Exception e) {
e.printStackTrace();
}

Or throw it again like below, 或像下面一样再次扔

public boolean onNavigationItemSelected(@NonNull MenuItem item) throws Exception

You are running network related threads on UI Thread which may cause ANR (Activity not responding) Follow the following tutorial. 您正在UI线程上运行与网络相关的线程,这可能会导致ANR(活动不响应),请遵循以下教程。

Android AsyncTask example and explanation Android AsyncTask示例和说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM