Realize emergency contact function - based on SQL database

The level belongs to the color pen level, and the projects developed by myself are basically pitted step by step. This time, some pitfalls encountered in the development of the emergency contact module are recorded.

Emergency contacts feature summary:

  • create contact

  • Modify contact information

  • delete contact

  • dial number

The essence of the emergency contact function is the address book, and the address book, as we all know, is implemented based on the database. Here, the built-in sqllite database of Android is used.

Create DatabaseHelper:

It is mainly query statements for building tables and adding, deleting, modifying and checking. This is not a big problem, if you haven’t learned it before, you just need to remember that there is such a thing.

public class DatabaseHelper extends SQLiteOpenHelper {
    //建表操作,固定的格式
    private static final String DB_NAME="Contact";
    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);";


    private SQLiteDatabase db;
    public 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 update(ContentValues values,String tp)
    {
        SQLiteDatabase db=getWritableDatabase();
        db.update(TABLE_NAME,values,"name=?",new String[]{tp});
    }

    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) {

    }
}

The main interface is still ListView, and RecyclerView is also available. You can consider using RecyclerView in the future.

xml file for contact relationlist_item

<?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="wrap_content"
    android:orientation="vertical"
    android:layout_marginRight="10dp"
    android:layout_marginLeft="10dp"
    android:padding="10dp"
    android:background="@drawable/contactlistitem">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/dialog_title"
        android:layout_alignParentStart="true"

        android:orientation="horizontal">

        <TextView
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="姓名:"
            android:textColor="@color/alpha_75_colorPrimary"
            android:textSize="16dp" />

        <TextView
            android:id="@+id/name"
            android:layout_width="275dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:textSize="16dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"

        android:orientation="horizontal">

        <TextView
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="电话:"
            android:textColor="@color/alpha_75_colorPrimary"
            android:textSize="16dp" />

        <TextView
            android:id="@+id/tel"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:textSize="16dp"
            />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:orientation="horizontal">
       <ImageView
           android:layout_weight="1"
           android:id="@+id/update"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_gravity="center_horizontal"
           android:src="@drawable/update"/>
        <ImageView
            android:layout_weight="1"
            android:id="@+id/delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:src="@drawable/delete"/>
    </LinearLayout>
</LinearLayout>

renderings

:

I encountered a problem when I realized the function of creating a contact. Click the Add button, a dialog box pops up, and enter the contact name and phone number in the dialog box. This is because I have not implemented the custom style of Dialog, so I also I checked a lot of blogs, and I have written a blog to record the custom dialog, so I won’t go into details here.

What I don't know is how to project the contents of the dialog box into the listView, the solution is to use SimpleCursorAdapter, this is the first time I use this adapter.

The official explanation is: a simple adapter that maps the data in the cursor to the TextView control or ImageView control in the layout file.

How to use it, click this link https://blog.csdn.net/yhaolpz/article/details/51635860 .

Finally realized the function.

        //建立映射集
        final String[] from={"name","tel"};
        int[] to={R.id.name,R.id.tel};
        //设置适配器
        SimpleCursorAdapter scadapter=new     
        SimpleCursorAdapter(getContext(),R.layout.relationlist,cursor,from,to);
        listView.setAdapter(scadapter);

Manually create the mapping method getRelationFromDB

private void getRelationFromDB()
    {
        final DatabaseHelper dbHelper=new DatabaseHelper(getContext());
        final Cursor cursor=dbHelper.query();

        //建立映射集
        final String[] from={"name","tel"};
        int[] to={R.id.name,R.id.tel};
        //设置适配器
        SimpleCursorAdapter scadapter=new SimpleCursorAdapter(getContext(),R.layout.relationlist,cursor,from,to);
        listView.setAdapter(scadapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //初始化操作
                Update=view.findViewById(R.id.update);
                Delete=view.findViewById(R.id.delete);
                name=view.findViewById(R.id.name);
                tel=view.findViewById(R.id.tel);

                //Log.e("YT:",name.toString());
                final long temp=id;
                //删除信息
                Delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AlertDialog.Builder adBuilder=new AlertDialog.Builder(getActivity());
                        adBuilder.setMessage("确认要删除联系人吗?").setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dbHelper.del((int) temp);
                                Cursor cursor = dbHelper.query();
                                String[] from = { "name", "tel"};
                                int[] to={ R.id.name,R.id.tel};
                                SimpleCursorAdapter scadapter = new SimpleCursorAdapter(getActivity().getApplicationContext(),R.layout.relationlist,cursor,from,to);
                                listView.setAdapter(scadapter);

                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                        AlertDialog alertDialog=adBuilder.create();
                        alertDialog.show();
                    }
                });
                //修改联系人信息
                Update.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialogshow(name.getText().toString(),tel.getText().toString());
                    }
                });
                //点击电话号码,跳转到拨打页面
                tel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(Intent.ACTION_DIAL);
                        intent.setData(Uri.parse("tel: "+tel.getText().toString()));
                        startActivity(intent);
                    }
                });

            }
        });
        dbHelper.close();

    }

This piece of code implements three functions: delete, modify, and make a call. Among them, making a call is the easiest, just call the dial directly with the intent, and the others are not so easy.

The two functions of creating and modifying a contact must pop up a dialog box, so these two functions can be implemented in one method, and when using it, two values ​​are passed in, which are the contact name and phone number. If the input is " " , then it is to create a new one, if it is not empty, it is to modify, the difference between the two functions is that the database operation is different. The above code

 private void dialogshow(final String Name, final String Tel) {

        LayoutInflater inflater = LayoutInflater.from(getContext());
        //加载自定义的格式
        View v=inflater.inflate(R.layout.addrelstion,null);
        //确定,取消

        Button btn_save = v.findViewById(R.id.dialog_btn_save);
        Button btn_cancel = v.findViewById(R.id.dialog_btn_cancel);

        final Dialog dialog=new MyDialog(getContext(),0,0,v,R.style.DialogTheme);
        dialog.setCancelable(true);
        dialog.show();
        //解决dialog中EditText不能弹出键盘的问题
        /*dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);*/
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

        addName=(EditText)v.findViewById(R.id.addName);
        Log.e("Editext",addName.getText().toString());
        addTel=(EditText) v.findViewById(R.id.addTel);

        dialog.getWindow().setContentView(v);//自定义布局应该在这里添加,要在dialog.show()的后面
        //dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        final ContentValues values = new ContentValues();

        final DatabaseHelper dbHelper = new DatabaseHelper(getContext().getApplicationContext());

        //在弹出的对话框中显示联系人信息,如果之前未创建过,则显示为空,若创建过,则显示.
        addName.setText(Name.toCharArray(),0,Name.length());
        addTel.setText(Tel.toCharArray(),0,Tel.length());
        //保存按钮点击事件
            btn_save.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    values.put("name", addName.getText().toString());
                    values.put("tel", addTel.getText().toString());
                    //创建新的联系人
                    if(Name=="")
                    {
                        dbHelper.insert(values);

                    }
                    //修改信息
                    else if(Name!="")
                    {
                        dbHelper.update(values,Name);
                    }
                    getRelationFromDB();
                    dialog.dismiss();
                }
            });
            btn_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
    }

In this way, the function is basically realized, and the format of the input phone can be judged later, and a regular expression can be added.

Guess you like

Origin blog.csdn.net/YuannaY/article/details/86695940