Search code examples
androidandroid-listview

Update TextView in ListView in real time


I am having a problem updating a TextView in real time. I want to update the TextView of a ListView with a custom adapter in real time. I have my socket I/O handler on which I receive a JSON message. I want to parse this JSON and put that text into the particular list row with setText(). How do I get the index of that ListView row and update its TextView?

responseid=object.getString("ResponseID");
if(responseid!=null){
    for(int j=0;j<countryList.size();j++){
        //If the countryList row match then i want to update the textView of that particular row
        if(countryList.get(j).getName().equals(caseid)) {                        
            int oldcount = Integer.parseInt((dataAdapter.findViewById(R.id.replycount)).getText().toString());
            int total=oldcount+1;
            (dataAdapter.findViewById(R.id.replycount)).setText(Integer.toString(total));
            dataAdapter.notifyDataSetChanged();
        }
    }    
}

Here is my solution:

for(int j=0;j<countryList.size();j++)
{
    if(countryList.get(j).getName().equals(caseid))
    {
        String oldcount = countryList.get(j).getCount();
        int oldcountint = Integer.parseInt(oldcount);
        int newcount = oldcountint + 1;
        countryList.get(j).setCount(Integer.toString(newcount));
        dataAdapter.notifyDataSetChanged();
        break;
    }
}

Solution

  • You should alter the items in your ListAdapter, and then call notifyDataSetChanged().

    Example:

    //Creating and adding ListAdapter to ListView
    MyObject myFirstObject = new MyObject("Test1");
    MyObject mySecondObject = new MyObject("Test2");
    
    MyAdapter myAdapter = new MyAdapter();
    myAdapter.add(myFirstObject);
    myAdapter.add(mySecondObject);
    myListView.setAdapter(myAdapter);
    

    When updating a particular position:

    myAdapter.getItem(position).text = "My updated text";
    myAdapter.notifyDataSetChanged();