2014-07-23 10 views
1

Привет, ребята, у меня есть этот код, который я использую для получения контактов с телефона и сохранения их в формате vcf, код работает правильно для контактов, у которых есть только один номер, но я продолжаю получать дубликаты для контакты с несколькими номерами, то есть контакты, которые имеют домашний, рабочий номер etc..any помощь будет оценена ..... это мой код нижеКак удалить дубликаты контактов в файле vcf

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.util.ArrayList; 
import android.app.Activity; 
import android.content.Context; 
import android.content.res.AssetFileDescriptor; 
import android.database.Cursor; 
import android.net.Uri; 
import android.os.Bundle; 
import android.os.Environment; 
import android.provider.ContactsContract; 
import android.util.Log; 


    public class Show_contacts extends Activity { 
     Cursor cursor; 
     ArrayList<String> vCard; 
     String vfile; 
     static Context mContext; 

     /** Called when the activity is first created. */ 
     @Override 
      public void onCreate(Bundle savedInstanceState) { 
       super.onCreate(savedInstanceState); 
       setContentView(R.layout.activity_main); 
       mContext = Show_contacts.this; 
       getVCF(); 
      } 

      public static void getVCF() { 
       final String vfile = "Contacts.vcf"; 
       Cursor phones = mContext.getContentResolver().query(
       ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); 
       phones.moveToFirst(); 
       for (int i = 0; i < phones.getCount(); i++) { 
        String lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); 
        Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey); 
        AssetFileDescriptor fd; 
        try { 
         fd = mContext.getContentResolver().openAssetFileDescriptor(uri, "r"); 
         FileInputStream fis = fd.createInputStream(); 
         byte[] buf = new byte[(int) fd.getDeclaredLength()]; 
         fis.read(buf); 
         String VCard = new String(buf); 
         String path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile; 
         FileOutputStream mFileOutputStream = new FileOutputStream(path, true); 
         mFileOutputStream.write(VCard.toString().getBytes()); 
         phones.moveToNext(); 
         Log.d("Vcard", VCard); 
         mFileOutputStream.close(); 
        } catch (Exception e1) { 
         // TODO Auto-generated catch block 
         e1.printStackTrace(); 
        } 
       } 
      } 
     } 

ответ

1

Мы должны проверить LookupKey. Меня устраивает.

Cursor cursor; 
ArrayList<String> vCard; 
Context mContext; 
ArrayList<String> saveLkKey; 
String vcfFile; 
String currentTime; 
String rootStorage; 

@Override 
public View onCreateView(LayoutInflater inflater, 
     @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 

    View view = inflater.inflate(R.layout.save_contact_fragment, container, 
      false); 

    mContext = getActivity(); 
    rootStorage = Environment.getExternalStorageDirectory() + "/"; 

    Time today = new Time(Time.getCurrentTimezone()); 
    today.setToNow(); 

    currentTime = today.monthDay + "" + (today.month + 1) + "" + today.year 
      + "-" + today.format("%k%M%S") + ""; 

    vcfFile = "myContacts" + currentTime + ".vcf"; 


    Button btnSaveVcf = (Button) view.findViewById(R.id.btnSave1); 
    btnSaveVcf.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      getVCF(vcfFile); 

     } 

    }); 

return view; 
} 

public void getVCF(String vfile) { 

    Cursor phones = mContext.getContentResolver().query(
      ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, 
      null, null); 
    phones.moveToFirst(); 

    for (int i = 0; i < phones.getCount(); i++) { 
     String lookupKey = phones.getString(phones 
       .getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); 
     lookupKey = lookupKey.trim(); 

     if (saveLkKey == null) { 
      saveLkKey = new ArrayList<String>(); 
      saveLkKey.add(lookupKey); 
     } else { 
      if (isDuplicate(lookupKey)) { 

       phones.moveToNext(); 
       continue; 
      } else { 
       saveLkKey.add(lookupKey); 
      } 
     } 

     Uri uri = Uri.withAppendedPath(
       ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey); 
     AssetFileDescriptor fd; 
     try { 
      fd = mContext.getContentResolver().openAssetFileDescriptor(uri, 
        "r"); 
      FileInputStream fis = fd.createInputStream(); 
      byte[] buf = new byte[(int) fd.getDeclaredLength()]; 
      fis.read(buf); 
      String VCard = new String(buf); 
      String path = rootStorage + vfile; 

      FileOutputStream mFileOutputStream = new FileOutputStream(path, 
        true); 
      mFileOutputStream.write(VCard.toString().getBytes()); 
      phones.moveToNext(); 
      Log.d("Vcard", VCard); 
      mFileOutputStream.close(); 

     } catch (Exception e1) { 
      e1.printStackTrace(); 
     } 
    } 


} 

public boolean isDuplicate(String lkKey) { 
    for (String s : saveLkKey) { 
     if (s.equals(lkKey)) { 
      return true; 
     } 
    } 
    return false; 
} 
+0

только что вернул ответ на этот вопрос после 2 лет, к сожалению, я прекратил разработку Android. все равно спасибо за ответ :) – danidee

Смежные вопросы