【问题标题】:How to create Async Task to build a RSSReader如何创建异步任务来构建 RSSReader
【发布时间】:2017-06-24 08:27:17
【问题描述】:

在投票之前。是的,我在问这个问题之前阅读了论坛。 RSSReader Async Task

阅读上面的那个,但我仍然不明白。

问题:

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

这是我的 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;
    }


}  

【问题讨论】:

    标签: java android asynchronous android-asynctask


    【解决方案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;
            }
    
        }
    }
    

    【讨论】:

    • 感谢这段代码给出了一个空指针异常。列表为空,但我在 Intelij 中测试了我的代码,我确定代码填充了列表
    【解决方案2】:

    你是对的,你需要 Asynctask。不过这里解释的太多了,这里已经解释的很透彻了,大家不妨看看:

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

    您需要确保在doInBackground 中运行您的网络调用,您可以在onPreExcute 中操作UI,完成后在onpostExecute 中操作。更多详情请访问链接。

    【讨论】:

      【解决方案3】:

      好吧,我假设您已经知道代码,因此 doInBackground 方法中的代码应该是长时间运行的代码,例如从互联网/服务器等获取信息。然后您可以返回一个成功或错误的字符串这将从 onPostExecute 方法中捕获,您可以对结果做任何您喜欢的事情。

      所以我想说不需要新类,只需在其中扩展异步任务,实现我提到的 2 个方法,并在方法中调用您已经拥有的正确函数,只需稍作更改即可返回结果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-10
        • 2021-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多