当前位置: 代码迷 >> Android >> 如何正确利用doinBackground()方法以检索RSS项
  详细解决方案

如何正确利用doinBackground()方法以检索RSS项

热度:88   发布时间:2023-08-04 10:54:55.0

现在,我正在创建一个RSS阅读器,主要是试图使项目的标题和描述显示在ListView上。 我之前没有RSS数据对其进行过测试,并确认该应用正确列出了我创建的项目。 但是,在尝试对RSS中的数据进行相同处理后,我在检索实际RSS数据以及如何使用doinBackground方法时遇到了问题。

阅读Google关于doinBackground的文档后,我了解到它的类(Async)允许执行后台操作并将其结果显示在UI线程中。 但是,我通常在提取RSS数据以及doinBackground()如何适合我的代码方面遇到问题。 关于如何正确检索数据并有效使用doinbackground()的任何想法?

我遇到麻烦的代码类别是Headlines和RSSManager。 这是代码:

标题片段

import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.net.MalformedURLException;
import java.net.URL;

public class Headlines extends Fragment {
EditText editText;
Button gobutton;
ListView listView;

public Headlines() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_headlines, container, false);
    editText = (EditText)v.findViewById(R.id.urlText);
    gobutton = (Button)v.findViewById(R.id.goButton);
    listView = (ListView)v.findViewById(R.id.listView);
    RSSFeedManager rfm = new RSSFeedManager();
    News [] news = new News[100]; // i shouldnt have to set the size of the array here since I did it in getFeed() in RSSFeedManager.java
    try {
        news = rfm.getFeed(String.valueOf(new URL("http://rss.cnn.com/rss/cnn_world.rss")));
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    RssAdapter adapter = new RssAdapter(this.getActivity(),news);
    listView.setAdapter(adapter);
    /*gobutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });*/
    return v;
}

}

RSSFeedManager

import android.os.AsyncTask;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class RSSFeedManager extends AsyncTask<String,Void,String> {
public URL rssURL;
News[] articles;

public News[] getFeed(String url) {
    try {
        String strURL = url;
        rssURL = new URL(url);
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(rssURL.openStream());

        //using Nodelist to get items within the rss, then creating
        //a News array the same size of the amount of items within the rss
        //then setting up a temporary "News" item which will be the temp object
        //used for storing multiple objects that contain title and description
        //of each item
        NodeList items = doc.getElementsByTagName("item");
        News[] articles = new News[items.getLength()];
        News news = null;

        //traverse through items and place the contents of each item within an RssItem object
        //then add to it to the News Array
        for (int i = 0; i < items.getLength(); i++) {
            Element item = (Element) items.item(i);
            news.setTitle(getValue(item, "title"));
            news.setDescription(getValue(item, "description"));
            articles[i] = news;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return articles;
}

public String getValue(Element parent, String nodeName) {
    return parent.getElementsByTagName(nodeName).item(0).getFirstChild().getNodeValue();
}

@Override
protected String doInBackground(String... url) {
    String rssURL = url[0];
    URL urlTemp;
    try {
        //pulling the url from the params and converting it to type URL and then establishing a connection
        urlTemp = new URL(rssURL);
        HttpURLConnection urlConnection = (HttpURLConnection) urlTemp.openConnection();
        urlConnection.connect();
        /*
        *im thinking i need to call the getFeed() method
        *after establishing the httpurlconnection however
        *I also thought I may just need to move the getFeed()
        *code within doinBackground. Lost at this point due to the
        * return types of getFeed and doinBackground
        */
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

}

在将每一行代码分开之后,我找出了RSSFeedManager类, doInBackground()方法和Headlines类的一些问题。

从RSSFeedManager开始,这里存在一些问题。 我将实例化的News [] articles实例化为类变量,然后在getFeeds()方法中对其进行了重新定义。 显然,这会导致一些问题,并且会将articles返回为null。 我还删除了strURLrssURL因为这是所有错误的方法。 不需要将URL传递给getFeeds()而是需要通过URL将XML传递给它。 我还修改了一些代码以利用News类的构造函数。

这是RSSFeedManager的固定代码:

public class RSSFeedManager{

News[] articles;

public News[] getFeed(String html) {
    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(new ByteArrayInputStream(html.getBytes()));

        NodeList items = doc.getElementsByTagName("item");
        articles = new News[items.getLength()];

        for (int i = 0; i < items.getLength(); i++) {
            Element item = (Element) items.item(i);
            News news = new News(getValue(item, "title"),getValue(item, "description").substring(0,100),"");
            articles[i] = news;
        }
    } catch (Exception e) {
        //e.printStackTrace();
        Log.d("EXCEPTION PARSING",e.toString());
    }
    return articles;
}

public String getValue(Element parent, String nodeName) {
    return parent.getElementsByTagName(nodeName).item(0).getFirstChild().getNodeValue();
}
}

如前所述,我意识到RSSFeedManager应该从URL而不是URL本身接收XML,并且应该在doInBackground()处放置一个新类。 本质上讲,带有Downloader类的doInBackground()方法(扩展了AsyncTask是接收输入的URL,然后从该RSS URL收集XML。

这是下载程序类

public class Downloader extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... urls) {
    String result ="";
    try{
        URL url = new URL(urls[0]);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        InputStream in = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while((line=reader.readLine())!= null){
            result= result + line;
        }
        connection.disconnect();

    } catch (Exception e) {
        Log.e("Error fetching", e.toString());
    }

    return result;
}
}

因此,在这两个课程都处理完之后,我知道我需要在头条新闻课程中解决一些问题。 最初,我蛮力地强迫代码进行测试,以确保RSS提要中的文章正确显示,然后确实显示出来,然后着手正确实施。 为了提醒人们,该程序的目的是显示RSS提要中的文章,用户可以通过将URL输入到editText这是一个EditText对象)中来指定该文章。 然后,用户按下Button类型为goButton ,然后列出editText中的所有URL文章。 我通过创建一个实现这个onClickListenergoButton和创建的对象的DownloaderRssFeedManager以调用它们的方法来建立连接,获取URL的XML,然后通过其解析类。

这是Headline类代码的一小段,我可以将所有内容捆绑在一起。

 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_headlines, container, false);
    editText = (EditText)v.findViewById(R.id.urlText);
    gobutton = (Button)v.findViewById(R.id.goButton);
    listView = (ListView)v.findViewById(R.id.listView);
    parent = this.getActivity();
    gobutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RSSFeedManager rfm = new RSSFeedManager();
            String html = "";
            try {
                Downloader d = new Downloader();
                d.execute(editText.getText().toString());
                html = d.get();
                Log.d("HTML CAME BACK", html);
                news = rfm.getFeed(html);
                RssAdapter adapter = new RssAdapter(parent, news);
                listView.setAdapter(adapter);
            } catch (InterruptedException e) {
                Log.e("ERROR!!!!!", e.toString());
            } catch (ExecutionException e) {
                Log.e("ERROR!!!!!!!", e.toString());
                Toast.makeText(parent, e.toString(), Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Log.e("WEIRD!", e.toString());
                Toast.makeText(parent, e.toString(), Toast.LENGTH_LONG).show();
            }


        }
    });

所有这些更改有助于解决问题,并使我能够进一步完成该程序,并了解有关android开发的更多信息。

  相关解决方案