2012-10-09 23 views
8

En mi aplicación, se adjuntan varios contactos al archivo .vcf y el archivo enviado al correo, intente mostrar todos los datos de los contactos en log cat, pero no puede enviar todos los datos adjuntos al archivo .vcf ?Android ¿Cómo se envían múltiples contactos se adjuntan en un único archivo .vcf y se envían al correo?

Alguien tiene una idea con respecto a esto ayúdeme, por favor.

aquí es mi código

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    vCard = new ArrayList<String>();     

    Log.i("TAG one", "vfile" +vfile); 
    vfile = "Contacts" + "_" + System.currentTimeMillis() + ".vcf"; 

    /** 
    * This Function For Vcard And here i take one Array List in Which i 
    * store every Vcard String of Every Contact Here i take one Cursor and 
    * this cursor is not null and its count>0 than i repeat one loop up to 
    * cursor.getcount() means Up to number of phone contacts. And in Every 
    * Loop i can make vcard string and store in Array list which i declared 
    * as a Global. And in Every Loop i move cursor next and print log in 
    * logcat. 
    * */ 
    getVcardString();   
}  

private void getVcardString() { 

    cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); 
    Log.i("TAG two", "cursor" +cursor); 
    if (cursor != null && cursor.getCount() > 0) { 
     cursor.moveToFirst(); 
     Log.i("Number of contacts", "cursorCount" +cursor.getCount());   

     for (int i = 0; i < cursor.getCount(); i++) {      
      get(cursor);      
      Log.i("TAG send contacts", "Contact " + (i + 1) + "VcF String is" + vCard.get(i));      
      cursor.moveToNext();           
     }   

     StringBuffer s = new StringBuffer(); 
     s.append(vCard.toString());     
     string = s.toString();       
     file = new File(string);   

    // Log.i("s", ""+s); 
    // Log.i("string", ""+string); 
     Log.i("file", ""+file);    

    } else { 
     Log.i("TAG", "No Contacts in Your Phone"); 
    }   
}  

public void get(Cursor cursor) { 

    String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); 
    Log.i("lookupKey", ""+lookupKey); 
    Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);  

    try { 
     AssetFileDescriptor fd = this.getContentResolver().openAssetFileDescriptor(uri, "r");   

     FileInputStream fis = fd.createInputStream(); 
     byte[] buf = new byte[(int) fd.getDeclaredLength()]; 
     fis.read(buf); 
     String vcardstring= new String(buf);   

     String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile; 
     FileOutputStream mFileOutputStream = new FileOutputStream(storage_path, true); 
     mFileOutputStream.write(vcardstring.toString().getBytes()); 

     vCard.add(storage_path);    

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

private void data() {  

    File filelocation = file;  
    Intent sharingIntent = new Intent(Intent.ACTION_SEND); 
    sharingIntent.setType("vnd.android.cursor.dir/email");  
    sharingIntent.setType("application/x-vcard");    
    sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+filelocation)); 
    startActivity(Intent.createChooser(sharingIntent, "Send email"));    
} 
}  

Respuesta

6

finalmente mi problema se resuelve utilizando como esto

 public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main);  

    mContext = this; 

    button = (Button) findViewById(R.id.send);   
    button.setOnClickListener(new OnClickListener() {   
     public void onClick(View v) {   
      data(); 
     } 
    });      

    /** 
    * This Function For Vcard And here i take one Array List in Which i 
    * store every Vcard String of Every Contact Here i take one Cursor and 
    * this cursor is not null and its count>0 than i repeat one loop up to 
    * cursor.getcount() means Up to number of phone contacts. And in Every 
    * Loop i can make vcard string and store in Array list which i declared 
    * as a Global. And in Every Loop i move cursor next and print log in 
    * logcat. 
    * */ 
    getVcardString();   
}  

public static void getVcardString() { 

    String path = null;  
    String vfile = null; 

    vfile = "Contacts.vcf";   
    Cursor phones = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, 
        null, null, null); 

    phones.moveToFirst(); 
    Log.i("Number of contacts", "cursorCount" +phones.getCount()); 
    for(int i =0;i<phones.getCount();i++) {  

     String lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); 
     Log.i("lookupKey", " " +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);   

      path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile; 
      FileOutputStream mFileOutputStream = new FileOutputStream(path, true); 
      mFileOutputStream.write(VCard.toString().getBytes());  

      phones.moveToNext();    

      filevcf = new File(path); 
      Log.i("file", "file" +filevcf); 

     }catch(Exception e1) { 
      e1.printStackTrace(); 
     } 
    }  
    Log.i("TAG", "No Contacts in Your Phone");   
} 

protected void data() {    
    File filelocation = filevcf ;  
    Intent sharingIntent = new Intent(Intent.ACTION_SEND); 
    sharingIntent.setType("vnd.android.cursor.dir/email");  
    sharingIntent.setType("application/x-vcard");  
    sharingIntent.putExtra(Intent.EXTRA_EMAIL, "[email protected]");   
    sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+filelocation.getAbsolutePath())); 
    startActivity(Intent.createChooser(sharingIntent, "Send email"));    
} 
+0

no veo dónde has estado inicializando 'filedata'. – BBdev

+0

@BBdev, ver el código de edición pequeño desajuste. – NagarjunaReddy

+0

me tropecé con esto, así que llegué aquí, había solucionado mi problema, pero pensé que para otros sería útil decírtelo :). Solo para una respuesta futura. Gracias – BBdev

2

He probado con éxito el siguiente. Los cambios en su código se indican con comentarios que comienzan con "CAMBIAR:". No olvides tener android.permission.WRITE_EXTERNAL_STORAGE en tu manifiesto.

public class MainActivity extends Activity { 
    private String vfile; 
    private Cursor cursor; 
    private ArrayList<String> vCard; 
    private String string; 
    private File file; 
    private String storage_path; //CHANGE: storage_path global 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     vCard = new ArrayList<String>();     

     Log.i("TAG one", "vfile" + vfile); 
     vfile = "Contacts" + "_" + System.currentTimeMillis() + ".vcf"; 

    /** 
    * This Function For Vcard And here i take one Array List in Which i 
    * store every Vcard String of Every Contact Here i take one Cursor and 
    * this cursor is not null and its count>0 than i repeat one loop up to 
    * cursor.getcount() means Up to number of phone contacts. And in Every 
    * Loop i can make vcard string and store in Array list which i declared 
    * as a Global. And in Every Loop i move cursor next and print log in 
    * logcat. 
    * */ 
     getVcardString();  
     data(); //CHANGE: now calling data to send vCard intent 
    } 

    private void getVcardString() { 

     cursor = getContentResolver(). 
     query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
     null, null, null, null); 
     Log.i("TAG two", "cursor" +cursor); 
     if (cursor != null && cursor.getCount() > 0) { 
     cursor.moveToFirst(); 
     Log.i("Number of contacts", "cursorCount" +cursor.getCount());   

     for (int i = 0; i < cursor.getCount(); i++) {      
      get(cursor);      
      Log.i("TAG send contacts", 
      "Contact " + (i + 1) + "VcF String is" + vCard.get(i));      
      cursor.moveToNext();           
     }   

//   StringBuffer s = new StringBuffer(); CHANGE: not needed 
//   s.append(vCard.toString());     
//   string = s.toString();       
//   file = new File(string); //CHANGE: this is not what file should be   

     } else { 
      Log.i("TAG", "No Contacts in Your Phone"); 
     }   
    }  

    public void get(Cursor cursor) { 

     String lookupKey =  cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); 
     Log.i("lookupKey", ""+lookupKey); 
     Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);  

     try { 
      AssetFileDescriptor fd = this.getContentResolver().openAssetFileDescriptor(uri, "r");   

      FileInputStream fis = fd.createInputStream(); 
      byte[] buf = new byte[(int) fd.getDeclaredLength()]; 
      fis.read(buf); 
      String vcardstring= new String(buf);  
      vCard.add(vcardstring); //CHANGE: added this, so log statement in above method doesn't generate error 

//   String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile; 
      //CHANGE: this is the path we need to get file for intent: 
      storage_path = getExternalFilesDir(null).toString() + File.separator + vfile;    
      Log.i("MainActivity", storage_path); 
      //CHANGE: this will create the file we need: 
      file = new File(getExternalFilesDir(null), vfile); 
      file.createNewFile(); //CHANGE 
      //CHANGE: this will create the stream we need: 
      FileOutputStream mFileOutputStream = new FileOutputStream(file, true); 
      mFileOutputStream.write(vcardstring.toString().getBytes()); 
      mFileOutputStream.close(); //don't forget to close 

    //   vCard.add(storage_path); //CHANGE: not needed   

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

    private void data() {  
    //  File filelocation = file; //CHANGE: not what we need  
     Intent sharingIntent = new Intent(Intent.ACTION_SEND); 
     sharingIntent.setType("vnd.android.cursor.dir/email");  
     sharingIntent.setType("application/x-vcard"); 
     //CHANGE: using correct path: 
     sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(storage_path)); 
     startActivity(Intent.createChooser(sharingIntent, "Send email"));    
    } 

} 
+0

no está funcionando enviar el archivo de correo es solamente 0k Gracias por la respuesta se resuelve mi problema actualizado mi respuesta pronto ..... Mi solución – NagarjunaReddy

+0

funciona para mí: cuando lo ejecuto, aparece una lista de aplicaciones para enviar por correo el archivo .vcf, y cuando selecciono una de las aplicaciones de la lista, se adjunta un archivo .vcf de 40 KB en el nuevo mensaje. Me envié el archivo con éxito y confirmé que mis contactos estaban en él. Me alegro de que tengas una solución, aunque lamento que la mía no haya funcionado para ti. Tengo curiosidad por saber dónde falló mi solución, si me proporcionas detalles. Gracias. – hBrent

+0

ver respuesta actualizada funciona bien .... – NagarjunaReddy

Cuestiones relacionadas