Bufferedreader returning null

南笙酒味 提交于 2019-12-11 21:20:14

问题


i'm trying to read a web address from a text and then have the app open that address, my buffered reader seems to be reading the lines correctly but readline keeps coming back null

String rsslink = null;
    InputStream is = getResources().openRawResource(R.raw.xmlsource);
    BufferedReader br = new BufferedReader(new InputStreamReader(is));

    try {
        while ((rsslink = br.readLine()) != null) 
        {

        }
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    }
    String RSS_LINK = rsslink;

    Log.d(Constants.TAG, "Service started");
    List<RssItem> rssItems = null;
    try 
    {
        XMLRssParser parser = new XMLRssParser();
        rssItems = parser.parse(getInputStream(RSS_LINK));

回答1:


You will get the last line that is null rsslink. You need to change your loop

try {
        while ((rsslink = br.readLine()) != null) 
        {

        }
    } 

to

 try {
        StringBuilder sb=  new StringBuilder();
        while ((rsslink = br.readLine()) != null) 
        {
               sb.append(rsslink);
        }
        rsslink = sb.toString();
    } 



回答2:


Use this:

String rsslink = "";
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;

try {
    while ((line = br.readLine()) != null) 
    {
       rsslink +=line ;
    }
} 
catch (IOException e) 
{
    e.printStackTrace();
}
String RSS_LINK = rsslink;

Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try 
{
    XMLRssParser parser = new XMLRssParser();
    rssItems = parser.parse(getInputStream(RSS_LINK));

Better your StringBuffer orStringBuilder.

StringBuilder rsslink = new StringBuilder();
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;

try {
    while ((line = br.readLine()) != null) 
    {
       rsslink.append(line);
    }
} 
catch (IOException e) 
{
    e.printStackTrace();
}
String RSS_LINK = rsslink.toString();


来源:https://stackoverflow.com/questions/19582100/bufferedreader-returning-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!