如何写联系人姓名和contactno行方向在Android的.csv文件?如何写、姓名、联系人、方向

由网友(小伙肾不行,一切等于零)分享简介:我要带联系人姓名和对应的联系人没有来自移动,并希望把它写在的.csv 文件。每一行包含联系人姓名和每个人的整个联系人列表的联系号码。如何写联系人信息的.csv 文件?我写的code用于显示联系人姓名列,但只显示一个接触意味着它与现有的一个,这样应该是什么改变了一行新的联系人姓名的伎俩覆盖。我的code 公共类cont...

我要带联系人姓名和对应的联系人没有来自移动,并希望把它写在的.csv 文件。每一行包含联系人姓名和每个人的整个联系人列表的联系号码。如何写联系人信息的.csv 文件?

我写的code用于显示联系人姓名列,但只显示一个接触意味着它与现有的一个,这样应该是什么改变了一行新的联系人姓名的伎俩覆盖。

我的code

 公共类contactlist延伸活动{   静态字符串名称;   静态诠释计数;   静态INT countno;   静态文件的文件= NULL;  / **当第一次创建活动调用。 * /     @覆盖       公共无效的onCreate(捆绑savedInstanceState){    super.onCreate(savedInstanceState);    的setContentView(R.layout.main);    按钮filterbtn =(按钮)findViewById(R.id.button1);    filterbtn.setOnClickListener(新View.OnClickListener()    {    公共无效的onClick(视图v)    {        乌里U1 = Uri.fromFile(文件);        意图sendIntent =新意图(Intent.ACTION_SEND);         sendIntent.putExtra(Intent.EXTRA_SUBJECT,人详细信息);         sendIntent.putExtra(Intent.EXTRA_STREAM,U1);         sendIntent.setType(text / html的);         startActivity(sendIntent);       }   });    ContentResolver的CR = getContentResolver();    光标CUR = cr.query(ContactsContract.Contacts.CONTENT_URI,            NULL,NULL,NULL,NULL);    如果(cur.getCount()大于0){    而(cur.moveToNext()){        字符串ID = cur.getString(                    cur.getColumnIndex(ContactsContract.Contacts._ID));             名称= cur.getString(                        cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));          串columnString =PersonName的\PHONENO ;         字符串dataString = NULL; 

我只用名字和PHONENO难codeD。但在.csv文件中只有一个联系人显示

  dataString =+名字+,+PHONENO+;         字符串combinedString = columnString + n+ dataString;         文件根= Environment.getExternalStorageDirectory();         如果(root.canWrite()){             文件DIR =新的文件(root.getAbsolutePath()+/ PersonData);              dir.mkdirs();               文件=新的文件(目录Data.csv);              FileOutputStream中走出= NULL;             尝试{                 OUT =新的FileOutputStream(文件);                 }赶上(FileNotFoundException异常五){                     e.printStackTrace();                 }                 尝试{                     out.write(combinedString.getBytes());                 }赶上(IOException异常五){                     e.printStackTrace();                 }                 尝试{                     out.close();                 }赶上(IOException异常五){                     e.printStackTrace();                 }             }        }}    cur.close();} 

解决方案 怎么将手机里联系人的姓名号码等信息打印出来

的 编辑的

 进口的java.io.File;进口java.io.FileWriter;进口java.io.IOException异常;进口android.app.Activity;进口android.content.Intent;进口android.database.Cursor;进口android.net.Uri;进口android.os.Bundle;进口android.os.Environment;进口android.provider.ContactsContract;进口android.provider.ContactsContract.CommonDataKinds.Phone;进口android.util.Log;进口android.widget.Toast;/ ** * @author潘卡 * * /公共类CsvSender延伸活动{    私人光标指针;    私人布尔csv_status = FALSE;    @覆盖    公共无效的onCreate(捆绑savedInstanceState){        super.onCreate(savedInstanceState);        的setContentView(R.layout.main);        createCSV();        exportCSV();    }    私人无效createCSV(){        CSVWriter作家=无效;        尝试{            作家=新CSVWriter(新的FileWriter(Environment.getExternalStorageDirectory()getAbsolutePath()+/my_test_contact.csv)。);        }赶上(IOException异常E1){            // TODO自动生成catch块            e1.printStackTrace();        }        字符串显示名;        串号;        长_id;        字符串列[] =新的String [] {ContactsContract.Contacts._ID,                   ContactsContract.Contacts.DISPLAY_NAME};        writer.writeColumnNames(); //写列标题        光标光标= getContentResolver()查询(ContactsContract.Contacts.CONTENT_URI,                   列,                   空值,                   空值,                   ContactsContract.Data.DISPLAY_NAME +分页中局部ASC);        startManagingCursor(光标);       如果(cursor.moveToFirst()){           做{               _id =的Long.parseLong(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)));               显示名= cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))修剪()。               数= getPrimaryNumber(_id);               writer.writeNext((显示名+/+号).split(/));           }而(cursor.moveToNext());           csv_status = TRUE;       }其他{           csv_status = FALSE;       }       尝试{            如果(作家!= NULL)                writer.close();        }赶上(IOException异常五){           Log.w(测试,e.toString());        }   } // close方法。   私人无效exportCSV(){       如果(csv_status ==真){           // CSV文件被创建,所以我们需要导出...            最终文件CSVFile =新的文件(Environment.getExternalStorageDirectory()getAbsolutePath()+/my_test_contact.csv);            //Log.i("SEND EMAIL测试,发送Email);            意图emailIntent =新意图(android.content.Intent.ACTION_SEND);            emailIntent.setType(文/ CSV);            emailIntent .putExtra(android.content.Intent.EXTRA_SUBJECT,测试人脉);            emailIntent .putExtra(android.content.Intent.EXTRA_TEXT, n  nAdroid开发商 n潘卡);            emailIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse(文件://+ CSVFile.getAbsolutePath()));            emailIntent.setType(信息/ RFC822); //可见,支持SEND活动的所有应用程序            尝试{                startActivity(Intent.createChooser(emailIntent,发送邮件...));            }赶上(android.content.ActivityNotFoundException前){                Toast.makeText(getApplicationContext()的电子邮件客户端:+ ex.toString(),Toast.LENGTH_SHORT);            }        }其他{            Toast.makeText(getApplicationContext(),不可用于创建CSV信息,Toast.LENGTH_SHORT).show();        }   }       / **        *获取请求ID的主号码。        *        *主号码的@返回字符串值。        * /       私人字符串getPrimaryNumber(长_id){           字符串primaryNumber = NULL;           尝试{               光标光标= getContentResolver()查询(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,                       新的String [] {Phone.NUMBER,Phone.TYPE},                       ContactsContract.CommonDataKinds.Phone.CONTACT_ID +=+ _id,//我们需要增加更多的选择为手机类型                       空值,                       空值);               如果(指针!= NULL){                   而(cursor.moveToNext()){                       开关(cursor.getInt(cursor.getColumnIndex(Phone.TYPE))){                           案例Phone.TYPE_MOBILE:                               primaryNumber = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));                               打破;                           案例Phone.TYPE_HOME:                               primaryNumber = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));                               打破;                           案例Phone.TYPE_WORK:                               primaryNumber = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));                               打破;                           案例Phone.TYPE_OTHER:                       }                       如果(primaryNumber!= NULL)                           打破;                   }               }           }赶上(例外五){               Log.i(测试,异常+ e.toString());           } {最后               如果(指针!= NULL){                   cursor.deactivate();                   cursor.close();               }           }           返回primaryNumber;       }} 

这是CSVWriter类

 进口java.io.IOException异常;进口的java.io.PrintWriter;进口的java.io.Writer;/ ** * @author潘卡 * * /公共类CSVWriter {    私人PrintWriter的PW;    私人字符分隔符;    私人焦炭quotechar;    私人焦炭escapechar;    私人字符串lineEnd;    / **用于转义引号的字符。 * /    公共静态最后的char DEFAULT_ESCAPE_CHARACTER ='';    / **如果没有提供构造函数的默认分隔符使用。 * /    公共静态最后的char DEFAULT_SEPARATOR ='';    / **     *如果没有提供给默认引号字符使用     *构造函数。     * /    公共静态最后的char DEFAULT_QUOTE_CHARACTER ='';    / **当你想用晚餐preSS所有引述报价不变使用。 * /    公共静态最后的char NO_QUOTE_CHARACTER =' u0000的';    / **当你想用晚餐preSS都逃脱越狱不断使用。 * /    公共静态最后的char NO_ESCAPE_CHARACTER =' u0000的';    / **默认的行终止使用平台编码。 * /    公共静态最后弦乐DEFAULT_LINE_END = n;    / **默认列名。 * /    公共静态最后弦乐DEFAULT_COLUMN_NAME =联系人姓名,电话号码,    / **     *构造CSVWriter使用分隔逗号。     *     * @参数作家     *笔者到​​底层CSV来源。     * /    公共CSVWriter(作家作家){        这个(作家,DEFAULT_SEPARATOR,DEFAULT_QUOTE_CHARACTER,            DEFAULT_ESCAPE_CHARACTER,DEFAULT_LINE_END);    }    / **     *构造CSVWriter与提供的分隔符,引号字符,逃离char和行结束。     *     * @参数作家     *笔者到​​底层CSV来源。     * @参数分离器     *分隔符用于分隔条目     * @参数quotechar     *字符用于引用元素     * @参数escapechar     *字符使用转义quotechars或escapechars     * @参数lineEnd     *换行终止使用     * /    公共CSVWriter(作家作家,字符分隔,字符quotechar,焦炭escapechar,弦乐lineEnd){        this.pw =的新PrintWriter(作家);        this.separator =分隔符;        this.quotechar = quotechar;        this.escapechar = escapechar;        this.lineEnd = lineEnd;    }    / **     *写入下一行到文件。     *     * @参数nextLine     *一个字符串数组,每个逗号分隔的元素作为一个独立的     *条目。     * /    公共无效writeNext(字符串[] nextLine){        如果(nextLine == NULL)                返回;        StringBuffer的SB =新的StringBuffer();        的for(int i = 0; I< nextLine.length;我++){            如果(ⅰ!= 0){                sb.append(分隔符);            }            字符串nextElement = nextLine [I]            如果(nextElement == NULL)                继续;            如果(quotechar!= NO_QUOTE_CHARACTER)                sb.append(quotechar);            对于(INT J = 0; J< nextElement.length(); J ++){                焦炭nextChar = nextElement.charAt(J);                如果(escapechar = NO_ESCAPE_CHARACTER和放大器;!&安培; nextChar == quotechar){                        sb.append(escapechar).append(nextChar);                }否则如果(escapechar = NO_ESCAPE_CHARACTER和放大器;!&安培; nextChar == escapechar){                        sb.append(escapechar).append(nextChar);                }其他{                    sb.append(nextChar);                }            }            如果(quotechar!= NO_QUOTE_CHARACTER)                sb.append(quotechar);        }        sb.append(lineEnd);        pw.write(sb.toString());    }    公共无效writeColumnNames(){        writeNext(DEFAULT_COLUMN_NAME.split(,));    }    / **     *冲洗底层流作家。     *     *引发IOException如果不好的事情发生     * /    公共无效的flush()抛出IOException        pw.flush();    }    / **     *关闭底层流作家刷新任何缓冲的内容。     *     *引发IOException如果不好的事情发生     *     * /    公共无效的close()抛出IOException        pw.flush();        pw.close();    }} 

和添加权限,表现为

 <使用许可权的android:NAME =android.permission.READ_CONTACTS/><使用许可权的android:NAME =android.permission.WRITE_EXTERNAL_STORAG​​E/> 

I want to take contactname and corresponding contact no from mobile and want to write it in .csv file. Each row will contains contact name and contact number of each person for the entire contact list. How to write contact information in .csv file?

I write the code for showing contactname column but it display only one contact means its override with existing one so what should be the trick for changing the row for new contact name.

My code

       public class contactlist extends Activity {
   static  String name;
   static int count;
   static int countno;
   static File file = null ;

  /** Called when the activity is first created. */
     @Override
       public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button filterbtn = (Button)findViewById(R.id.button1);
    filterbtn.setOnClickListener(new View.OnClickListener()
    {
    public void onClick(View v)
    {


        Uri u1  =   Uri.fromFile(file);
        Intent sendIntent = new Intent(Intent.ACTION_SEND);
         sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Person Details");
         sendIntent.putExtra(Intent.EXTRA_STREAM, u1);
         sendIntent.setType("text/html");
         startActivity(sendIntent);


       }
   });

    ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null, null, null, null);
    if (cur.getCount() > 0) {
    while (cur.moveToNext()) {
        String id = cur.getString(
                    cur.getColumnIndex(ContactsContract.Contacts._ID));

             name = cur.getString(
                        cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));





          String columnString =   ""PersonName","phoneno"";
         String dataString = null;

I use only name and "phoneno" is hardcoded. But in .csv file only one contact is shown

            dataString   =   """ + name +"","" + "phoneno" + """;    


         String combinedString = columnString + "n" + dataString;

         File root   = Environment.getExternalStorageDirectory();
         if (root.canWrite()){
             File dir    =   new File (root.getAbsolutePath() + "/PersonData");
              dir.mkdirs();
               file   =   new File(dir, "Data.csv");
              FileOutputStream out   =   null;
             try {
                 out = new FileOutputStream(file);
                 } catch (FileNotFoundException e) {
                     e.printStackTrace();
                 }
                 try {
                     out.write(combinedString.getBytes());
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
                 try {
                     out.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }



        }



}
    cur.close();
}

解决方案

Edited.

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.widget.Toast;

/**
 * @author Pankaj
 *
 */
public class CsvSender extends Activity {

    private Cursor cursor;
    private boolean csv_status = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        createCSV();
        exportCSV();

    }

    private void createCSV() {
        CSVWriter writer = null;
        try {
            writer = new CSVWriter(new FileWriter(Environment.getExternalStorageDirectory().getAbsolutePath() + "/my_test_contact.csv"));
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        String displayName;
        String number;
        long _id;
        String columns[] = new String[]{ ContactsContract.Contacts._ID,
                   ContactsContract.Contacts.DISPLAY_NAME };
        writer.writeColumnNames(); // Write column header
        Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
                   columns,                
                   null,               
                   null,               
                   ContactsContract.Data.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
        startManagingCursor(cursor);
       if(cursor.moveToFirst()) {  
           do {
               _id = Long.parseLong(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)));   
               displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)).trim();
               number = getPrimaryNumber(_id);
               writer.writeNext((displayName + "/" + number).split("/"));
           } while(cursor.moveToNext());   
           csv_status = true;
       } else {
           csv_status = false;
       }
       try {
            if(writer != null)
                writer.close();
        } catch (IOException e) {
           Log.w("Test", e.toString());
        }

   }// Method  close.  


   private void exportCSV() {
       if(csv_status == true) {
           //CSV file is created so we need to Export that ...
            final File CSVFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/my_test_contact.csv");
            //Log.i("SEND EMAIL TESTING", "Email sending");
            Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
            emailIntent.setType("text/csv");
            emailIntent .putExtra(android.content.Intent.EXTRA_SUBJECT, "Test contacts ");           
            emailIntent .putExtra(android.content.Intent.EXTRA_TEXT, "nnAdroid developern Pankaj");
            emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + CSVFile.getAbsolutePath()));
            emailIntent.setType("message/rfc822"); // Shows all application that supports SEND activity 
            try {
                startActivity(Intent.createChooser(emailIntent, "Send mail..."));
            } catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(getApplicationContext(), "Email client : " + ex.toString(), Toast.LENGTH_SHORT);
            }
        } else {
            Toast.makeText(getApplicationContext(), "Information not available to create CSV.", Toast.LENGTH_SHORT).show();
        }
   }
       /**
        * Get primary Number of requested  id.
        * 
        * @return string value of primary number.
        */
       private String getPrimaryNumber(long _id) {
           String primaryNumber = null;
           try {
               Cursor cursor = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                       new String[]{Phone.NUMBER, Phone.TYPE},
                       ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ _id, // We need to add more selection for phone type
                       null,
                       null);
               if(cursor != null) {
                   while(cursor.moveToNext()){
                       switch(cursor.getInt(cursor.getColumnIndex(Phone.TYPE))){
                           case Phone.TYPE_MOBILE :
                               primaryNumber = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
                               break;
                           case Phone.TYPE_HOME :
                               primaryNumber = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
                               break;
                           case Phone.TYPE_WORK :
                               primaryNumber = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
                               break;
                           case Phone.TYPE_OTHER :
                       }
                       if(primaryNumber != null)
                           break;
                   }
               }       
           } catch (Exception e) {
               Log.i("test", "Exception " + e.toString());
           } finally {
               if(cursor != null) {
                   cursor.deactivate();
                   cursor.close();             
               }
           }
           return primaryNumber;
       }
}

And here is CSVWriter class

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;

/**
 * @author Pankaj
 *
 */
public class CSVWriter {

    private PrintWriter pw;
    private char separator;
    private char quotechar;
    private char escapechar;
    private String lineEnd;

    /** The character used for escaping quotes. */
    public static final char DEFAULT_ESCAPE_CHARACTER = '"';

    /** The default separator to use if none is supplied to the constructor. */
    public static final char DEFAULT_SEPARATOR = ',';

    /**
     * The default quote character to use if none is supplied to the
     * constructor.
     */
    public static final char DEFAULT_QUOTE_CHARACTER = '"';

    /** The quote constant to use when you wish to suppress all quoting. */
    public static final char NO_QUOTE_CHARACTER = 'u0000';

    /** The escape constant to use when you wish to suppress all escaping. */
    public static final char NO_ESCAPE_CHARACTER = 'u0000';

    /** Default line terminator uses platform encoding. */
    public static final String DEFAULT_LINE_END = "n";

    /** Default column name. */
    public static final String DEFAULT_COLUMN_NAME = "Contact Name,Phone Number,";

    /**
     * Constructs CSVWriter using a comma for the separator.
     *
     * @param writer
     *            the writer to an underlying CSV source.
     */
    public CSVWriter(Writer writer) {
        this(writer, DEFAULT_SEPARATOR, DEFAULT_QUOTE_CHARACTER,
            DEFAULT_ESCAPE_CHARACTER, DEFAULT_LINE_END);
    }

    /**
     * Constructs CSVWriter with supplied separator, quote char, escape char and line ending.
     *
     * @param writer
     *            the writer to an underlying CSV source.
     * @param separator
     *            the delimiter to use for separating entries
     * @param quotechar
     *            the character to use for quoted elements
     * @param escapechar
     *            the character to use for escaping quotechars or escapechars
     * @param lineEnd
     *                    the line feed terminator to use
     */
    public CSVWriter(Writer writer, char separator, char quotechar, char escapechar, String lineEnd) {
        this.pw = new PrintWriter(writer);
        this.separator = separator;
        this.quotechar = quotechar;
        this.escapechar = escapechar;
        this.lineEnd = lineEnd;
    }

    /**
     * Writes the next line to the file.
     *
     * @param nextLine
     *            a string array with each comma-separated element as a separate
     *            entry.
     */
    public void writeNext(String[] nextLine) {

        if (nextLine == null)
                return;

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < nextLine.length; i++) {

            if (i != 0) {
                sb.append(separator);
            }

            String nextElement = nextLine[i];
            if (nextElement == null)
                continue;
            if (quotechar !=  NO_QUOTE_CHARACTER)
                sb.append(quotechar);
            for (int j = 0; j < nextElement.length(); j++) {
                char nextChar = nextElement.charAt(j);
                if (escapechar != NO_ESCAPE_CHARACTER && nextChar == quotechar) {
                        sb.append(escapechar).append(nextChar);
                } else if (escapechar != NO_ESCAPE_CHARACTER && nextChar == escapechar) {
                        sb.append(escapechar).append(nextChar);
                } else {
                    sb.append(nextChar);
                }
            }
            if (quotechar != NO_QUOTE_CHARACTER)
                sb.append(quotechar);
        }

        sb.append(lineEnd);
        pw.write(sb.toString());

    }

    public void writeColumnNames() {
        writeNext(DEFAULT_COLUMN_NAME.split(","));
    }

    /**
     * Flush underlying stream to writer.
     *
     * @throws IOException if bad things happen
     */
    public void flush() throws IOException {
        pw.flush();
    }

    /**
     * Close the underlying stream writer flushing any buffered content.
     *
     * @throws IOException if bad things happen
     *
     */
    public void close() throws IOException {
        pw.flush();
        pw.close();
    }

}

And add permissions to manifest as

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

阅读全文

相关推荐

最新文章