如何在Android中的.csv文件中逐行写入contactname和contactno?

发布于 2024-11-27 04:26:23 字数 2722 浏览 4 评论 0原文

我想从手机中获取联系人姓名和相应的联系人号码,并将其写入 .csv 文件中。每行将包含整个联系人列表中每个人的联系人姓名和联系电话号码。如何在.csv文件中写入联系信息?

我编写了用于显示联系人姓名列的代码,但它仅显示一个联系人,这意味着它会覆盖现有联系人,所以更改新联系人姓名的行应该是什么技巧。

我的代码

       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;

仅使用名称,“phoneno”是硬编码的。但在 .csv 文件中仅显示一个联系人

            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();
}

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();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

那支青花 2024-12-04 04:26:23

已编辑

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, "\n\nAdroid developer\n 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;
       }
}

这是 CSVWriter 类

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();
    }

}

并添加权限以体现为

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

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, "\n\nAdroid developer\n 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" />
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文