【问题标题】:Getting data with asyncTask and thread使用 asyncTask 和线程获取数据
【发布时间】:2012-10-18 09:25:09
【问题描述】:

我正在尝试从 RSS 提要中获取数据以在片段中显示它(11 个片段),但是每次我传递给一个新片段时,UI 都会阻塞几秒钟,因为它正在获取数据,所以我尝试使用 asyncTask 来做这是在后台,但它似乎不起作用。

public class AndroidSaxFeedParser extends AsyncTask<String, Long, ArrayList<Article>>{

String dt;
String bb;
String nameCat;
RootElement root;
Element item;

static final String RSS = "rss";
static final String FEED = "feed";
static final String ENTRY = "entry";
static final String CHANNEL = "channel";
static final String PUB_DATE = "pubDate";
static final  String DESCRIPTION = "description";
static final  String LINK = "link";
static final  String TITLE = "title";
static final  String ITEM = "item";
static final  String CATEGORY = "category";
static final  String DURATION = "itunes:duration";

ArrayList<Article> rssItems = new ArrayList<Article>();

public URL feedUrl;

Context mContext;

public AndroidSaxFeedParser(Context context)
{
    mContext = context;

}

//  ProgressDialog pd = new ProgressDialog(mContext);

@Override
protected void onPostExecute(ArrayList<Article> result) {
//      pd.dismiss();       
    super.onPostExecute(result);
}

@Override
protected void onPreExecute() {
//      ProgressDialog.show(mContext, "", "Chargement...");
    super.onPreExecute();
}

@Override
protected ArrayList<Article> doInBackground(String... params) {

    try {
        feedUrl = new URL(params[0]);
    } catch (MalformedURLException e1) {
        e1.printStackTrace();
    }

    final Article currentRssItem = new Article();
    root = new RootElement(RSS);
    Element channel = root.getChild(CHANNEL);
    item = channel.getChild(ITEM);

    item.getChild(TITLE).setEndTextElementListener(new EndTextElementListener(){
        public void end(String body) {
            currentRssItem.setTitle(body); 
            Log.i("Title Article", " "+currentRssItem.getTitle());
        }
    });

    item.getChild(CATEGORY).setEndTextElementListener(new EndTextElementListener(){
        public void end(String body) {
            currentRssItem.setCategorie(body);
            Log.i("Category Article", " "+currentRssItem.getCategorie());
        }
    });

    item.getChild(DESCRIPTION).setEndTextElementListener(new EndTextElementListener(){
        public void end(String body) {
            String imgUrl, desc;
            try {imgUrl = body.substring(body.indexOf("src=")+5,body.indexOf("\"", body.indexOf("src=")+6));} 
            catch (Exception e) 
            {imgUrl = "";}
            try {desc=body;} 
            catch (Exception e) 
            { desc = "";}
            currentRssItem.setImageUrl(imgUrl);
            currentRssItem.setDescription(desc);

            Log.i("Image URL Article", " "+currentRssItem.getImageUrl());
            Log.i("Description Article", " "+currentRssItem.getDescription());
        }
    });

    item.getChild(PUB_DATE).setEndTextElementListener(new EndTextElementListener(){
        public void end(String body) {
            currentRssItem.setPubDate(body);
            Log.i("Date Article", " "+currentRssItem.getPubDate());
        }
    });

    item.setEndElementListener(new EndElementListener(){
        public void end() {
            rssItems.add(currentRssItem.copy());
        }
    });
    try {
        Xml.parse(feedUrl.openConnection().getInputStream(), Xml.Encoding.UTF_8, root.getContentHandler());
    } catch (IOException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }   
    return rssItems;
}   

我在每个片段中都这样称呼它

ArrayList<Article> feeds ;
    try {
        feeds=AndroidSaxFeedParser.execute(url).get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

【问题讨论】:

  • it seems that it does not work 非常通用。您必须始终详细说明问题。
  • 我的意思是每次我传递到一个新的片段时,UI 仍然会阻塞几秒钟。

标签: java android multithreading rss android-asynctask


【解决方案1】:

在请求XML 类解析它之前,您应该始终下载文件并将其保存为String

public String getXml(String url) {
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);

// HTTP OK 200
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    HttpEntity entity = response.getEntity();
    // NOTE: Here need to set the default charset to be UTF-8
    content = EntityUtils.toString(entity, "UTF-8");
    return content;
}
} catch (IOException e) {
    e.printStackTrace();
} catch (IllegalStateException e) {
    content = null;
}
}

这样就不太可能因为连接问题而中断。另外,请告诉我们更多关于“似乎它不起作用”的含义。是解析xml失败,运行任务失败,还是失败了什么?

另外,你不应该打电话

feeds=AndroidSaxFeedParser.execute(url).get();

在您的片段中。你应该修改AndroidSaxFeedParser的这个函数:

@Override
protected void onPostExecute(ArrayList<Article> result) {
    feeds = result;
    // Do whatever you wanna do to set up things with the feeds
}

要完成这项工作,您必须将 AndroidSaxFeedParser 作为片段的内部类。

【讨论】:

  • 每次我传递到一个新片段时,UI 仍然会阻塞几秒钟。
  • 能否请您给我所有必须放入片段中的代码,我不知道我在哪里调用 getXml()!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多