可以实现添加联系人,删除联系人,修改联系人,查找号码,查询联系人信息等功能。
具体实现界面如图所示。
相关代码介绍如下:
Android项目配置AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.demo.pr3"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:maxSdkVersion="8"/>
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<application
android:icon="@drawable/icon"
android:label="@string/app_name">
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--增加号码录入Activity-->
<activity
android:name=".AddContactsActivity">
</activity>
<!--修改号码录入Activity-->
<activity
android:name=".UpdateContactsActivity">
</activity>
<!--查询号码录入Activity-->
<activity
android:name=".ContactsMessageActivity">
</activity>
<!--添加导出手机电话簿所需权限-->
</application>
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
</manifest>
手机通讯录程序主界面类MyContactsActivity.java
package com.demo.pr3;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.*;
import android.provider.ContactsContract.Contacts.Data;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.demo.pr3.datax.ContactsTable;
import com.demo.pr3.datax.User;
/********************(C)COPYRIGHT 2012********************
*主界面
************************************************************/
public class MainActivity extends Activity {
private ListView listView; //显示结果列表
private BaseAdapter listViewAdapter; //ListView 列表适配器
private User users[];//通讯录用户
private int selecteItem=0; //当前选择的数据项
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setTitle("通讯录");
listView =(ListView)findViewById(R.id.listView);
loadContacts();
}
/**
* 加载联系人列表
*/
private void loadContacts()
{
//获取所有通讯录联系人
ContactsTable ct=new ContactsTable(this);
users=ct.getAllUser();
//为 listView 列表创建适配器
listViewAdapter=new BaseAdapter() {
@Override
public View getView(int position,View convertView,ViewGroup parent){
if(convertView==null)
{
TextView textView=new TextView(MainActivity.this);
textView.setTextSize(22);
convertView=textView;
}
String moblie=users[position].getMoblie()==null?""
:users[position].getMoblie();
((TextView)convertView).setText(users[position]
.getName()+"---"+moblie);
if(position==selecteItem)
{
convertView.setBackgroundColor(Color.YELLOW);
}else
{
convertView.setBackgroundColor(0);
}
return convertView;
}
@Override
public long getItemId(int position){
return position;
}
@Override
public Object getItem(int position){
return users[position];
}
@Override
public int getCount() {
return users.length;
}
};
//设置 listView 控件的适配器
listView.setAdapter(listViewAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0,View arg1,int arg2,long arg3){
selecteItem=arg2; //记录单击列的位置
listViewAdapter.notifyDataSetChanged();//刷新列表
}
});
}
/**
* 创建菜单
*/
public boolean onCreateOptionsMenu(Menu menu){
menu.add(Menu.NONE,1,Menu.NONE,"添加");
menu.add(Menu.NONE,2,Menu.NONE,"编辑");
menu.add(Menu.NONE,3,Menu.NONE,"查看信息");
menu.add(Menu.NONE,4,Menu.NONE,"删除");
menu.add(Menu.NONE,5,Menu.NONE,"查询");
menu.add(Menu.NONE,6,Menu.NONE,"导入到手机电话簿");
menu.add(Menu.NONE,7,Menu.NONE,"退出");
return super.onCreateOptionsMenu(menu);
}
/**
* 菜单事件
*/
public boolean onOptionsItemSelected(MenuItem item){
String sHint;
switch(item.getItemId()){
case 1://添加
Intent intent=new Intent(MainActivity.this, AddContactsActivity.class);
startActivity(intent);
break;
case 2://编辑
//根据数据库ID判断当前记录是否可以操作
if(users[selecteItem].getId_DB()>0){
intent=new Intent(MainActivity.this, UpdateContactsActivity.class);
intent.putExtra("user_ID",users[selecteItem].getId_DB());
startActivity(intent);
}else{
sHint="无结果记录,无法操作!";
Toast.makeText(this,sHint, Toast.LENGTH_SHORT).show();
}
break;
case 3://查看信息
if(users[selecteItem].getId_DB()>0)
{
intent=new Intent(MainActivity.this, ContactsMessageActivity.class);
intent.putExtra("user_ID",users[selecteItem].getId_DB());
startActivity(intent);
}else
{
sHint="无结果记录,无法操作!";
Toast.makeText(this, sHint , Toast.LENGTH_SHORT).show();
}
break;
case 4://删除
if(users[selecteItem].getId_DB()>0)
{
delete();
}else
{
sHint="无结果记录,无法操作!";
Toast.makeText(this,sHint,Toast.LENGTH_SHORT).show();
}
break;
case 5://查询
new FindDialog(this).show();
break;
case 6://导入到手机电话簿
if(users[selecteItem].getId_DB()>0)
{
importPhone(users[selecteItem].getName(),
users[selecteItem].getMoblie());
sHint="已经成功导入‘"+users[selecteItem].getName()+"’导入到手机电话簿!";
Toast.makeText(this, sHint , Toast.LENGTH_SHORT).show();
}else
{
sHint="无结果记录,无法操作!";
Toast.makeText(this, sHint, Toast.LENGTH_SHORT).show();
}
break;
case 7://退出
finish();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
//重新加载数据
ContactsTable ct=new ContactsTable(this);
users=ct.getAllUser();
//刷新数据显示列表
listViewAdapter.notifyDataSetChanged();
}
/**
* 查询
*/
public class FindDialog extends Dialog{
public FindDialog(Context context){
super(context);
}
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.find);
setTitle("联系人查询");
Button find=(Button)findViewById(R.id.find);
Button cancel=(Button)findViewById(R.id.cancel);
find.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
EditText value=(EditText)findViewById(R.id.value);
ContactsTable ct=new
ContactsTable(MainActivity.this);
users=ct.findUserByKey(value.getText().toString());
for(int i=0;i<users.length;i++)
{
System.out.println("姓名是"+users[i].getName()+
",电话是" +users[i].getMoblie());
}
listViewAdapter.notifyDataSetChanged();
selecteItem=0;
dismiss();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
dismiss();
}
});
}
}
/**
* 删除联系人
*/
public void delete()
{
Builder alert=new AlertDialog.Builder(this);
alert.setTitle("系统信息");
alert.setMessage("是否删除联系人?");
alert.setPositiveButton("是",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int whichButton){
ContactsTable ct=new ContactsTable(MainActivity.this);
//删除联系人信息
if(ct.deleteByUser(users[selecteItem]))
{
//重新获取数据
users=ct.getAllUser();
//刷新列表
listViewAdapter.notifyDataSetChanged();
selecteItem=0;
Toast.makeText(MainActivity.this," 删 除 成 功 ! ",Toast.LENGTH_SHORT).
show();
}else
{
Toast.makeText(MainActivity.this," 删 除 失 败 ! ",Toast.LENGTH_SHORT).
show();
}
}
});
alert.setNegativeButton("否",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int whichButton)
{
}
});
alert.show();
}
///导入到手机电话簿
public void importPhone(String name,String phone)
{
//系统通讯录ContentProvider 的 URI
Uri phoneURL=android.provider.ContactsContract.Data.CONTENT_URI;
ContentValues values=new ContentValues();
//首先向RawContacts.CONTENT_URI执行一个空值插入,目的是获取系统返回的rawContactId
Uri rawContactUri=this.getContentResolver().
insert(RawContacts.CONTENT_URI,values);
long rawContactId=ContentUris.parseId(rawContactUri);
//向 data 表插入姓名
values.clear();
values.put(Data.RAW_CONTACT_ID,rawContactId);
values.put(Data.MIMETYPE,StructuredName.CONTENT_ITEM_TYPE);
values.put(StructuredName.GIVEN_NAME,name);
this.getContentResolver().insert(phoneURL,values);
//向 data 表插入电话号码
values.clear();
values.put(Data.RAW_CONTACT_ID,rawContactId);
values.put(Data.MIMETYPE,Phone.CONTENT_ITEM_TYPE);
values.put(Phone.NUMBER,phone);
values.put(Phone.TYPE,Phone.TYPE_MOBILE);
this.getContentResolver().insert(phoneURL,values);
}
}
手机通讯录程序数据库类MyDB.java
package com.demo.pr3.datax;
//对数据库进行管理,包括创建表,并对表中数据进行增删查改,以及打开和关闭数据库
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
*SQLite 数据库操作管理
*/
public class MyDB extends SQLiteOpenHelper{
//定义该类的主要数据成员
private static String DB_NAME="My_DB.db"; //数据库名称
private static int DB_VERSION=2; //版本号
private SQLiteDatabase db; //数据库操作对象
public MyDB(Context context)//构造函数
{
//在子类的构造函数实现过程中,一般先调用父类的构造函数
super(context,DB_NAME,null,DB_VERSION);
db=getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db){
// TODO 创建数据库后,对数据库的操作
}
@Override
public void onOpen(SQLiteDatabase db){
// TODO 每次成功打开数据库后首先被执行
super.onOpen(db);
}
@Override
public void onUpgrade(SQLiteDatabase db,
int oldVersion,int newVersion){
// TODO 更改数据库版本的操作
}
/***
* 执行SQLite数据库链接
*/
public SQLiteDatabase openConnection (){
if(!db.isOpen())
{
//以读写方式获取 SQLiteDatabase
db=getWritableDatabase();
}
return db;
}
/***
* 关闭SQLite数据库链接操作
*/
public void closeConnection (){
try{
if(db!=null&&db.isOpen())
db.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
/**
* 创建表
*/
public boolean creatTable(String createTableSql)
{
try{
openConnection();
db.execSQL(createTableSql);
}catch(Exception ex)
{
ex.printStackTrace();
return false;
}finally
{
closeConnection();
}
return true;
}
/**
* 添加操作
* @param tableName 表名
* @param values 集合对象表示要插入表中的记录
*/
public boolean save(String tableName,ContentValues values)
{
try{
openConnection();
db.insert(tableName,null,values);
}catch(Exception ex)
{
ex.printStackTrace();
return false;
}finally {
closeConnection();
}
return true;
}
/**
* 更新操作
*/
public boolean update(String table, ContentValues values,String whereClause,String []whereArgs)
{
try{
openConnection();
db.update(table,values,whereClause,whereArgs);
}catch(Exception ex)
{
ex.printStackTrace();
return false;
}finally
{
closeConnection();
}
return true;
}
/**
* 删除
* @param deleteSql 对应删除的条件
* @param obj 对应删除条件的值
*/
public boolean delete(String table,String deleteSql,String obj[])
{
try{
openConnection();
db.delete(table,deleteSql,obj);
}catch(Exception ex)
{
ex.printStackTrace();
return false;
}finally
{
closeConnection();
}
return true;
}
/**
* 查询操作
* @param findSql 对应查询字段,如:
* select * from person limit wher name=?
* @param obj 对应查询字段?占位参数的取值,如:
* new String[]
* String.valueOf(sName)}
*/
public Cursor find(String findSql,String obj[])
{
try{
openConnection();
Cursor cursor=db.rawQuery(findSql,obj);
return cursor;
}catch(Exception ex)
{
ex.printStackTrace();
return null;
}
}
/**
* 判断表是否存在
*/
public boolean isTableExits(String tablename){
try{
openConnection();
String str="select count(*)xcount from " +tablename;
db.rawQuery(str,null).close();
}catch(Exception ex)
{
return false;
}finally
{
closeConnection();
}
return true;
}
}
手机通讯录程序添加、编辑、查看信息类ContactsTable.java
package com.demo.pr3.datax;
//用来封装联系人表中数据
import java.util.Vector;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
/**
* 联系人表操作
*/
public class ContactsTable {
//定义类的成员变量
private final static String TABLENAME="contactsTable";//表名
private MyDB db;//数据库管理对象
//在构造方法中创建表
public ContactsTable(Context context)
{
db=new MyDB(context);
if(!db.isTableExits(TABLENAME))
{//定义SQL语句
String createTableSql="CREATE TABLE IF NOT EXISTS " +
TABLENAME+"(id_DB integer " +
"primary key AUTOINCREMENT," +
User.NAME +" VARCHAR," +
User.MOBLIE +" VARCHAR,"+
User.QQ +" VARCHAR,"+
User.DANWEI +" VARCHAR,"+
User.ADDRESS+ " VARCHAR)";
//创建表
db.creatTable(createTableSql);
}
}
/**
* 添加数据到联系人表
*/
public boolean addData(User user)
{
ContentValues values=new ContentValues();//将联系人数据放到ContentValues对象中
values.put(User.NAME,user.getName());
values.put(User.MOBLIE,user.getMoblie());
values.put(User.DANWEI,user.getDanwei());
values.put(User.QQ,user.getQq());
values.put(User.ADDRESS,user.getAddress());
return db.save(TABLENAME,values);
}
/**
* 获取联系人表数据
*/
public User[] getAllUser()
{
Vector<User> v=new Vector<User>();
Cursor cursor=null;
try {
cursor=db.find("select * from "+TABLENAME,null);
while(cursor.moveToNext()){
User temp=new User();
temp.setId_DB(cursor.getInt(cursor.getColumnIndex("id_DB")));
temp.setName(cursor.getString(cursor.getColumnIndex(User.NAME)));
temp.setMoblie(cursor.getString(cursor.getColumnIndex(User.MOBLIE)));
temp.setDanwei(cursor.getString(cursor.getColumnIndex(User.DANWEI)));
temp.setQq(cursor.getString(cursor.getColumnIndex(User.QQ)));
temp.setAddress(cursor.getString(cursor.getColumnIndex(User.ADDRESS)));
v.add(temp);
}
}catch(Exception e){
e.printStackTrace();
}finally {
if (cursor != null) {
cursor.close();
}
db.closeConnection();
}
if (v.size()>0){
return v.toArray(new User[]{});
}else{
User[] users=new User[1];
User user=new User();
user.setName("无结果");
users[0]=user;
return users;
}
}
/**
* 根据数据库改变主键 ID来获取联系人
*/
public User getUserByID(int id)
{
Cursor cursor=null;
try {
cursor=db.find("select * from "+TABLENAME +" where "
+"id_DB=?",new String[]{id+""});
User temp=new User();
//游标从一开始指向-1位置,moveToNext方法将游标移到了下一行,即第一行
cursor.moveToNext();
temp.setId_DB(cursor.getInt(cursor.getColumnIndex("id_DB")));
temp.setName(cursor.getString(cursor.getColumnIndex(User.NAME)));
temp.setMoblie(cursor.getString(cursor.getColumnIndex(User.MOBLIE)));
temp.setDanwei(cursor.getString(cursor.getColumnIndex(User.DANWEI)));
temp.setQq(cursor.getString(cursor.getColumnIndex(User.QQ)));
temp.setAddress(cursor.getString(cursor.getColumnIndex(User.ADDRESS)));
return temp;
}catch(Exception e){
e.printStackTrace();
}finally {
if(cursor != null){
cursor.close();
}
db.closeConnection();
}
return null;
}
/**
* @return
*/
public User[] findUserByKey(String key)
{
//定义一个专门存放user类型数据的vector向量类对象
Vector<User> v=new Vector<User>();
Cursor cursor=null;
try {
cursor=db.find("select * from "+TABLENAME +" where "
+User.NAME+" like '%"+key+"%' " +
" or "+User.MOBLIE+" like '%"+key+"%' " +
" or "+User.QQ+" like '%"+key+"%' "
,null);
while(cursor.moveToNext()){
User temp=new User();
temp.setId_DB(cursor.getInt(cursor.getColumnIndex("id_DB")));
temp.setName(cursor.getString(cursor.getColumnIndex(User.NAME)));
temp.setMoblie(cursor.getString(cursor.getColumnIndex(User.MOBLIE)));
temp.setDanwei(cursor.getString(cursor.getColumnIndex(User.DANWEI)));
temp.setQq(cursor.getString(cursor.getColumnIndex(User.QQ)));
temp.setAddress(cursor.getString(cursor.getColumnIndex(User.ADDRESS)));
//将符合查询条件的user对象添加到向量集中
v.add(temp);
}
}catch(Exception e){
e.printStackTrace();
}finally {
if(cursor != null){
cursor.close();
}
db.closeConnection();
}
if(v.size() > 0){
//将vector中的数据,强制以user数组形式返回
return v.toArray(new User[] {});
}else
{
User[] users=new User[1];
User user=new User();
user.setName("无结果");
users[0]=user;
return users;
}
}
/**
* 修改联系人信息
*/
public boolean updateUser(User user)
{
ContentValues values=new ContentValues();
values.put(User.NAME,user.getName());
values.put(User.MOBLIE,user.getMoblie());
values.put(User.DANWEI,user.getDanwei());
values.put(User.QQ,user.getQq());
values.put(User.ADDRESS,user.getAddress());
return db.update(TABLENAME, values," id_DB=? ",new String[]{user.getId_DB()+""});
}
/**
* 删除联系人
*/
public boolean deleteByUser(User user)
{
return db.delete(TABLENAME, " id_DB=?",new String[]{user.getId_DB()+""});
}
}
手机通讯录程序辅助类User.java
package com.demo.pr3.datax;
//辅助类,采用面向对象的方法管理联系人数据,以便于对联系人表中的字段统一进行设置和获取操作
/**
* 联系人信息类
*/
public class User {
public final static String NAME="name";
public final static String MOBLIE="mobile";
public final static String DANWEI="danwei";
public final static String QQ="qq";
public final static String ADDRESS="address";
private String name; //用户名
private String moblie;//手机号码
private String danwei;//单位
private String qq; //QQ
private String address;//地址
private int id_DB=-1;//表主键ID
public int getId_DB() {
return id_DB;
}
public void setId_DB(int idDB){
id_DB=idDB;
}
public String getName() {
return name;
}
public void setName(String name){
this.name=name;
}
public String getMoblie() {
return moblie;
}
public void setMoblie(String moblie){
this.moblie=moblie;
}
public String getDanwei() {
return danwei;
}
public void setDanwei(String danwei){
this.danwei=danwei;
}
public String getQq() {
return qq;
}
public void setQq(String qq){
this.qq=qq;
}
public String getAddress() {
return address;
}
public void setAddress(String address){
this.address=address;
}
}
手机通讯录程序添加联系人界面类AddContactsActivity.java
package com.demo.pr3;
//将界面上的数据保持到数据库(添加数据界面)
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import com.demo.pr3.datax.ContactsTable;
import com.demo.pr3.datax.User;
/********************(C)COPYRIGHT 2012********************
*增加号码记录操作界面
************************************************************/
public class AddContactsActivity extends Activity {
private EditText nameEditText; //姓名输入框
private EditText mobileEditText; //手机输入框
private EditText qqEditText; //qq输入框
private EditText danweiEditText; //单位输入框
private EditText addressEditText; //地址输入框
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit);
setTitle("添加联系人");
//从已设置的页面布局获得对应的控件
nameEditText = (EditText) findViewById(R.id.name);
mobileEditText = (EditText) findViewById(R.id.mobile);
danweiEditText = (EditText) findViewById(R.id.danwei);
qqEditText = (EditText) findViewById(R.id.qq);
addressEditText = (EditText) findViewById(R.id.address);
}
/**
*创建菜单
*/
public boolean onCreateOptionsMenu(Menu menu){
menu.add(Menu.NONE,1,Menu.NONE,"保存");
menu.add(Menu.NONE,2,Menu.NONE,"返回");
return super.onCreateOptionsMenu(menu);
}
/**
* 菜单事件 实现保存和返回处理操作,将输入界面中的信息先保存在User对象中,
* 再通过前面定义的ContactsTable类addData方法将其数据保存到数据库的表中
*/
public boolean onOptionsItemSelected(MenuItem item){
// TODO Auto-generated method stub
switch(item.getItemId()){
case 1://保存
if(!nameEditText.getText().toString().equals(""))
{
User user=new User();
user.setName(nameEditText.getText().toString());
user.setMoblie(mobileEditText.getText().toString());
user.setDanwei(danweiEditText.getText().toString());
user.setQq(qqEditText.getText().toString());
user.setAddress(addressEditText.getText().toString());
ContactsTable ct= new ContactsTable(AddContactsActivity.this);
if(ct.addData(user))
{
Toast.makeText(AddContactsActivity.this,"添加成功!",
Toast.LENGTH_SHORT).show();
finish();
}else
{
Toast.makeText(AddContactsActivity.this,"添加失败!",
Toast.LENGTH_SHORT).show();
}
}else
{
Toast.makeText(AddContactsActivity.this,"请先输入数据!",
Toast.LENGTH_SHORT).show();
}
break;
case 2://返回
finish();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
手机通讯录程序修改联系人界面类UpdateContactsActivity.java文章来源:https://www.toymoban.com/news/detail-528028.html
package com.demo.pr3;
//更新通讯录
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import com.demo.pr3.datax.ContactsTable;
import com.demo.pr3.datax.User;
/********************(C)COPYRIGHT 2012********************
*修改号码记录操作界面
************************************************************/
public class UpdateContactsActivity extends Activity {
private EditText nameEditText; //姓名输入框
private EditText mobileEditText; //手机输入框
private EditText qqEditText; //qq 输入框
private EditText danweiEditText; //单位输入框
private EditText addressEditText; //地址输入框
private User user; //修改的联系人
//将要修改的联系人数据赋值到用户界面进行显示
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit);
setTitle("修改联系人");
//从已设置的页面布局获得对应的控件
nameEditText = (EditText) findViewById(R.id.name);
mobileEditText = (EditText) findViewById(R.id.mobile);
danweiEditText = (EditText) findViewById(R.id.danwei);
qqEditText = (EditText) findViewById(R.id.qq);
addressEditText = (EditText) findViewById(R.id.address);
//将要修改的联系人数据赋值到用户界面进行显示
Bundle localBundle = getIntent().getExtras();
//参数id表示用户单击需要修改的记录值的主键
int id = localBundle.getInt("user_ID");
ContactsTable ct = new ContactsTable(this);
user = ct.getUserByID(id);
nameEditText.setText(user.getName());
mobileEditText.setText(user.getMoblie());
qqEditText.setText(user.getQq());
danweiEditText.setText(user.getDanwei());
addressEditText.setText(user.getAddress());
}
/**
* 创建菜单
*/
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, 1, Menu.NONE, "保存");
menu.add(Menu.NONE, 2, Menu.NONE, "返回");
return super.onCreateOptionsMenu(menu);
}
/**
* 菜单事件
*/
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case 1://保存
if (!nameEditText.getText().toString().equals("")) {
user.setName(nameEditText.getText().toString());
user.setMoblie(mobileEditText.getText().toString());
user.setDanwei(danweiEditText.getText().toString());
user.setQq(qqEditText.getText().toString());
user.setAddress(addressEditText.getText().toString());
ContactsTable ct = new ContactsTable(UpdateContactsActivity.this);
//修改数据库联系人信息
if (ct.updateUser(user)) {
Toast.makeText(UpdateContactsActivity.this, "修改成功!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(UpdateContactsActivity.this, "修改失败!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(UpdateContactsActivity.this, "数据不能为空!", Toast.LENGTH_SHORT).show();
}
break;
case 2://返回
finish();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
手机通讯录程序显示联系人界面类ContactMessageActivity.java文章来源地址https://www.toymoban.com/news/detail-528028.html
package com.demo.pr3;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.demo.pr3.datax.ContactsTable;
import com.demo.pr3.datax.User;
/********************(C)COPYRIGHT 2012********************
*显示联系人界面
************************************************************/
public class ContactsMessageActivity extends Activity {
private TextView nameTextView; //姓名输入框
private TextView mobileTextView; //手机输入框
private TextView qqTextView; //qq 输入框
private TextView danweiTextView; //单位输入框
private TextView addressTextView; //地址输入框
private User user; //联系人
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.message);
setTitle("联系人信息");
//从已设置的页面布局查找对应的控件
nameTextView=(TextView)findViewById(R.id.name);
mobileTextView=(TextView)findViewById(R.id.mobile);
danweiTextView=(TextView)findViewById(R.id.danwei);
qqTextView=(TextView)findViewById(R.id.qq);
addressTextView=(TextView)findViewById(R.id.address);
//将要修改的联系人数据赋值到用户界面进行显示
Bundle localBundle=getIntent().getExtras();
int id=localBundle.getInt("user_ID");
ContactsTable ct=new ContactsTable(this);
user =ct.getUserByID(id);
nameTextView.setText("姓名:"+user.getName());
mobileTextView.setText("电话:"+user.getMoblie());
qqTextView.setText("QQ:"+user.getQq());
danweiTextView.setText("单位:"+user.getDanwei());
addressTextView.setText("地址:"+user.getAddress());
}
/**
* 创建菜单
*/
public boolean onCreateOptionsMenu(Menu menu){
menu.add(Menu.NONE,1,Menu.NONE,"返回");
return super.onCreateOptionsMenu(menu);
}
/**
* 菜单事件
*/
public boolean onOptionsItemSelected(MenuItem item){
// TODO Auto-generated method stub
switch(item.getItemId()){
case 1://返回
finish();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
到了这里,关于Android手机通讯录(上)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!