我使用下面的代码每分钟使用从 xml Web 服务返回的数据刷新列表字段。但第一次刷新后,数据重复。如何防止它重复?
public final class MyScreen extends MainScreen implements ListFieldCallback
{
ResponseHandler handler = new ResponseHandler();
ListField listUsers = new ListField(handler.getItem().size());
Manager mainManager = getMainManager();
protected void onUiEngineAttached(boolean attached) {
if (attached) {
Timer timer = new Timer();
// schedule the web service task to run every minute
timer.schedule(new WebServiceTask(), 0, 3000);
}
}
public MyScreen() {
setTitle("Uikro");
listUsers.setEmptyString("No Users found", 0);
listUsers.setCallback(this);
add(listUsers);
handler.getItem().removeAllElements();
}
private class WebServiceTask extends TimerTask {
public void run() {
//Fetch the xml from the web service
String wsReturnString = GlobalV.Fetch_Webservice("myDs");
//Parse returned xml
SAXParserImpl saxparser = new SAXParserImpl();
ByteArrayInputStream stream = new ByteArrayInputStream(wsReturnString.getBytes());
try {
saxparser.parse( stream, handler );
}
catch ( Exception e ) {
response.setText( "Unable to parse response.");
}
// now, update the UI back on the UI thread:
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
//Return vector sze from the handler class
int currentIndex = listUsers.getSelectedIndex();
int scrollPosition = getMainManager().getVerticalScroll();
//Return vector sze from the handler class
listUsers.setSize(handler.getItem().size());
listUsers.setSelectedIndex(currentIndex);
getMainManager().setVerticalScroll(scrollPosition);
}
});
}
}
public void drawListRow(ListField list, Graphics g, int index, int y, int w) {
String personToDraw = (String) this.get(list, index);
int drawColor = Color.RED;
g.setColor(drawColor);
g.drawText(personToDraw, 0, y, 0, w);
}
// get the selected index from the correct Vector
public Object get(ListField list, int index) {
return handler.getItem().elementAt(index);
}
public void insert(String toInsert, int index) {
handler.getItem().insertElementAt(toInsert, index);
}
public int getPreferredWidth(ListField list) {
return Display.getWidth();
}
public int indexOfList(ListField listField, String prefix, int start) {
return handler.getItem().indexOf(prefix, start);
}
}
public class ResponseHandler extends DefaultHandler
{
boolean username=false;
Vector _vectorUser = new Vector();
public void startElement(String uri, String localName, String qName, Attributes attributes){
if (qName.equalsIgnoreCase("U_Username")){
username = true;
}
}
public void characters(char[] ch, int start, int length) {
if (username){
_vectorUser.addElement(new String( ch, start, length ));
username=false;
}
}
Vector getItem(){
return _vectorUser;
}
}