简体   繁体   中英

Getting data with asyncTask and thread

I am trying to get data from RSS feed to display it in fragments (11 fragment), but each time i pass to a new fragment the UI block for a several seconds because it's fetching data so i try to use asyncTask to do this in background but it seems that it does not work.

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

I am calling it this way in each fragment

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

You should always download the file and save it as a String before asking the XML class to parse it.

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

In this way it is less likely to get interrupted due to connection problem. In addtition, please tell us more about what "it seems that it does not work" means. Did it fail to parse the xml, fail to run the task, or fail what?

Also, you should not be calling

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

in your fragment. You should modify this function of your AndroidSaxFeedParser :

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

To make this work you must put your AndroidSaxFeedParser as an inner class of your fragment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM