the contactsList
is empty until the readContacts()
method was executed, in other words, when contactsView.setAdapter(adapter)
was executed, the contactsList
is empty, so why this code still can show contacts' info correctly?
public class MainActivity extends AppCompatActivity {
ListView contactsView;
ArrayAdapter<String> adapter;
List<String> contactsList = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactsView = (ListView) findViewById(R.id.contacts_list);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contactsList);
contactsView.setAdapter(adapter);
readContacts();
}
private void readContacts() {
Cursor cursor = null;
try {
cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
while (cursor.moveToNext()) {
String displayName = cursor.getString(cursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
));
String number = cursor.getString(cursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER
));
contactsList.add(displayName + "\n" + number);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}
but if i add something like this, i have to call notifyDataSetChanged()
:
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
contactsList.add("blabla");
adapter.notifyDataSetChanged();
}
});
add
is button.
now that the android would call the method automatically, why when remove the adapter.notifyDataSetChanged();
the UI couldn't refresh?
notifyDataSetChanged. Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.
If you are accessing it from outside scope, you can get it from the ListView object and cast it so you can call notifyDataSetChanged(). Like so: ServerItemAdapter listAdapter = (ServerItemAdapter) listView. getAdapter(); listAdapter.
Create your own class derived from BaseAdapter and ListAdapter that allows changing of the underlying List data structure. Use the notifyDataSetChanged() every time the list is updated. To call it on the UI-Thread, use the runOnUiThread() of Activity. Then, notifyDataSetChanged() will work.
notifyDataSetChanged tells the recycler view that every single item should be updated. However, its usually called when only 1 item has changed. Our RecyclerView. Adapter s should be changed to only notify that the changed items should be updated.
That method is called internally in the Android framework. You do not have to call it explicitly.
source: https://www.udacity.com/course/developing-android-apps--ud853
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With