In my application I have a function to populate listview.I want to run this function periodically on every 5 minutes.I have used following method for that.
private class RefreshThread extends Thread{
public boolean isStop = false;
public void run(){
try{
while(!isStop){
Headlines.this.runOnUiThread(new Runnable() {
public void run() {
populate_listview(); //Function to populate listview
}
});
try{ Thread.sleep(300000); } catch(Exception ex){}
}
}catch(Exception e){
}
}
}
when I use this method the function runs on foreground so the entire application got affected by this.I want to run this function in background so that the listview updates and the user never knows that the function is running.
following is the function to populate listview.
public void populate_listview()
{
ArrayList<HashMap<String, String>> newsList = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_HEAD);
// looping through all song nodes <song>
NodeList itemLst = doc.getElementsByTagName("item");
String MarqueeStr="";
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
//map.put(KEY_DATE, parser.getValue(e, KEY_DATE));
newsList.add(map);
}
To get smaller performance overhead, you should do all the preparations, including populating
HashMapwith proper values, in your background thread and leave inpopulate_listview()method onlynewList.add(refresh_thread.getMap());. Just add toRefreshThreadsynchronizedmethodgetMap()to access thisHashMapfrom another class, and anothersynchronizedmethodprepareHashMap()for the code that prepare it. Obviously, yourHashMapmust be a field ofRefreshThreadclass. Then, therun()method will look like this: