实习阶段,今天没什么事可做,就写个通讯录玩玩,供大家参考一下具体实现方法和步骤,希望对大家有用。


首先作为通讯录总得有数据吧,那数据怎么来,又该如何显示呢,我用SQLite存储读写数据的。

先给大家看看效果图吧:

android 仿 通讯录 android简易通讯录_sql

      图1.当没有添加时的显示内容

android 仿 通讯录 android简易通讯录_android 仿 通讯录_02

                                         图2.插入数据时的显示界面


android 仿 通讯录 android简易通讯录_List_03

                                                图3.添加联系人信息


android 仿 通讯录 android简易通讯录_android 仿 通讯录_04

                                        图四.上下文菜单显示信息


android 仿 通讯录 android简易通讯录_List_05

                               图五.单击某通讯录一员时的弹窗界面



可以看到右下角还有一个向上的按钮图片,它表示当数据较多需要分页滑动时,点击此按钮可以回到顶部(代码就一行,下面会有代码表示的)。

由此我们可以想到如何设计页面,主页面布局中主要有三个组件,一个无疑是ListView,一个是当数据为空时的TextView,另一个就是右下角的至顶按钮了(activity_main.xml)。

另外我们还需要设计一个XML布局用来显示每一条数据(即每一个通讯录用户),它包括头像,姓名,手机号码(item_listview_main.xml)。

另外我还创建了

android 仿 通讯录 android简易通讯录_sql_06

以及在menu文件夹下创建了

android 仿 通讯录 android简易通讯录_List_07

分别表示插入时显示的界面,和菜单界面内容。看代码大家就应该清楚了。


还是直接上代码吧:

MySQLiteOpenHelper.java(数据库类)

import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import android.content.Context;
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteOpenHelper;

 public class MySQLiteOpenHelper extends SQLiteOpenHelper {
     // 数据库的名字
     private final static String DB_NAME = "db_mycontacts.db";
     // 数据库版本号
     private final static int VERSION = 1;
     // 数据库操作对象
     public SQLiteDatabase dbConn;

     public MySQLiteOpenHelper(Context context) {
         super(context, DB_NAME, null, VERSION);
         dbConn = this.getReadableDatabase();
     }
     // 创建数据库和其中的表结构的
     @Override
     public void onCreate(SQLiteDatabase db) {
         // 创建表结构
         db.execSQL("create table if not exists tb_mycontacts(_id integer primary key autoincrement , username , phonenumber)");
     }
     // 更新数据库及其中的 表结构的
     @Override
     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
         // 如果新的版本号高于旧的版本号
         if (newVersion > oldVersion) {
             // 删除表结构
             db.execSQL("drop table if exists tb_mycontacts");
             onCreate(db);
         }
     }
     /**
      * @作用:执行带占位符的select语句,查询数据,返回Cursor
      * @param sql
      * @param selectionArgs
      * @return Cursor
      */
     public Cursor selectCursor(String sql, String[] selectionArgs) {
         return dbConn.rawQuery(sql, selectionArgs);
     }

     /**
      * @作用:执行带占位符的select语句,返回结果集的个数
      * @param sql
      * @param selectionArgs
      * @return int
      */
     public int selectCount(String sql, String[] selectionArgs) {
         Cursor cursor = dbConn.rawQuery(sql, selectionArgs);
         if (cursor != null) {
             cursor.moveToFirst();
             int count = cursor.getInt(0);
             cursor.close();
             return count;
         } else {
             return 0;
         }
     }

     /**
      * @作用:执行带占位符的select语句,返回多条数据,放进List集合中。
      * @param sql
      * @param selectionArgs
      * @return List<Map<String, Object>>
      */
     public List<Map<String, Object>> selectList(String sql,
             String[] selectionArgs) {
         Cursor cursor = dbConn.rawQuery(sql, selectionArgs);
         return cursorToList(cursor);
     }

     /**
      * @作用:将Cursor对象转成List集合
      * @param Cursor
      *            cursor
      * @return List<Map<String, Object>>集合
      */
     public List<Map<String, Object>> cursorToList(Cursor cursor) {
         List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

         String[] arrColumnName = cursor.getColumnNames();
         while (cursor.moveToNext()) {
             Map<String, Object> map = new HashMap<String, Object>();
             for (int i = 0; i < arrColumnName.length; i++) {
                 Object cols_value = cursor.getString(i);
                 // switch (cursor.getType(i)) {
                 // case 1:
                 // cols_value = cursor.getInt(i);
                 // break;
                 // case 2:
                 // cols_value = cursor.getFloat(i);
                 // break;
                 // case 3:
                 // cols_value = cursor.getString(i);
                 // break;
                 // case 4:
                 // cols_value = cursor.getBlob(i);
                 // break;
                 // default:
                 // break;
                 // }
                 map.put(arrColumnName[i], cols_value);
             }
             list.add(map);
         }
         if (cursor != null) {
             cursor.close();
         }
         return list;
     }

     /**
      * @作用:执行带占位符的update、insert、delete语句,更新数据库,返回true或false
      * @param sql
      * @param bindArgs
      * @return boolean
      */
     public boolean execData(String sql, Object[] bindArgs) {
         try {
             dbConn.execSQL(sql, bindArgs);
             return true;
         } catch (Exception e) {
             return false;
         }
     }

     public void destroy() {
         if (dbConn != null) {
             dbConn.close();
         }
     }
 }MainActivity.java
import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;

 import android.app.Activity;
 import android.app.AlertDialog.Builder;
 import android.content.DialogInterface;
 import android.content.Intent;
 import android.net.Uri;
 import android.content.DialogInterface.OnClickListener;
 import android.os.Bundle;
 import android.view.ContextMenu;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.view.View;
 import android.view.ContextMenu.ContextMenuInfo;
 import android.widget.AdapterView;
 import android.widget.AdapterView.AdapterContextMenuInfo;
 import android.widget.AdapterView.OnItemClickListener;
 import android.widget.EditText;
 import android.widget.ListView;
 import android.widget.SimpleAdapter;
 import android.widget.TextView;
 import android.widget.Toast;

 public class MainActivity extends Activity {
     private MySQLiteOpenHelper dbHelper = null;
     private TextView emptyText;
     private ListView lv_main;
     private SimpleAdapter adapter = null;
     private List<Map<String, Object>> totalList = new ArrayList<Map<String, Object>>();

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         dbHelper = new MySQLiteOpenHelper(this);
         lv_main = (ListView) findViewById(R.id.listView_main);
         emptyText = (TextView) findViewById(R.id.textView_empty);
         totalList = getcontent();

         adapter = new SimpleAdapter(this, totalList, R.layout.item_listview_main,
                 new String[] { "phonenumber", "username" },
                 new int[] { R.id.textView_item_phonenumber, R.id.textView_item_username });
         lv_main.setAdapter(adapter);
         lv_main.setEmptyView(emptyText);
         registerForContextMenu(lv_main);

         lv_main.setOnItemClickListener(new OnItemClickListener() {
             @Override
             public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                 final String number = totalList.get(arg2).get("phonenumber").toString();
                 Builder builder = createAlertDialog(android.R.drawable.stat_sys_phone_call, "确定要拨打: " + number + " ?");
                 builder.setPositiveButton("拨打", new OnClickListener() {
                     @Override
                     public void onClick(DialogInterface dialog, int which) {
                         Intent intent = new Intent();
                         intent.setAction(Intent.ACTION_CALL);
                         intent.setData(Uri.parse("tel:" + number));
                         startActivity(intent);
                     }
                 });
                 builder.show();
             }
         });
     }

     private List<Map<String, Object>> getcontent() {
         return dbHelper.selectList("select * from tb_mycontacts", null);
     }

     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
         // Inflate the menu; this adds items to the action bar if it is present.
         getMenuInflater().inflate(R.menu.main, menu);
         return true;
     }

     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
         switch (item.getItemId()) {
         case R.id.action_insert:
             Builder builder_insert = createAlertDialog(android.R.drawable.ic_dialog_alert, "添加联系人信息");
             View view = getLayoutInflater().inflate(R.layout.dialog_insert, null);
             final EditText et_name = (EditText) view.findViewById(R.id.editText_dialog_name);
             final EditText et_number = (EditText) view.findViewById(R.id.editText_dialog_number);

             builder_insert.setView(view);
             builder_insert.setPositiveButton("确定", new OnClickListener() {
                 @Override
                 public void onClick(DialogInterface dialog, int which) {
                     String name = et_name.getText() + "";
                     String number = et_number.getText() + "";
                     if (name.equals("") || number.equals("")) {
                         toast("whta are you 弄啥咧?");
                     } else {
                         String sql = "insert into tb_mycontacts(username, phonenumber)values(?,?)";
                         boolean flag = dbHelper.execData(sql, new Object[] { name, number });
                         if (flag) {
                             toast("插入成功!");
                             reloadView();
                         } else {
                             toast("插入失败!");
                         }
                     }
                 }
             });
             builder_insert.show();
             break;
         case R.id.action_deleteAll:
             Builder builder_delete = createAlertDialog(android.R.drawable.ic_menu_delete, "确定要删除所有数据?");
             builder_delete.setPositiveButton("删除", new OnClickListener() {
                 @Override
                 public void onClick(DialogInterface dialog, int which) {
                     String sql = "delete from tb_mycontacts";
                     boolean flag = dbHelper.deleteData(sql);
                     if (flag) {
                         toast("删除所有数据成功!");
                         reloadView();
                     } else {
                         toast("删除所有数据失败!");
                     }
                 }
             });
             builder_delete.show();
         default:
             break;
         }
         return super.onOptionsItemSelected(item);
     }

     @Override
     public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
         super.onCreateContextMenu(menu, v, menuInfo);

         AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
         menu.setHeaderIcon(android.R.drawable.btn_dialog);
         String name = totalList.get(info.position).get("username").toString();
         String number = totalList.get(info.position).get("phonenumber").toString();
         menu.setHeaderTitle(name + "|" + number);
         getMenuInflater().inflate(R.menu.contextmenu_listview_main, menu);
     }

     @Override
     public boolean onContextItemSelected(MenuItem item) {
         AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
         String name = totalList.get(info.position).get("username").toString();
         String number = totalList.get(info.position).get("phonenumber").toString();
         final String _id = totalList.get(info.position).get("_id").toString();
         switch (item.getItemId()) {
         case R.id.action_delete:
             Builder builder_dele = createAlertDialog(android.R.drawable.ic_delete, "确定要删除?");
             builder_dele.setPositiveButton("删除", new OnClickListener() {
                 @Override
                 public void onClick(DialogInterface dialog, int which) {
                     String sql = "delete from tb_mycontacts where _id=?";
                     boolean flag = dbHelper.execData(sql, new Object[] { _id });
                     if (flag) {
                         toast("删除数据成功!");
                         reloadView();
                     } else {
                         toast("删除数据失败!");
                     }
                 }
             });
             builder_dele.show();
             break;

         case R.id.action_update:
             Builder builder_update = createAlertDialog(android.R.drawable.ic_dialog_alert, "修改联系人信息");
             View view = getLayoutInflater().inflate(R.layout.dialog_update, null);
             final EditText editText_name = (EditText) view.findViewById(R.id.editText_dialog_name);
             final EditText editText_number = (EditText) view.findViewById(R.id.editText_dialog_number);

             // 因为是更新,所以两个控件里应该有初始值
             editText_name.setText(name);
             editText_number.setText(number);

             builder_update.setView(view);

             builder_update.setPositiveButton("确认", new OnClickListener() {

                 @Override
                 public void onClick(DialogInterface dialog, int which) {
                     String name_sure = editText_name.getText() + "";
                     String number_sure = editText_number.getText() + "";
                     String sql = "update tb_mycontacts set username=? , phonenumber=? where _id=?";
                     boolean flag = dbHelper.execData(sql, new Object[] { name_sure, number_sure, _id });
                     if (flag) {
                         toast("更新数据成功!");
                         reloadView();
                     } else {
                         toast("更新数据失败!");
                     }
                 }
             });
             builder_update.show();
             break;

         case R.id.action_sendsms:
             Intent intent = new Intent();
             intent.setAction(Intent.ACTION_SENDTO);
             intent.setData(Uri.parse("smsto:" + number));
             intent.putExtra("sms_body", "dont't call me!");
             startActivity(intent);
             break;
         default:
             break;
         }
         return super.onContextItemSelected(item);
     }

     protected void reloadView() {
         totalList.clear();
         totalList.addAll(getcontent());
         adapter.notifyDataSetChanged();
     }

     public void clickButton(View view) {
         lv_main.setSelection(0);
     }

     protected void toast(String string) {
         Toast.makeText(MainActivity.this, string, Toast.LENGTH_LONG).show();
     }

     private Builder createAlertDialog(int icDialogAlert, String string) {
         Builder builder = new Builder(this);
         builder.setIcon(icDialogAlert);
         builder.setTitle(string);
         builder.setNegativeButton("取消", null);
         return builder;
     }
 }


activity_main.xml:<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent" >

     <ListView
         android:id="@+id/listView_main"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_alignParentLeft="true" >
     </ListView>

     <ImageView
         android:id="@+id/imageView_totop"
         android:layout_width="50dp"
         android:layout_height="50dp"
         android:layout_alignParentBottom="true"
         android:layout_alignParentRight="true"
         android:layout_marginBottom="10dp"
         android:layout_marginRight="10dp"
         android:onClick="clickButton"
         android:src="@drawable/lv_backtotop" />

     <TextView
         android:id="@+id/textView_empty"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:gravity="center"
         android:textSize="20sp"
         android:textColor="#00f"
         android:text="暂无联系人信息!" />

 </RelativeLayout>dialog_insert.xml:
<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical" >

     <EditText
         android:id="@+id/editText_dialog_name"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:ems="10" 
         android:hint="请输入联系人姓名">

         <requestFocus />
     </EditText>

     <EditText
         android:id="@+id/editText_dialog_number"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:ems="10"
         android:inputType="phone" 
         android:hint="输入电话号码"/>

 </LinearLayout>

dialog_update.xml:<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical" >

     <EditText
         android:id="@+id/editText_dialog_name"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:ems="10"
         android:hint="联系人" >

         <requestFocus />
     </EditText>

     <EditText
         android:id="@+id/editText_dialog_number"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:ems="10"
         android:hint="手机号码"
         android:inputType="phone" />

 </LinearLayout>
item_listview_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent" >

     <ImageView
         android:id="@+id/imageView_item_headpic"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentLeft="true"
         android:layout_alignParentTop="true"
         android:src="@drawable/ic_launcher" />

     <TextView
         android:id="@+id/textView_item_username"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentTop="true"
         android:layout_marginLeft="20dp"
         android:layout_toRightOf="@+id/imageView_item_headpic"
         android:textSize="24sp"
         android:textColor="#00f"
         android:text="TextView" />

     <TextView
         android:id="@+id/textView_item_phonenumber"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignBottom="@+id/imageView_item_headpic"
         android:layout_alignLeft="@+id/textView_item_username"
         android:text="TextView" />

 </RelativeLayout>contextmenu_listview_main.xml(menu文件夹下):
<?xml version="1.0" encoding="utf-8"?>
 <menu xmlns:android="http://schemas.android.com/apk/res/android" >
     <item
         android:id="@+id/action_delete"
         android:title="删除"/>
     <item
         android:id="@+id/action_update"
         android:title="更新"/>
     <item
         android:id="@+id/action_sendsms"
         android:title="发短信"/>

 </menu>

main.xml:(menu文件夹下)<menu xmlns:android="http://schemas.android.com/apk/res/android" >

     <item
         android:id="@+id/action_insert"
         android:orderInCategory="100"
         android:showAsAction="never"
         android:title="插入新数据"/>
     <item
         android:id="@+id/action_deleteAll"
         android:orderInCategory="100"
         android:showAsAction="never"
         android:title="删除所有数据"/>

 </menu>

最后记得在AndroidManifest.xml中加入拨打电话和发短信的权限哦

<uses-permission android:name="android.permission.SEND_SMS"/>
     <uses-permission android:name="android.permission.CALL_PHONE"/>

最后附上源代码下载地址吧!

                                                                                                

android 仿 通讯录 android简易通讯录_android 仿 通讯录_08