Android应用开发——数据库通讯录

版权声明:转载请注明出处 https://blog.csdn.net/Zach_z/article/details/80788681

代码下载地址

一、设计目的

  1. 掌握SQLiteOpenHelper类结构
  2. 掌握基于SQLite数据库的应用开发过程
  3. 掌握Content Provider发布数据的方法
  4. 掌握Content Resolver获取数据的方法

二、设计内容

实现基于SQLite数据库的通信录应用,通过单击增加图标打开添加通信录界面,通过单击通信录中的各条信息可删除选中项。

三、软硬件环境

开发环境:Android Studio
模拟运行:Android Emulator – Nexus_5X_API_24

四、实现过程及结果

4.1 建立数据库操作类DatabaseHelper如下所示

public class DatabaseHelper extends SQLiteOpenHelper{
    private static final String DB_NAME = "MyRelation.db";
    private static final String TABLE_NAME = "relation";
    private static final String CREATE_TABLE = "create table relation(_id integer primary key autoincrement," +
                                               "name text," +
                                               "tel text," +
                                               "groupName text);";
    private SQLiteDatabase db;

    DatabaseHelper(Context context){
        super(context,DB_NAME,null,2);
    }

    public void insert(ContentValues values){
        SQLiteDatabase db = getWritableDatabase();
        db.insert(TABLE_NAME,null,values);
        db.close();
    }

    public void del(int id){
        if(db==null)
            db = getWritableDatabase();
        db.delete(TABLE_NAME,"_id = ?",new String[]{String.valueOf(id)});
    }
    public Cursor query(){
        SQLiteDatabase db = getWritableDatabase();
        Cursor cursor = db.query(TABLE_NAME,null,null,null,null,null,null);
        return cursor;
    }
    public void close(){
        if(db != null)
            db.close();
    }
    public void onCreate(SQLiteDatabase db){
        this.db = db;
        db.execSQL(CREATE_TABLE);
    }
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){}
}

4.2 修改主布局如下:

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

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="通讯录"
        android:background="#777"
        android:textColor="#ddd"
        android:textSize="16pt"
        android:gravity="center"/>
    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:layout_alignLeft="@+id/title">
    </ListView>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerInParent="true"
        android:cropToPadding="false"
        android:onClick="add"
        android:src="@mipmap/add" />
</RelativeLayout>

完成后的界面如图所示:

这里写图片描述

4.3 修改主Activity文件:

public class MainActivity extends AppCompatActivity {
    private ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listView);
        getRelationFromDB();
    }

    private void getRelationFromDB(){
        final DatabaseHelper dbHelper = new DatabaseHelper(this);
        final Cursor cursor = dbHelper.query();
        final String[] from = { "_id", "name", "tel", "groupName"};
        int[] to = {R.id._id,R.id.name,R.id.tel,R.id.group};
        SimpleCursorAdapter scadapter = new SimpleCursorAdapter(this,R.layout.relationlist,cursor,from,to);
        listView.setAdapter(scadapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
                final long temp = id;
                AlertDialog.Builder adBuilder = new AlertDialog.Builder(MainActivity.this);
                adBuilder.setMessage("确认要删除记录吗?").setPositiveButton("确认",new DialogInterface.OnClickListener(){
                    public void onClick(DialogInterface dialog, int which){
                        dbHelper.del((int) temp);
                        Cursor cursor = dbHelper.query();
                        String[] from = { "_id", "name", "tel", "groupName"};
                        int[] to={R.id._id, R.id.name,R.id.tel,R.id.group};
                        SimpleCursorAdapter scadapter = new SimpleCursorAdapter(getApplicationContext(),R.layout.relationlist,cursor,from,to);
                        MainActivity.this.listView.setAdapter(scadapter);
                    }
                }).setNegativeButton("取消",new DialogInterface.OnClickListener(){
                    public void onClick(DialogInterface dialog,int which){}
                });
                AlertDialog alertDialog = adBuilder.create();
                alertDialog.show();
            }
        });
        dbHelper.close();
    }

    public void add(View view) {
        Intent intent = new Intent(MainActivity.this,AddRelationActivity.class);
        startActivityForResult(intent,0x111);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,Intent data){
        super.onActivityResult(requestCode,resultCode,data);
        if(requestCode == 0x111 && resultCode == 0x111){
            getRelationFromDB();
        }
    }
}

4.4 创建列表视图布局文件relationlist.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="horizontal">

    <TextView
        android:id = "@+id/_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10pt"/>
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10pt"/>
    <TextView
        android:id = "@+id/tel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10pt"/>
    <TextView
        android:id = "@+id/group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10pt"/>
</LinearLayout>

4.5 创建增加联系人界面布局文件addrelation.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">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="姓名"/>
    <EditText
        android:id="@+id/addName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="电话"/>
    <EditText
        android:id="@+id/addTel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="所属组"/>
    <Spinner
        android:id="@+id/addGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:entries="@array/dept"></Spinner>
    <Button
        android:id="@+id/save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="保存"
        android:onClick="save"
        android:layout_gravity="center"/>
</LinearLayout>

完成后的界面如图所示:
这里写图片描述

4.6 创建增加联系人界面主Activity文件AddRelationActivity.java:

public class AddRelationActivity extends Activity{
    private EditText addName, addTel;
    private Spinner addGroup;
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addrelation);
        addName = (EditText)findViewById(R.id.addName);
        addTel = (EditText)findViewById(R.id.addTel);
        addGroup = (Spinner) findViewById(R.id.addGroup);
    }
    public void save(View view){
        final ContentValues values = new ContentValues();
        values.put("name",addName.getText().toString());
        values.put("tel",addTel.getText().toString());
        values.put("groupName",addGroup.getSelectedItem().toString());
        final DatabaseHelper dbHelper = new DatabaseHelper(getApplicationContext());
        final AlertDialog.Builder adBuilder = new AlertDialog.Builder(this);
        adBuilder.setMessage("确认保存记录吗?").setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogI, int which) {
                dbHelper.insert(values);
                Intent intent = getIntent();
                setResult(0x111,intent);
                AddRelationActivity.this.finish();
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogI, int which) {}
        });
        AlertDialog alertDialog = adBuilder.create();
        alertDialog.show();
    }
}

在新增联系人页面添加联系人,在主页面看到数据库相关存储信息,点击可以删除联系人(delete数据库信息)

这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

猜你喜欢

转载自blog.csdn.net/Zach_z/article/details/80788681
今日推荐