Android小程序实现访问联系人

时间:2022-07-26
本文章向大家介绍Android小程序实现访问联系人,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本文实例为大家分享了Android实现访问联系人的具体代码,供大家参考,具体内容如下

要求:

编写程序,使用ContentProvider实现访问联系人

ContentProvider类的作用:

ContentProvider(内容提供器)是所有应用程序之间数据存储和检索的一个桥梁,其作用是是各个应用程序之间能共享数据;主要功能是存储、检索数据并向应用程序提供访问数据的接口。

基本操作:

查询:使用ContentResolver的query()方法查询数据与 SQLite查询一样,返回一个指向结果集的游标Cursor。

插入:使用ContentResolver.insert()方法向ContentProvide中增加一个新的记录时,需要先将新纪录的数据封装到ContentValues对象中,然后调用ContentResolver.insert()方法将返回一个URI,该URI内容是由ContentProvider的URI加上该新纪录的扩展ID得到的,可以通过该URI对该记录做进一步的操作。

删除:如果要删除单个记录,可以调用ContentResolver.delete()方法,通过给该方法传递一个特定行的URI参数来实现删除操作。如果要对多行记录执行删除操作,就需要给delete()方法传递需要被删除的记录类型的URI以及一个where子句来实现多行删除。

更新:使用ContentResolver.update()方法实现记录的更新操作。

实现方案:

(1)CPActivity.java程序代码如下:

package com.example.contentprovider;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
import android.widget.TextView;

public class CPActivity extends Activity {

 Uri contact_uri = Contacts.CONTENT_URI;//联系人的URI

 //声明TextView的对象
 TextView textview;

 //定义文本颜色
 int textcolor = Color.BLACK;

 @Override
 protected void onCreate(Bundle savedInstanceState) {

 super.onCreate(savedInstanceState);

 //根据main.xml设置程序UI
 setContentView(R.layout.activity_cp);

 textview = (TextView)findViewById(R.id.textview);

 //调用getContactInfo()方法获取联系人信息
 String result = getContactInfo();

 //设置文本框的颜色
 textview.setTextColor(textcolor);

 //定义字体大小
 textview.setTextSize(20.0f);

 //设置文本框的文本
 textview.setText("记录t 名字n"+result); 
 }

 //getContactInfo()获取联系人列表的信息,返回String对象
 public String getContactInfo() {
 // TODO Auto-generated method stub
 String result = "";
 ContentResolver resolver = getContentResolver();
 Cursor cursor = resolver.query(contact_uri, null, null, null, null);

 //获取_ID字段索引
 int idIndex = cursor.getColumnIndex(Contacts._ID);

 //获取name字段的索引
 int nameIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME);

 //遍历Cursor提取数据
 cursor.moveToFirst();
 for(;!cursor.isAfterLast();cursor.moveToNext()){
 result = result+cursor.getString(idIndex)+"ttt";
 result = result+cursor.getString(nameIndex)+"tn";
 }

 //使用close方法关闭游标
 cursor.close();

 //返回结果
 return result;
 }
}

(2)Activity_cp.xml代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context="${relativePackage}.${activityClass}"  

 <TextView
 android:id="@+id/textview"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"/ 

</LinearLayout 

(3)其次必须在AndroidManifest.xml中添加如下权限:

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

(4)实现效果:

在联系人中添加几个联系人:

运行程序,手机里的所有联系人的ID及名字就会记录下来:

运行程序,手机里的所有联系人的ID及名字就会记录下来:

以上就是本文的全部内容,希望对大家的学习有所帮助。