如何创建Async Task来构建RSSReader

时间:2017-06-24 08:27:18

标签: java android asynchronous android-asynctask

在投票之前。是的我在提出这个问题之前就已经阅读了论坛RSSReader Async Task

阅读上面的内容,但我仍然没有得到它。

问题:

我用Java编写了een RSSReader。这完全适用于控制台打印我想要的等等。但在Android中它不起作用,因为它没有使用een异步任务。现在我从Google文档中了解到有三种类型可以输入AsyncTask。我不知道如何在我的代码中实现这一点。我是否需要创建一个单独的类,使用AsyncTask扩展它,并创建我的Reader的实例,并在其中使用doInBackground方法调用我的读者或如何执行此操作。

这是我的RSSReader的代码:

public class RSSReader {
    //Lists to store headlines, descriptions & images
    String url = "http://www.nu.nl/rss/Algemeen";
    List<String> titleList;
    List<String> descriptionList;
    List<String> imageList;
    public RSSReader(){

        try {
            titleList = readRSS(url, "<title>", "</title>");
            descriptionList = listFilter(readRSS(url, "<description>", "</description>"), "&amp;nbsp;", "");
            imageList = readRSS(url, "<enclosure url \"", "\" length=\"0\" type=\"image/jpeg\"</enclosure>");

        }
        catch (IOException e){

        }
        }
    public List<String> readRSS(String feedUrl, String openTag, String closeTag) throws IOException, MalformedURLException {

        URL url = new URL(feedUrl);
        BufferedReader reader= new BufferedReader(new InputStreamReader(url.openStream()));

        String currentLine;
        List<String> tempList = new ArrayList<String>();
        while((currentLine = reader.readLine()) != null){
            Integer tagEndIndex = 0;
            Integer tagStartIndex = 0;
            while (tagStartIndex >= 0){
                tagStartIndex = currentLine.indexOf(openTag, tagEndIndex);
                if(tagStartIndex >= 0){
                    tagEndIndex = currentLine.indexOf(closeTag, tagStartIndex);
                    tempList.add(currentLine.substring(tagStartIndex + openTag.length(), tagEndIndex) + "\n");
                }
            }
        }
        tempList.remove(0);
        return tempList;
    }

    public List<String> getDesciptionList(){
        return descriptionList;
    }

    public List<String> getTitleList(){
        return titleList;
    }
    public List<String> getImageList(){
        return imageList;
    }

    public List<String> listFilter(List<String> tempList, String require, String 
    replace){
        //Creates new List
        List<String> newList = new ArrayList<>();
        //Loops through old list and checks for the 'require' variable
        for(int i = 0; i < tempList.size(); i++){
            if(tempList.get(i).contains(require)){
                newList.add(tempList.get(i).replace(require, replace));
            }
            else{
                newList.add(tempList.get(i));
            }
        }
        return newList;
    }


}  

3 个答案:

答案 0 :(得分:1)

RSSReader#readRSS中,您不会检查tempList.size()

并且不要忘记添加

<uses-permission android:name="android.permission.INTERNET"/>

AndroidManifest.xml

例如

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new RssReaderAsyncTask(new RSSCallBack() {

            @Override
            public void success(RSSReader rssReader) {
                // TODO That Should run on UI Thread if you update UI
                // for example
                final RSSReader reader = rssReader;
                // you can use runOnUiThread or Handler update UI
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Toast 
                        Toast.makeText(MainActivity.this, reader.getTitleList().toString(), Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void failed() {
                // TODO That Should run on UI Thread if you update UI
                Log.e("RSS", "failed");
            }
        }).execute("");

    }

    private class RssReaderAsyncTask extends AsyncTask<String, Integer, Integer> {
        private RSSCallBack rssCallBack;

        public RssReaderAsyncTask(RSSCallBack rssCallBack) {
            this.rssCallBack = rssCallBack;
        }

        @Override
        protected Integer doInBackground(String... params) {
            // TODO
            try {
                RSSReader reader = new RSSReader();
                rssCallBack.success(reader);
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                rssCallBack.failed();
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                rssCallBack.failed();
                e.printStackTrace();
            }
            return null;
        }

    }

    private interface RSSCallBack {
        void success(RSSReader rssReader);

        void failed();
    }

    public class RSSReader {
        // Lists to store headlines, descriptions & images
        String url = "http://www.nu.nl/rss/Algemeen";
        List<String> titleList;
        List<String> descriptionList;
        List<String> imageList;

        public RSSReader() throws MalformedURLException, IOException {

            titleList = readRSS(url, "<title>", "</title>");
            descriptionList = listFilter(readRSS(url, "<description>", "</description>"), "&amp;nbsp;", "");
            imageList = readRSS(url, "<enclosure url \"", "\" length=\"0\" type=\"image/jpeg\"</enclosure>");

        }

        public List<String> readRSS(String feedUrl, String openTag, String closeTag)
                throws IOException, MalformedURLException {

            URL url = new URL(feedUrl);
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));

            String currentLine;
            List<String> tempList = new ArrayList<String>();
            while ((currentLine = reader.readLine()) != null) {
                Integer tagEndIndex = 0;
                Integer tagStartIndex = 0;
                while (tagStartIndex >= 0) {
                    tagStartIndex = currentLine.indexOf(openTag, tagEndIndex);
                    if (tagStartIndex >= 0) {
                        tagEndIndex = currentLine.indexOf(closeTag, tagStartIndex);
                        tempList.add(currentLine.substring(tagStartIndex + openTag.length(), tagEndIndex) + "\n");
                    }
                }
            }
            if (tempList.size() > 0) {
                //TODO you do not check it
                tempList.remove(0);
            }
            return tempList;
        }

        public List<String> getDesciptionList() {
            return descriptionList;
        }

        public List<String> getTitleList() {
            return titleList;
        }

        public List<String> getImageList() {
            return imageList;
        }

        public List<String> listFilter(List<String> tempList, String require, String replace) {
            // Creates new List
            List<String> newList = new ArrayList<String>();
            // Loops through old list and checks for the 'require' variable
            for (int i = 0; i < tempList.size(); i++) {
                if (tempList.get(i).contains(require)) {
                    newList.add(tempList.get(i).replace(require, replace));
                } else {
                    newList.add(tempList.get(i));
                }
            }
            return newList;
        }

    }
}

答案 1 :(得分:0)

你是对的,你需要Asynctask。但这里解释得太多了,这里已经对它进行了彻底的解释,所以你可能想看看:

https://stackoverflow.com/a/9671602/3673616

您需要确保在doInBackground中运行网络电话,您可以在onPreExcuteonpostExecute完成后操作用户界面。有关详细信息,请访问该链接。

答案 2 :(得分:0)

我假设您已经知道代码,因此 doInBackground 方法应该是长时间运行的代码,例如从Internet /服务器等获取信息。然后您可以返回成功或错误的字符串将从 onPostExecute 方法中获取,您可以使用结果执行任何您喜欢的操作。

所以我要说新类只需要在这里扩展异步任务,实现我提到的2个方法,并在方法中调用你已经拥有的正确函数,只需要对返回结果进行一点点改动。