Android studio implements address book

This project mainly realizes the functions of adding, deleting, modifying and querying contact information (name and telephone). SQLite database is mainly used to store data. Unlike other SQL databases, SQLite database does not need to install another database software on the mobile phone. Android system has integrated this database. We will introduce SQLite database in detail below.

The development environment is still the same. JDK version 1.8, API version 28 and Android studio version 3.6.1 are preferred.

The overall layout is a linear layout. I set the page margin: Android: padding = "10dp", and the vertical vertical mode is also selected for the orientation direction. First, a small LinearLayout is placed, in which a text box and an input box represent the name. Then put a LinearLayout, which is also a text box and an input box to represent the phone number. This is a common basic design for every project. The code is as follows:

    <LinearLayout
        android:layout_marginTop="130dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="姓 名:"
            android:textSize="28sp"/>
        <EditText
            android:id="@+id/et_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入姓名"
            android:textSize="26sp"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="电 话:"
            android:textSize="28sp"/>
        <EditText
            android:id="@+id/et_phone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入电话号码"
            android:textSize="26sp"/>
    </LinearLayout>

Here are four buttons. I set four colors to distinguish it. Here, I divide the width of the four buttons into the parent layout, set the width of the four buttons to 0dp, and then set the weight to 1.

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp">
        <Button
            android:id="@+id/btn_add"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginRight="2dp"
            android:layout_weight="1"
            android:background="#7CFC00"
            android:text="添加"
            android:textSize="18sp"/>

        <Button
            android:id="@+id/btn_query"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginRight="2dp"
            android:layout_weight="1"
            android:background="#DCB5FF"
            android:text="查询"
            android:textSize="18sp"/>
        <Button
            android:id="@+id/btn_update"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginRight="2dp"
            android:layout_weight="1"
            android:background="#97FFFF"
            android:text="修改"
            android:textSize="18sp"/>
        <Button
            android:id="@+id/btn_delete"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginRight="2dp"
            android:layout_weight="1"
            android:background="#ACD6FF"
            android:text="删除"
            android:textSize="18sp"/>
    </LinearLayout>

There is also a hidden textview at the bottom, which is used to display the queried contact information.

<TextView
        android:id="@+id/tv_show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:textSize="20sp"/>

SQLite is a lightweight relational database with fast operation speed and less resources. It is very suitable for use on mobile devices. It not only supports standard SQL syntax, but also follows the acid (database transaction) principle. It does not need an account and is very convenient to use! The built-in SQLite for Android is version 3 of SQLite.

Previously, we learned to use files and SharedPreferences to save data, but in many cases, files are not necessarily effective. For example, multithreading concurrent access is related; App has to deal with complex data structures that may change, and so on. Such as bank deposit and withdrawal! Using the first two will be very weak or cumbersome. The emergence of database can solve this problem, and Android provides us with such a lightweight SQLite, which must be used well.

SQLite supports five data types: null, integer, real (floating point number), text (string text) and blob (binary object). Although there are only five data types, they can be saved for varchar, char and other data types; Because SQLite has a biggest feature: you can save data of various data types to any field, regardless of the data type declared by the field. For example, you can store string strings in fields of integer type. Of course, except for fields declared as primary key integer primary key, only 64 bit integers can be stored. In addition, SQLite ignores the data type information following the field name in the CREATE TABLE statement when parsing the CREATE TABLE statement. As shown in the following statement, the type information of the name field will be ignored:

 CREATE TABLE person (personid integer primary key autoincrement, name varchar(20))

Abstract class, we can inherit this class, and then override the methods of database creation and update. We can also obtain database instances through the objects of this class, or close the database.

Database access class: we can add, delete, modify and query the database through the objects of this class.

Cursor, a bit similar to the resultset and result set in JDBC! It can be simply understood as a pointer to a record in the database.

Android provides us with two methods of sqliteopenhelper: oncreate() and onupgrade() to implement oncreate (database): generate database tables when using the software for the first time. Onupgrade (database, OldVersion, newversion): it will be called when the database version changes. Generally, the version number needs to be changed when the software is upgraded, and the database version is controlled by the programmer.

  class MyHelper extends sqliteOpenHelper{
        public MyHelper(Context context){
            super(context,"dzh.db",null,1);//数据库文件夹名为dzh.db
        }
        //数据库第一次创建时被调用
        @Override
        public void onCreate(sqliteDatabase db){
            db.execsql("CREATE TABLE person(_id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(20),phone VARCHAR(20))");
        }
        //软件版本号发生改变时调用
        @Override
        public void onUpgrade(sqliteDatabase db,int oldVersion,int newVersion){

        }

This project directly uses some API methods for operating the database provided by Android. Next, we use the code for adding, deleting, modifying and querying in this part of the project to demonstrate the usage of these APIs.

 @Override
    public void onClick(View v){
        String name,phone;//声明姓名和电话字段
        sqliteDatabase db;//声明一个数据库db
        ContentValues values;//创建values对象
        switch (v.getId()){
            case R.id.btn_add://添加数据
                name=mEtName.getText().toString();//获取字符串数据
                phone=mEtPhone.getText().toString();
                db=myHelper.getWritableDatabase();//获取可读写sqliteDatabase对象
                values=new ContentValues();//创建ContentValues值
                values.put("name",name);//将数据添加到ContentValues对象
                values.put("phone",phone);
                //参数依次是:表名,强行插入null值的数据列的列名,一行记录的数据
                db.insert("person",values);//将数据插入到表中
                Toast.makeText(this,"信息已添加",Toast.LENGTH_SHORT).show();//提示信息
                db.close();//关闭数据库
                break;
            case R.id.btn_query://查询数据
                db=myHelper.getReadableDatabase();
                //参数依次是:表名,列名,where约束条件,where中占位符提供具体的值,指定group by的列,进一步约束
                Cursor cursor=db.query("person",
                null,null);//声明并打开游标
                if(cursor.getCount()==0){//获得总的数据条数
                    mTvShow.setText(" ");
                    Toast.makeText(this,"没有数据",Toast.LENGTH_SHORT).show();
                }else {
                    cursor.moveToFirst();//指针移动到第一行,成功返回true,也说明有数据
                    mTvShow.setText("Name: "+cursor.getString(1)+
                        " ;Tel: "+cursor.getString(2));
                }
                while (cursor.moveToNext()){//指针移动到下一行,表明还有元素
                    mTvShow.append("\n"+"Name:"+cursor.getString(1)+
                        " ;Tel: "+cursor.getString(2));
                }
                cursor.close();//关闭游标
                db.close();
                break;
            case R.id.btn_update://修改数据
                db=myHelper.getReadableDatabase();
                values=new ContentValues();//要修改的数据
                values.put("phone",phone=mEtPhone.getText().toString());
                //参数依次是表名,修改后的值,where条件,以及约束,如果不指定三和四两个参数,会更改所有行
                db.update("person",values,"name=?",
                        new String[]{mEtName.getText().toString()});//更新并得到行数
                Toast.makeText(this,"信息已修改",Toast.LENGTH_SHORT).show();
                db.close();
                break;
            case R.id.btn_delete://删除数据
                db=myHelper.getWritableDatabase();
                //参数依次是表名,以及where条件与约束
                db.delete("person",null);
                Toast.makeText(this,"信息已删除",Toast.LENGTH_SHORT).show();
                mTvShow.setText(" ");
                db.close();
                break;
        }
    }

1. Run the simulator and start the application

This address book project mainly tests students' use of SQLite database, which is still relatively basic. Students who have just come into contact with Android will understand it as long as they type it once. These knowledge points will be frequently used in future Android projects. Therefore, we hope you can master the use of the above knowledge points to facilitate subsequent development projects.

Students who need source learning can pay attention to my WeChat official account. Reply: mail list, you can get source code, and many Android projects are waiting for you to learn.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>