我正在尝试将手机的所有联系人发送到我的服务器。 但是我在StringBuffer中附加了大量的联系人时出现内存不足的问题。所以请提出建议如何解决这个问题。附在我的代码块之下。
try{
userContactDetails = new StringBuffer();
Thread t1 = new Thread(new Runnable() {
public void run() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
StringBuffer singleUserDetail = new StringBuffer();
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// Create query to use CommonDataKinds classes to fetch emails
Cursor eCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = " + id, null, null);
StringBuffer phoneNos = new StringBuffer("");
String emailAddress = "";
if (Integer.parseInt(cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
phoneNos.append(pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))+PHONO_NO_SEPARATOR);
}
pCur.close();
}
while (eCur.moveToNext()) {
// This would allow you get several email addresses
emailAddress = eCur
.getString(eCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
//Log.i("SyncContacts", "Email=="+emailAddress);
}
eCur.close();
if(!phoneNos.toString().equals("")){ // phono not null
singleUserDetail.append(name);
singleUserDetail.append(CONTACT_ITEMS_SEPARATOR);
singleUserDetail.append(phoneNos.substring(0,phoneNos.length()-1));
}
if(phoneNos.toString().equals("") && !emailAddress.equals("")){ // phone no null and email not null
singleUserDetail.append(name);
singleUserDetail.append(CONTACT_ITEMS_SEPARATOR);
singleUserDetail.append(emailAddress);
}
if(!phoneNos.toString().equals("") && !emailAddress.equals("")){
singleUserDetail.append(CONTACT_ITEMS_SEPARATOR);
singleUserDetail.append(emailAddress);
}
if(!singleUserDetail.toString().equals("")){
userContactDetails.append(singleUserDetail);
userContactDetails.append(CONTACTS_SEPARATOR);
}
}
}
if(!userContactDetails.toString().equals("")) {
}
}
});
t1.start();
}catch(Exception e ){
e.printStackTrace();
Log.i("SyncContacts", "Server not called : " + e.toString());
}