Anshuman Kaushik
Anshuman Kaushik

Reputation: 91

Not able to update listview items color in background

When i try to update my listview items colors as per my database. I am making an attendance app which allows teacher to mark present or absent.When they mark attendance a preference file automatically generated as per marked attendance and change color to red or green. This is not permanent thats y i have made an button which will check preference file which student is present or absent if he is present change his name into green color otherwise red its working perfectly. But problem is I want it automatically to check in background and dont want to press button all the time. Here is my button code which is working but i want it to do automatically in background...

public void check(View view) {


    //getting everything from table student
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy");
    String formattedDate = simpleDateFormat.format(new Date());

    SharedPreferences data = getSharedPreferences(latestBranch + "(" + latestSection + ") - " + formattedDate, MODE_PRIVATE);


    ArrayList<String> attend = new ArrayList<String>();

    //making loop to get all students from studentslist
    for (int x = 0; x < studentsList.size(); x++) {

        attend.add(data.getString(studentsList.get(x).toString(), ""));

    }

    for (int y = 0;y < studentsList.size(); y++) {

        if (attend.get(y).toString().equals("Present")) {

            listView.getChildAt(y).setBackgroundColor(Color.GREEN);

        } else if (attend.get(y).toString().equals("Absent")) {

            listView.getChildAt(y).setBackgroundColor(Color.RED);

        }


    }
}

Upvotes: 0

Views: 474

Answers (1)

nits.kk
nits.kk

Reputation: 5316

With ListView you need to write your custom Adapter for the list. Create a class extending the ArrayAdapter.java. Set the object of the custom adapter you create in the listView as its adapter.

Override the public View getView (int position, View convertView, ViewGroup parent)

This method is called when View of the list is being displayed. You can reuse the views by setting the state of the view [properties like text, color,enabled state, etc] for each position.

You associate the data (array of data ) with the adapter. When ever there is a change in the data array, call notifyDataSetInvalidated() on the object of the adapter.

In the getView method (As described above) for each position set the color as per the color in your data array for that position.

The code : listView.getChildAt(y) is based upon the visible items , for details refer to another question link below.

Sometimes listView.getChildAt(int index) returns NULL (Android)

For Custom adapter with overridden getView method, I suggest you to read about view-holder pattern in android.

Upvotes: 2

Related Questions