Android Updating ListView

大兔子大兔子 提交于 2019-12-06 03:17:37

问题


I have looked at Android - how to update ListView item that is currently displayed and http://commonsware.com/Android/excerpt.pdf and the Android documentation but I still don't understand.

My problem:
Using a handler, I am trying to update a Stock data multi-column listview which I have populated from a webservice which retrieves data from a MySQL database. To update the listview, I am calling a servlet which returns an XML that I loop through using DOM.

I cannot find a working way to apply the new data (from the XML) into the Listview, though only the third column (Trade Column) has to be updated. Also when I try to cast a View from a ListView row, I get a NullPointerException and can't figure out why.

The code I have done so far is below.

java Code:

private void updateUI() throws Exception
{        
    Date dt = new Date();                 
    int hours = dt.getHours();
    int minutes = dt.getMinutes();                 
    int seconds = dt.getSeconds();                 
    String curTime = hours + ":" + minutes + ":"+ seconds;

    refreshHandler.sleep(60000);

    ListView listview = (ListView) findViewById(R.id.listview); 

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse("http://10.0.0.29:8080/CI3500/FTSEXML");

    //Filter and store ALL 'update' XML elements into node array
    NodeList nodeList = doc.getElementsByTagName("update");
    View v = null;
    TextView t = null;

    Adapter adapter = listview.getAdapter();

    for (int i = 0; i < adapter.getCount(); i++) 
    {
        v = listview.getChildAt(i);
        t = (TextView)v.findViewById(R.id.item2);

        String companyCode = t.getText().toString(); //Column 1

        for(int j = 0; j < nodeList.getLength(); j++) 
        {
            if(companyCode == nodeList.item(j).getFirstChild().getNodeValue())
            {
                //TODO Update Listview Code
            }
        }
    }       

    txtStatus.setText(String.valueOf("Last Update: " + curTime));
}

The listview mapping is as follows:

// create the grid item mapping
String[] columns = new String[] {"col_1", "col_2", "col_3" };
int[] rows = new int[] { R.id.CodeColumn, R.id.NameColumn, R.id.TradeColumn };

回答1:


You should implement you own ListView Adapter that will provide data to the list view. Calling notifyDataSetChanged() from adapter will force list view to fetch data from the adapter. Updating list view views directly looks strange.




回答2:


You can call invalidate to let the listview redraw.



来源:https://stackoverflow.com/questions/4486107/android-updating-listview

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