编辑.

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

}

}

并将清单的权限添加为

android contacts 编辑,如何在Android中的.csv文件中逐行编写contactn...相关推荐

  1. java中iterator_如何在Java中读取CSV文件-Iterator和Decorator的案例研究

    java中iterator 在本文中,我将讨论如何使用Apache Common CSV读取CSV(逗号分隔值)文件. 从这个案例研究中,我们将学习如何在设计模式的上下文中使用Iterator和Dec ...

  2. 如何在Java中读取CSV文件-Iterator和Decorator的案例研究

    在本文中,我将讨论如何使用Apache Common CSV读取CSV(逗号分隔值)文件. 从这个案例研究中,我们将学习如何在设计模式的上下文中使用Iterator和Decorator来提高不同情况下 ...

  3. android在java下建立模块,Android Studio:如何在Android模块中包含Java模块?

    在Android工作室我有一个Android模块,我们称之为MyAndroid.我还有一个Java模块(不是独立的JAR,而是模块中的完整Java项目),我们称之为MyJava.Android Stu ...

  4. android 禁用触摸屏,如何在Android手机中禁用触摸屏?

    编辑 您可以通过实现ListView控件的自定义扩展已设为列表中的XML文件中使用做到这一点.然后在你的CustomListView中,实现onTouchEvent方法,如果你想让列表处理触摸,只调用 ...

  5. android怎么查看方法被谁调用,Android中查看布局文件中的控件(view,id)在哪里被调用(使用)...

    在阅读别人的代码时通常是很痛苦的,有时很想要看一看布局中的控件在哪里被调用了,为之很苦恼 在这里提供一种方法. 复制要查看的控件ID,到R文件中搜索到该ID, 接下来就好办的了,选中ID按下Ctrl鼠 ...

  6. html img调用js,html调用js变量 如何在html中输出js文件中的变量

    html页面代码中怎么调用js变量?html页面代码中怎么调用js变量,例如 在html代码中插入js代码: a=取浏览你把index1.js 中的onReady 去掉,把index1.js改成 fu ...

  7. vscode中如何创新建php文件,php – 如何在Visual Studio Code,UNIX中的所有文件中创建所有行结尾(EOL)?...

    我使用Windows 10 home,我通常使用Visual Studio Code(VSCODE)来编辑Linux Bash脚本以及PHP和JavaScript. 我没有开发任何专门用于Window ...

  8. python爬取微博数据存入数据库_Python爬取新浪微博评论数据,写入csv文件中

    因为新浪微博网页版爬虫比较困难,故采取用手机网页端爬取的方式 操作步骤如下: 1. 网页版登陆新浪微博 2.打开m.weibo.cn 3.查找自己感兴趣的话题,获取对应的数据接口链接 4.获取cook ...

  9. 向oracle中导入*.csv文件

    向oracle中导入*.csv文件 1.什么是*.csv,如何得到? 里面存放的是数据表.每行代表数据库表格的一行, 每行中,每两个数据中间由逗号","分割. *.csv可以通过& ...

最新文章

  1. 服务器返回数据为空,iOS 处理服务器返回数据中的null
  2. vue就地复用不是更快吗_Vue.js从零开始——组件(1)
  3. 134. 加油站(贪心算法)
  4. 读取配置文件失败_还在为Find_Package失败而烦恼吗?
  5. python新闻评论分析_从新闻文章中提取评论
  6. QStackedWidget实现自适应紧凑布局
  7. Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration.
  8. java 上下文加载器_【深入理解Java虚拟机 】线程的上下文类加载器
  9. 谈谈asp.net中的% %,%= %,%# %%$ %的使用
  10. 学习笔记--asp.net主题和外观(转自msdn,仅为自己学习存储和有意读者使用)
  11. 数据可视化系统在哪些行业中应用
  12. 一位算法工程师从30+场秋招面试中总结出的超强面经—文本检测与GAN篇(含答案)...
  13. mybatis关于factorybean疑问
  14. 一次防火墙无法重启的排查过程和总结
  15. 张正友相机标定法--相机去畸变(C++)
  16. c#实现的破解程序--针对软件使用时间限制
  17. Axure 8 团队协作
  18. KNEEL: Knee Anatomical Landmark Localization Using Hourglass Networks
  19. python获取交换机信息
  20. 劲牌连续两年问鼎全国质量大奖背后的密码

热门文章

  1. PyTorch框架学习十六——正则化与Dropout
  2. C++模板的一些基础知识
  3. C++学习之路 | PTA乙级—— 1083 是否存在相等的差 (20 分)(精简)
  4. C++学习之路 | PTA乙级—— 1019 数字黑洞 (20分)(精简)
  5. php return 值_php return的用法是什么
  6. jsp解决mysql乱码_解决mysql+jsp出现乱码的问题
  7. r语言 柱状图加星号_R语言绘制带有显著性字母标记的柱状图
  8. 外设驱动库开发笔记3:AD527x系列数字电位器驱动
  9. arm64动态链接库通过函数名获取函数偏移
  10. python 硬件模拟_如何编写一个硬件模拟器?