移动应用开发实践实验四

实验六:基于SQLite的通讯录

一、 实验目的

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

二、 实验内容

简要介绍本次实验的内容及要求。(通过文字与图片说明)
实现基于SQLite数据库的通信录应用,运行结果如图1-图3所示:通过单击增加图标打开添加通信录界面,通过单击通信录中的各条信息可删除选中项。

三、 理论

Android系统中集成了SQLite 数据库,并且为数据库的操作提供了相关的类和方法,便于没
有数据库开发经验的开发者编写程序。另外,Android平台中利用Content Provider 机制来实现跨应用程序数据共享。一个应用程序可以通过Content Provider 来发布自己的数据,其他的应用程序可以通过Content Resolver来获取共享数据。

四、 设计步骤

将设计内容细化为具体步骤,完善每步的具体内容。

  1. 建立数据库操作类DatabaseHelper,代码如下所示。
  2. 修改主布局如下,请将下列空出代码部分补全。
  3. 修改主Activity文件MainActivity.java,代码如下所示。
  4. 创建列表视图布局文件relationlist.xml,请将下列空出代码部分补全。
  5. 创建添加联系人界面布局文件addrelation,请将下列空出代码部分补全。
  6. 创建增加联系人界面主Activity文件AddRelationActivity.java,代码如下所示。
  7. 在AndroidManifest.xml文件中添加AddRelationActivity界面应用。

五、 效果图展示

根据实验内容的要求,把设计的每部分效果图进行展示,并对核心代码进行分析。(此处需要截图)

六、 实验总结

此处是对本次实验过程的总结(主要学习到了哪些知识,有什么心得体会等)。

九、 注意事项

下拉框需要设置一个values的资源,就像是本题中的groups
在这里插入图片描述
时间紧迫,有错的或者不懂的联系我吧。溜了溜了~~~
请添加图片描述

八、 代码

DatabaseHelper.java

package com.example.test4;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

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 DatabaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }
    public void close() {
        if(db!=null) db.close();
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        this.db = db;
        db.execSQL(CREATE_TABLE);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }
}

MainActivity.java

package com.example.test4;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;

public class MainActivity extends AppCompatActivity {
    private ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listView);
        getRelationFromDB();
    }
    private void getRelationFromDB() {
        final DatabaseHelper databaseHelper = new DatabaseHelper(this);
        Cursor cursor = databaseHelper.query();
        String[] from = {"_id", "name", "tel", "groupName"};
        int[] to = {R.id._id, R.id.name, R.id.tel, R.id.group};
        SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this, R.layout.relationlist, cursor, from, to);
        listView.setAdapter(simpleCursorAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                final long temp = id;
                //Log.d("temp", "onItemClick");
                AlertDialog.Builder adBuilder = new AlertDialog.Builder(MainActivity.this);
                adBuilder.setMessage("确定要删除记录吗?").setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        databaseHelper.del((int)temp);
                        Cursor cursor = databaseHelper.query();
                        String[] from = {"_id", "name", "tel", "groupName"};
                        int[] to = {R.id._id, R.id.name, R.id.tel, R.id.group};
                        SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.relationlist, cursor, from, to);
                        MainActivity.this.listView.setAdapter(simpleCursorAdapter);
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) { }
                });
                AlertDialog alertDialog = adBuilder.create();
                alertDialog.show();
            }
        });
        databaseHelper.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();
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fffae4"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:background="#FFE4E1"
        android:text="通讯录"
        android:textSize="40dp"
        />
    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        />
    <ImageView
        android:src="@drawable/add"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:onClick="add"
        />
</RelativeLayout>

AddRelationActivity.java

package com.example.test4;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class AddRelationActivity extends AppCompatActivity {
    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());
        //Toast.makeText(this, values.toString(), Toast.LENGTH_SHORT).show();
        final DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext());
        final AlertDialog.Builder adBuilder = new AlertDialog.Builder(this);
        adBuilder.setMessage("确认保存记录吗?").setPositiveButton("确认",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                databaseHelper.insert(values);
                Intent intent = getIntent();
                setResult(0x111, intent);
                AddRelationActivity.this.finish();
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) { }
        });
        AlertDialog alertDialog = adBuilder.create();
        alertDialog.show();
    }
}

addrelation.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#fffae4"
    tools:context=".AddRelationActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="姓名"
        android:textSize="30dp"
        />
    <EditText
        android:id="@+id/addName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="30dp"
        android:hint="请输入姓名"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="电话"
        android:textSize="30dp"
        />
    <EditText
        android:id="@+id/addTel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="30dp"
        android:hint="请输入电话号码"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="所属组"
        android:textSize="30dp"
        />
    <Spinner
        android:id="@+id/addGroup"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:entries="@array/groups"
        />
    <Button
        android:id="@+id/save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:onClick="save"
        android:text="保存"
        />
</LinearLayout>

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:descendantFocusability="blocksDescendants"
    android:orientation="horizontal"
    android:background="#fffae4">
    <TextView
        android:id="@+id/_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="id"
        android:textSize="20dp"
        android:visibility="gone"
        />
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="40dp"
        android:text="name"
        android:textSize="20dp"
        android:layout_weight="1"
        />
    <TextView
        android:id="@+id/tel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="tel"
        android:textSize="20dp"
        android:layout_weight="3"
        />
    <TextView
        android:id="@+id/group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="40dp"
        android:text="group"
        android:textSize="20dp"
        android:layout_weight="1"
        />
    <CheckBox
        android:id="@+id/select"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="false"
        android:visibility="gone"
        />
</LinearLayout>

groups.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="groups">
        <item>同事</item>
        <item>同学</item>
        <item>朋友</item>
    </string-array>
</resources>

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">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Test4"
        tools:targetApi="31">
        <activity
            android:name=".AddRelationActivity"
            android:exported="false">
            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
    </application>

</manifest>
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值