Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
773 views
in Technique[技术] by (71.8m points)

android - listview not updating with notifydatasetchanged() call

This is my code

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


    ArrayList<SClass> Monday = new ArrayList<SClass>();

    SClass s1=new SClass();
    s1.sName="samp";
    s1.salary=1000;
    Monday.add(s1);
    temp=Monday;
    adapter = new CustomAdap(this, temp);
    listview.setAdapter(adapter);

The above code works fine.But when i change my code to this

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


    adapter = new CustomAdap(this, temp);

    SClass s1=new SClass();
    s1.sName="samp";
    s1.salary=1000;
    Monday.add(s1);
    temp=Monday;

    listview.setAdapter(adapter);
    adapter.notifyDataSetChanged();

Listview does not show anything.what is the problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It looks like you're changing the collection that you initialized adapter with. I would change your code in this way:

// initial setup
listview =(ListView) findViewById(R.id.lv1);
ArrayList<SClass> Monday = new ArrayList<SClass>();
adapter = new CustomAdap(this, Monday);
listview.setAdapter(adapter);

// change your model Monday here, since it is what the adapter is observing
SClass s1=new SubjectClass();
s1.sName="samp";
s1.salary=1000;
Monday.add(s1);

// notify the list that the underlying model has changed
adapter.notifyDataSetChanged();

Note that if your CustomAdap was a subclass of ArrayAdapter, you could also have done

// change your array adapter here
SClass s1=new SubjectClass();
s1.sName="samp";
s1.salary=1000;
adapter.add(s1);

// notify the list that the underlying model has changed
adapter.notifyDataSetChanged();

EDIT: I understand more what you want to do now thanks to your comment. You'll probably want to have the adapter replace its contents with that your different ArrayLists then. I would make your CustomAdap be a subclass of ArrayAdapter.

Then you can utilize it this way:

// replace the array adapters contents with the ArrayList corresponding to the day
adapter.clear();
adapter.addAll(MONDAY);

// notify the list that the underlying model has changed
adapter.notifyDataSetChanged();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...