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?