Android手机开发——通讯录
实现增加、查询、修改、删除的功能,输入联系人信息,点击“添加”按钮,可以添加联系人信息到数据库;点击“查询”按钮,会发现添加的联系人信息显示在界面中;重新输入联系人电话,点击“修改”按钮,可以修改该联系人的电话,再进行查询发现联系人电话已经修改;点击“删除”按钮,会将数据库中该联系人的所有记录删除。
主界面的布局文件代码
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="100dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="姓名:" />
<EditText
android:id="@+id/et_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入姓名"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="电话:" />
<EditText
android:id="@+id/et_tel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入手机号码"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="20dp">
<Button
android:id="@+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="添加"
android:background="#b9b9ff"/>
<Button
android:id="@+id/btn_query"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="查询"
android:background="#dcb5ff"/>
<Button
android:id="@+id/btn_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="修改"
android:background="#e6caff"/>
<Button
android:id="@+id/btn_del"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="删除"
android:background="#acd6ff"/>
</LinearLayout>
<TextView
android:id="@+id/tv_show"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp" />
MyHelper.java
public class MyHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION=2;
private static final String DATABASE_NAME="mydb";
private static final String sql="CREATE TABLE directory("+
"_id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(20),"
+"phone VARCHAR(20))";
public MyHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
MyDBManager.java
public class MyDBManager {
private MyHelper myHelper;
private SQLiteDatabase sqLiteDatabase;
public MyDBManager(Context context){
myHelper=new MyHelper(context);
sqLiteDatabase=myHelper.getReadableDatabase();
}
public void getConnect(){
sqLiteDatabase=myHelper