-1

Before getting down vote. Yes I read the forums before asking this question. RSSReader Async Task

Read that one above but I still don't get it.

The question:

I wrote een RSSReader in Java. This perfectly works in the console prints what I want etc. But in Android it doesn't work because it's not using een Async Task. Now I understood from the Google Documentation that there are three types to be entered AsyncTask something like that. I have no idea how I can implement this in my code. Do I need to make a seperate class extends it with AsyncTask and create and instance of my Reader and in it's doInBackground method call my reader or how do I need to do this.

This is the code of my 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;
    }


}  
Sander bakker
  • 518
  • 1
  • 6
  • 20

3 Answers3

1

In RSSReader#readRSS,you do not check tempList.size()

and do not forget add

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

to your AndroidManifest.xml

for example

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

    }
}
  • Thanks this code gives a null pointer exception. List empty but I tested my code in Intelij and I know for sure the code fills the list – Sander bakker Jun 24 '17 at 10:21
0

You are right, you need Asynctask. But it is too much to explain here, it has already been explained very thoroughly here, so you might wanna take a look:

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

What you need to make sure is to run your network calls in doInBackground, you can manipulate the UI in onPreExcute and after finish in onpostExecute. For more details please visit the link.

techfly
  • 1,826
  • 3
  • 25
  • 31
0

Well i assume that you already know the code so in the doInBackground method should be the long running code, like getting information from internet/server etc. You can then return a string with success or error that will be catched from onPostExecute method, where you can just do what ever you like with the result.

So i would say no need for new class just extend async task in this, implement the 2 methods i mentioned and in the methods call the right function that you already have with just a litttle change for returning result.

Marjan
  • 40
  • 3