我使用的是 Android 2.1 平台,当我尝试检索联系人的电子邮件时,我的模拟器中有 7 个联系人,它将正常工作,但不是按照我保存在联系人列表中的顺序。如果我使用新电子邮件创建了一个新联系人,它会到最后。我正在使用这段代码。
代码
public class RetrieveData extends Activity {
ListView lvItem;
private Button btnAdd;
String displayName="", emailAddress="", phoneNumber="";
ArrayList<String> contactlist=new ArrayList<String>();
ArrayAdapter<String> itemAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lvItem = (ListView)this.findViewById(R.id.listview);
btnAdd = (Button)this.findViewById(R.id.btn);
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,contactlist);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GetEmails();
}
});
}
private void GetEmails()
{
ContentResolver cr =getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext())
{
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor emails = cr.query(Email.CONTENT_URI,null,Email.CONTACT_ID + " = " + id, null, null);
while (emails.moveToNext())
{
emailAddress = emails.getString(emails.getColumnIndex(Email.DATA));
contactlist.add(emailAddress);
itemAdapter.notifyDataSetChanged();
}
emails.close();
}
cursor.close();
}
}
xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/listview"
android:layout_width="fill_parent"
android:layout_height="288dp"
android:layout_weight="0.03" >
</ListView>
<Button
android:id="@+id/btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Retrieve"
android:layout_weight="0.01" />
</LinearLayout>
如何解决?