Android簡易版圖書管理系統


這是我的代碼github地址,想要的可以自行去看看:https://github.com/nihaowoshipanq/Library

終於完工了,做了半個月,我真是太懶了,記錄一下:

准備工作:

1.虛擬器安裝搜狗輸入法,這樣虛擬器就可以輸入中文了,步驟:

①網上下載搜狗輸入法X86的安裝包(可以在以下網址下載)

http://www.mdpda.com/app/apk3670941.html

②下載好后。啟動虛擬器后直接拖下載的apk文件進去,下載好會顯示搜狗輸入法的

2.准備好軟件的圖標,為軟件設置一個好看的外觀。可以參照以下博主的帖子

https://blog.csdn.net/sinat_41924085/article/details/80514151

 

一、設置各種界面xml文件

1、activity_main.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"
    android:background="@color/cardview_light_background">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="50dp"
            android:layout_gravity="center"
            android:paddingLeft="16dp"
            android:paddingRight="16dp"
            android:text="圖書管理系統"

            android:textSize="30dp" />
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:src="@drawable/pic_logo1"/>

<!-- 用戶名子布局,水平布局,包含一個TextView控件與EditView控件   -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="5dp">

        <TextView
            android:padding="8dp"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginTop="30dp"
            android:layout_marginLeft="70dp"
            android:text="用戶名:"
            android:gravity="center"
            android:textSize="20dp"/>

        <EditText
            android:id="@+id/username_text"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="0dp"
            android:layout_marginTop="30dp"
            android:layout_marginRight="90dp"
            android:layout_weight="2"
            android:background="@drawable/eidttext_background"
            android:hint="請輸入用戶名"
            android:maxLines="1"
            android:padding="8dp" />

    </LinearLayout>

<!--    密碼子布局-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:padding="8dp"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginTop="30dp"
            android:layout_marginLeft="70dp"
            android:text="密碼:"
            android:gravity="center"
            android:textSize="20dp"/>

        <EditText
            android:padding="8dp"
            android:layout_width="0dp"
            android:layout_weight="2"
            android:layout_height="wrap_content"
            android:id="@+id/password_text"
            android:layout_marginTop="30dp"
            android:layout_marginLeft="0dp"
            android:layout_marginRight="90dp"
            android:maxLines="1"
            android:hint="請輸入密碼"
            android:background="@drawable/eidttext_background"
            android:inputType="textPassword"/>
<!--inputType是設置密碼輸入框的文本是密碼的形式,這步很關鍵-->
    </LinearLayout>

<!--    記住密碼子布局-->
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <CheckBox
            android:layout_marginTop="20dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/checkbox_text"
            android:layout_marginLeft="90dp"
            android:checked="false"
            android:text="記住密碼"
            android:textSize="12dp"/>
        <CheckBox
            android:layout_marginTop="20dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/password_checkbook"
            android:layout_marginLeft="70dp"
            android:checked="false"
            android:text="顯示密碼"
            android:textSize="12dp"
            />

    </LinearLayout>

<!--    注冊登錄按鈕子布局-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="30dp"
        android:layout_marginLeft="40dp">

<!--        注冊按鈕-->
        <Button
            android:id="@+id/register_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="60dp"

            android:backgroundTint="#000000"
            android:paddingRight="20dp"
            android:paddingLeft="20dp"
            android:textSize="20dp"
            android:textColor="@color/cardview_light_background"
            android:text="注冊"/>
<!--登錄按鈕-->
        <Button
            android:id="@+id/login_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="50dp"

            android:backgroundTint="#000000"
            android:paddingRight="20dp"
            android:paddingLeft="20dp"
            android:textSize="20dp"
            android:textColor="@color/cardview_light_background"
            android:text="登錄"/>
    </LinearLayout>



</LinearLayout>
View Code

 

 

 2.注冊界面,activity_register.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:gravity="center"
        android:layout_marginTop="70dp"
        android:text="用戶注冊"
        android:textSize="35dp"
        />
    <!-- 用戶名子布局,水平布局,包含一個TextView控件與EditView控件   -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="15dp">

        <TextView
            android:padding="8dp"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginTop="30dp"
            android:layout_marginLeft="70dp"
            android:text="用戶名:"
            android:gravity="right"
            android:textSize="20dp"/>

        <EditText
            android:id="@+id/newusername_text"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="0dp"
            android:layout_marginTop="30dp"
            android:layout_marginRight="90dp"
            android:layout_weight="2"
            android:background="@drawable/eidttext_background"
            android:hint="請輸入用戶名"
            android:maxLines="1"
            android:padding="8dp" />

    </LinearLayout>

    <!--    密碼子布局-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="15dp">

        <TextView
            android:padding="8dp"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginTop="30dp"
            android:layout_marginLeft="70dp"
            android:text="密碼:"
            android:gravity="right"
            android:textSize="20dp"/>

        <EditText
            android:padding="8dp"
            android:layout_width="0dp"
            android:layout_weight="2"
            android:layout_height="wrap_content"
            android:id="@+id/newpassword_text"
            android:layout_marginTop="30dp"
            android:layout_marginLeft="0dp"
            android:layout_marginRight="90dp"
            android:maxLines="1"
            android:hint="請輸入密碼"
            android:background="@drawable/eidttext_background"
            android:inputType="textPassword"/>
        <!--inputType是設置密碼輸入框的文本是密碼的形式,這步很關鍵-->
    </LinearLayout>
<!--    再次確認密碼-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="15dp">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="0dp"
            android:layout_marginRight="0dp"
            android:layout_marginTop="30dp"
            android:layout_weight="1"
            android:gravity="right"
            android:padding="0dp"
            android:paddingLeft="0dp"
            android:paddingRight="0dp"
            android:text="確認密碼:"
            android:textSize="20dp" />

        <EditText
            android:padding="8dp"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/new_again_password_text"
            android:layout_marginTop="30dp"
            android:layout_marginLeft="0dp"
            android:layout_marginRight="90dp"
            android:maxLines="1"
            android:hint="請再次輸入密碼"
            android:background="@drawable/eidttext_background"
            android:inputType="textPassword"/>

        <!--inputType是設置密碼輸入框的文本是密碼的形式,這步很關鍵-->
    </LinearLayout>
    <CheckBox
        android:layout_marginTop="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/new_password_checkbook"
        android:layout_marginLeft="220dp"
        android:checked="false"
        android:text="顯示密碼"
        android:textSize="12dp"
        />
<!--    注冊以及返回按鈕子布局-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="30dp"
        android:layout_marginLeft="40dp">

        <!--        注冊按鈕-->
        <Button
            android:id="@+id/yes_register_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="60dp"

            android:backgroundTint="#000000"
            android:paddingRight="20dp"
            android:paddingLeft="20dp"
            android:textSize="20dp"
            android:textColor="@color/cardview_light_background"
            android:text="注冊"/>
        <!--返回按鈕-->
        <Button
            android:id="@+id/back_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="50dp"

            android:backgroundTint="#000000"
            android:paddingRight="20dp"
            android:paddingLeft="20dp"
            android:textSize="20dp"
            android:textColor="@color/cardview_light_background"
            android:text="返回"/>
    </LinearLayout>

    <ImageView
        android:layout_width="68dp"
        android:layout_height="57dp"
        android:layout_gravity="center"
        android:layout_marginTop="90dp"
        android:src="@drawable/pic_logo1" />


</LinearLayout>
View Code

 

3.功能界面,activity_library_function.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">

    <Button
        android:id="@+id/find_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="查詢書籍"
        android:textSize="25dp"
        android:textColor="@color/cardview_light_background"
        android:background="@drawable/eidttext_background"
        android:backgroundTint="#000000"
        android:layout_marginTop="70dp"
        android:layout_gravity="center"
        android:paddingLeft="50dp"
        android:paddingRight="50dp"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"/>

    <Button
        android:id="@+id/add_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="增添書籍"
        android:textSize="25dp"
        android:textColor="@color/cardview_light_background"
        android:background="@drawable/eidttext_background"
        android:backgroundTint="#000000"
        android:layout_marginTop="70dp"
        android:layout_gravity="center"
        android:paddingLeft="50dp"
        android:paddingRight="50dp"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"/>

    <Button
        android:id="@+id/alter_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="修改書籍"
        android:textSize="25dp"
        android:textColor="@color/cardview_light_background"
        android:background="@drawable/eidttext_background"
        android:backgroundTint="#000000"
        android:layout_marginTop="70dp"
        android:layout_gravity="center"
        android:paddingLeft="50dp"
        android:paddingRight="50dp"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"/>

    <Button
        android:id="@+id/cancel_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="刪除書籍"
        android:textSize="25dp"
        android:textColor="@color/cardview_light_background"
        android:background="@drawable/eidttext_background"
        android:backgroundTint="#000000"
        android:layout_marginTop="70dp"
        android:layout_gravity="center"
        android:paddingLeft="50dp"
        android:paddingRight="50dp"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"/>



</LinearLayout>
View Code

 

 

4.查詢書籍頁面,find.xml

 

 

 代碼:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="300dp"
    android:layout_height="match_parent"
    android:background="@drawable/eidttext_background"
    android:backgroundTint="@color/cardview_light_background">

    <!--    書籍名稱子布局-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="15dp">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="right"
            android:text="書籍名稱:"
            android:textSize="20dp"
            android:textColor="#000000"

            />
        <EditText
            android:id="@+id/find_bookname_text"
            android:layout_width="0dp"
            android:layout_height="35dp"
            android:layout_weight="1"
            android:layout_marginRight="20dp"
            android:background="@drawable/eidttext_background"
            android:layout_gravity="center"
            android:textColor="#000000"
            />
    </LinearLayout>

    <!--    操作結果文本框-->
    <EditText
        android:id="@+id/find_result_text"
        android:layout_width="250dp"
        android:layout_height="90dp"
        android:layout_marginTop="15dp"
        android:layout_gravity="center"
        android:textColor="#000000"
        android:background="@drawable/eidttext_background"/>

    <!--    確定以及取消按鈕-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="20dp"
        android:gravity="center"
        >

        <!--        確定按鈕-->
        <Button
            android:id="@+id/find_yes_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:backgroundTint="#000000"
            android:paddingRight="10dp"
            android:paddingLeft="10dp"
            android:textSize="15dp"
            android:textColor="@color/cardview_light_background"
            android:text="確定"/>
        <!--登錄按鈕-->
        <Button
            android:id="@+id/find_no_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:backgroundTint="#000000"
            android:paddingRight="10dp"
            android:paddingLeft="10dp"
            android:textSize="15dp"
            android:textColor="@color/cardview_light_background"
            android:text="取消"/>
    </LinearLayout>
</LinearLayout>
View Code

 

5.增添書籍頁面,activity_dialog.xml

 

 

 代碼:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="300dp"
    android:layout_height="match_parent"
    android:background="@drawable/eidttext_background"
    android:backgroundTint="@color/cardview_light_background">

<!--    書籍名稱子布局-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="15dp">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="right"
            android:text="書籍名稱:"
            android:textSize="20dp"
            android:textColor="#000000"

            />
        <EditText
            android:id="@+id/add_bookname_text"
            android:layout_width="0dp"
            android:layout_height="35dp"
            android:layout_weight="1"
            android:layout_marginRight="20dp"
            android:background="@drawable/eidttext_background"
            android:layout_gravity="center"
            android:textColor="#000000"
            />
    </LinearLayout>

<!--    書籍編號子布局-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="15dp">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="right"
            android:text="書籍編號:"
            android:textSize="20dp"
            android:textColor="#000000"

            />
        <EditText
            android:id="@+id/add_bookID_text"
            android:layout_width="0dp"
            android:layout_height="35dp"
            android:layout_weight="1"
            android:layout_marginRight="20dp"
            android:background="@drawable/eidttext_background"
            android:layout_gravity="center"
            android:textColor="#000000"
            android:maxLines="5"

            />
    </LinearLayout>

<!--    書籍價格子布局-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="15dp">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="right"
            android:text="書籍價格:"
            android:textSize="20dp"
            android:textColor="#000000"

            />
        <EditText
            android:id="@+id/add_bookPrice_text"
            android:layout_width="0dp"
            android:layout_height="35dp"
            android:layout_weight="1"
            android:layout_marginRight="20dp"
            android:background="@drawable/eidttext_background"
            android:layout_gravity="center"
            android:textColor="#000000"

            />
    </LinearLayout>

<!--    操作結果文本框-->
    <EditText
        android:id="@+id/add_result_text"
        android:layout_width="250dp"
        android:layout_height="90dp"
        android:layout_marginTop="15dp"
        android:layout_gravity="center"
        android:background="@drawable/eidttext_background"/>

<!--    確定以及取消按鈕-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="20dp"
        android:gravity="center"
        >

        <!--        確定按鈕-->
        <Button
            android:id="@+id/add_yes_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:backgroundTint="#000000"
            android:paddingRight="10dp"
            android:paddingLeft="10dp"
            android:textSize="15dp"
            android:textColor="@color/cardview_light_background"
            android:text="確定"/>
        <!--登錄按鈕-->
        <Button
            android:id="@+id/add_no_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:backgroundTint="#000000"
            android:paddingRight="10dp"
            android:paddingLeft="10dp"
            android:textSize="15dp"
            android:textColor="@color/cardview_light_background"
            android:text="取消"/>
    </LinearLayout>

</LinearLayout>
View Code

 

6.修改書籍信息頁面,alter_activity.xml

 

 

 代碼:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="300dp"
    android:layout_height="match_parent"
    android:background="@drawable/eidttext_background"
    android:backgroundTint="@color/cardview_light_background">

    <!--    書籍名稱子布局-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="15dp"
        android:layout_gravity="center">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="right"
            android:text="原書籍名稱:"
            android:textSize="20dp"
            android:textColor="#000000"

            />
        <EditText
            android:id="@+id/alter_bookname_text"
            android:layout_width="0dp"
            android:layout_height="35dp"
            android:layout_weight="1"
            android:layout_marginRight="20dp"
            android:background="@drawable/eidttext_background"
            android:layout_gravity="center"
            android:textColor="#000000"
            />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="15dp"
        android:layout_gravity="center">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="right"
            android:text="書籍新名稱:"
            android:textSize="20dp"
            android:textColor="#000000"

            />
        <EditText
            android:id="@+id/new_alter_bookname_text"
            android:layout_width="0dp"
            android:layout_height="35dp"
            android:layout_weight="1"
            android:layout_marginRight="20dp"
            android:background="@drawable/eidttext_background"
            android:layout_gravity="center"
            android:textColor="#000000"
            />
    </LinearLayout>

    <!--    書籍編號子布局-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="15dp">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="right"
            android:text="書籍新編號:"
            android:textSize="20dp"
            android:textColor="#000000"

            />
        <EditText
            android:id="@+id/alter_bookID_text"
            android:layout_width="0dp"
            android:layout_height="35dp"
            android:layout_weight="1"
            android:layout_marginRight="20dp"
            android:background="@drawable/eidttext_background"
            android:layout_gravity="center"
            android:textColor="#000000"
            android:maxLines="5"

            />
    </LinearLayout>

    <!--    書籍價格子布局-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="15dp">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="right"
            android:text="書籍新價格:"
            android:textSize="20dp"
            android:textColor="#000000"

            />
        <EditText
            android:id="@+id/alter_bookPrice_text"
            android:layout_width="0dp"
            android:layout_height="35dp"
            android:layout_weight="1"
            android:layout_marginRight="20dp"
            android:background="@drawable/eidttext_background"
            android:layout_gravity="center"
            android:textColor="#000000"

            />
    </LinearLayout>

    <!--    操作結果文本框-->
    <EditText
        android:id="@+id/alter_result_text"
        android:layout_width="250dp"
        android:layout_height="90dp"
        android:layout_marginTop="15dp"
        android:layout_gravity="center"
        android:textColor="#000000"
        android:background="@drawable/eidttext_background"/>

    <!--    確定以及取消按鈕-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="20dp"
        android:gravity="center"
        >

        <!--        確定按鈕-->
        <Button
            android:id="@+id/alter_yes_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:backgroundTint="#000000"
            android:paddingRight="10dp"
            android:paddingLeft="10dp"
            android:textSize="15dp"
            android:textColor="@color/cardview_light_background"
            android:text="確定"/>
        <!--登錄按鈕-->
        <Button
            android:id="@+id/alter_no_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:backgroundTint="#000000"
            android:paddingRight="10dp"
            android:paddingLeft="10dp"
            android:textSize="15dp"
            android:textColor="@color/cardview_light_background"
            android:text="取消"/>
    </LinearLayout>

</LinearLayout>
View Code

 

7.刪除書籍信息頁面,cancel_activity.xml

 

 

 代碼:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="300dp"
    android:layout_height="match_parent"
    android:background="@drawable/eidttext_background"
    android:backgroundTint="@color/cardview_light_background">

    <!--    書籍名稱子布局-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="15dp">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="right"
            android:text="書籍名稱:"
            android:textSize="20dp"
            android:textColor="#000000"

            />
        <EditText
            android:id="@+id/cancel_bookname_text"
            android:layout_width="0dp"
            android:layout_height="35dp"
            android:layout_weight="1"
            android:layout_marginRight="20dp"
            android:background="@drawable/eidttext_background"
            android:layout_gravity="center"
            android:textColor="#000000"
            />
    </LinearLayout>

    <!--    書籍編號子布局-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="15dp">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="right"
            android:text="書籍編號:"
            android:textSize="20dp"
            android:textColor="#000000"

            />
        <EditText
            android:id="@+id/cancel_bookID_text"
            android:layout_width="0dp"
            android:layout_height="35dp"
            android:layout_weight="1"
            android:layout_marginRight="20dp"
            android:background="@drawable/eidttext_background"
            android:layout_gravity="center"
            android:textColor="#000000"
            android:maxLines="5"

            />
    </LinearLayout>
    <!--    操作結果文本框-->
    <EditText
        android:id="@+id/cancel_result_text"
        android:layout_width="250dp"
        android:layout_height="90dp"
        android:layout_marginTop="15dp"
        android:layout_gravity="center"
        android:textColor="#000000"
        android:background="@drawable/eidttext_background"/>

    <!--    確定以及取消按鈕-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="20dp"
        android:gravity="center"
        >

        <!--        確定按鈕-->
        <Button
            android:id="@+id/cancel_yes_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:backgroundTint="#000000"
            android:paddingRight="10dp"
            android:paddingLeft="10dp"
            android:textSize="15dp"
            android:textColor="@color/cardview_light_background"
            android:text="確定"/>
        <!--登錄按鈕-->
        <Button
            android:id="@+id/cancel_no_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:backgroundTint="#000000"
            android:paddingRight="10dp"
            android:paddingLeft="10dp"
            android:textSize="15dp"
            android:textColor="@color/cardview_light_background"
            android:text="取消"/>
    </LinearLayout>
</LinearLayout>
View Code

 

注意:上面的四個功能頁面都是采用了對話框式的活動,所以要在AndroidManist.xml文件中每個活動里加入一句:android:theme="@style/Theme.AppCompat.Dialog"

AndroidManist.xml代碼:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.library">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".cancel"
            android:theme="@style/Theme.AppCompat.Dialog"></activity>
        <activity
            android:name=".find"
            android:theme="@style/Theme.AppCompat.Dialog"></activity>
        <activity
            android:name=".Alter_activity"
            android:theme="@style/Theme.AppCompat.Dialog" />
        <activity
            android:name=".Dialog_Activity"
            android:theme="@style/Theme.AppCompat.Dialog" />
        <activity android:name=".Library_function" />
        <activity android:name=".RegisterActivity" />
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>
View Code

 

二、java代碼

1.MainActivity.java

package com.example.library;

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

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private  EditText username; //用戶名輸入框
    private  EditText password; //密碼輸入框
    private Button LoginButton; //登錄按鈕
    private Button  RegisterButton; //注冊按鈕
    private CheckBox passwordCheck; //顯示密碼復選框
//    private EditText new_username;//注冊頁面的用戶名輸入框
//    private EditText new_password;//注冊頁面的密碼輸入框
//    private EditText new_again_password;//注冊頁面的再次輸入密碼框

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE" };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        verifyStoragePermissions(this);
        initialize(); //初始化各種控件
        ischeck(passwordCheck); //設置密碼顯示或不顯示
        LoginButton.setOnClickListener(this);
        RegisterButton.setOnClickListener(this);




    }
    /**
     * 初始化控件
     */
    private void initialize(){
        username=(EditText)findViewById(R.id.username_text); //創建用戶名輸入框對象
        password=(EditText)findViewById(R.id.password_text); //創建密碼輸入框對象
        RegisterButton=(Button)findViewById(R.id.register_button); //創建注冊按鈕對象
        LoginButton =(Button)findViewById(R.id.login_button);  //創建登錄按鈕對象
        passwordCheck=(CheckBox)findViewById(R.id.password_checkbook); //創建顯示密碼復選框對象
    }

    /**
     * 設置顯示密碼的點擊操作
     *
     */
    private void ischeck(CheckBox passwordCheck){
        passwordCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    //顯示明文,即設置為可見的密碼
                    password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                }else{
                    //不顯示明文,即設置為不可見的密碼
                    password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
            }
        });
    }

    /**
     * 點擊登錄或注冊按鈕時觸發的點擊事件
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.login_button://登錄的點擊事件
                login();
                break;
            case R.id.register_button://注冊的點擊事件
                //點擊注冊按鈕時轉去第二個活動頁面
                Intent intent=new Intent(MainActivity.this,RegisterActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }
    /**
     * 登錄
     */
    private  void login()  {
        //獲取輸入的用戶名與密碼
        String usernametext=username.getText().toString().trim();
        String passwordtext=password.getText().toString().trim();
        //System.out.println(usernametext+" "+passwordtext);
        //定義用戶名和密碼規則
        String usernameregex = "[a-zA-Z]{5}";
        String passwordregex = "[0-9]{5}";
        //校驗用戶名
        if (!(usernametext.matches(usernameregex))) {
           // JOptionPane.showMessageDialog(this, "用戶名格式不對,請輸入5位單詞字母)");
//            new AlertDialog.Builder(MainActivity.this)
//                    .setTitle("error").setMessage("用戶名格式不對,請輸入5位單詞字母")
//                    .setPositiveButton("好的",null).show();
            Toast.makeText(MainActivity.this,"用戶名格式不對,請輸入5位單詞字母",Toast.LENGTH_LONG).show();
            //清空用戶名框文本,並把輸入光標放回到輸入框
            this.username.setText("");
            this.username.requestFocus();
            return;
        }
        //校驗密碼
        if (!(passwordtext.matches(passwordregex))) {
            //JOptionPane.showMessageDialog(this, "密碼格式不對,請輸入6-12位任意字符)");
            Toast.makeText(MainActivity.this,"密碼格式不正確,請輸入6-12位任意字符",Toast.LENGTH_LONG).show();
//              new AlertDialog.Builder(MainActivity.this)
//                      .setTitle("error").setMessage("密碼格式不正確,請輸入6-12位任意字符")
//                      .setPositiveButton("好的",null).show();
//
            //清空用戶名框文本,並把輸入光標放回到輸入框
            this.password.setText("");
            this.username.requestFocus();
            return;
        }

        //調用登錄功能
        UserDaoImpl loginImpl=new UserDaoImpl();
        boolean flag=loginImpl.isloging(this,usernametext,passwordtext);
        if(!flag){
            //如果登錄不成功
            Toast.makeText(MainActivity.this,"用戶名或密碼錯誤",Toast.LENGTH_LONG).show();
            //將用戶名框與密碼框清空,並把光標放回框中
            this.username.setText("");
            this.password.setText("");
            this.username.requestFocus();
            this.password.requestFocus();

        }else{
            //登錄成功
            Toast.makeText(MainActivity.this,"登錄成功",Toast.LENGTH_LONG).show();
            Intent intent=new Intent(MainActivity.this,Library_function.class);
            startActivity(intent);

        }
    }


    private void openPerssion() {
        verifyStoragePermissions(this);
    }

    /**
     * @des 權限組的獲取
     * @author DELL
     * @time  10:44
     */
    public void verifyStoragePermissions(Activity activity) {
        try {
            //檢測是否有寫的權限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 沒有寫的權限,去申請寫的權限,會彈出對話框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
View Code

 

2.User.java:用戶信息類

package com.example.library;

/**
 *
 * @author Asus
 */
public class User {
    private String username;//用戶名
    private String password;//用戶密碼
    public User(){}

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }


}
View Code

 

3.UserDao.java:登錄注冊功能接口

package com.example.library;


import android.content.Context;

import java.io.FileNotFoundException;

/**
 *這是一個用戶登錄注冊接口
 * @author Asus
 */
public interface UserDao {
    /**
     * 這是判斷登錄是否成功的方法
     * @param username 用戶名
     * @param password 用戶的密碼
     * @return  用戶是否登錄成功
     */
    public abstract boolean isloging(Context context,String username, String password) ;
    /**
     * 這是注冊方法
     *
     */
    public abstract boolean register(Context context,User user);

}
View Code

 

4.UserDaoImpl.java:登錄注冊實現類

package com.example.library;


import android.content.Context;
import android.content.res.Resources;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;

import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Properties;
import java.util.Set;

/**
 * 用戶登錄注冊功能實現類
 *
 * @author Asus
 */
public class UserDaoImpl implements UserDao {

    private static File sdpath= Environment.getExternalStorageDirectory();
    private  static File  myfile=new File(sdpath,"panq.txt");


    //創建類的時候就創建文件
    static {
        try {
            if(myfile.exists())
                System.out.println("文件已存在");
            else{
                myfile.createNewFile();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

    /**
     * 登錄功能
     * @param context Activity的上面的某一層是Context,所以傳值過來的是一個Activity,此處可以寫成Context
     * @param username 用戶名
     * @param password 用戶的密碼
     * @return
     */
    @Override
    public boolean isloging(Context context,String username, String password)  {
        boolean flag =false;//判斷是否登錄成功
        BufferedReader br = null;
        try{
            //讀取文件信息,看用戶名與密碼是否匹配
            br = new BufferedReader(new FileReader(myfile));
            String line = null;
            while ((line = br.readLine()) != null) {
                String[] date = line.split("=");
                System.out.println("用戶名:"+date[0]+",密碼:"+date[1]);
                if (date[0].equals(username) && date[1].equals(password)) {
                    //信息匹配,登錄成功
                        flag = true;
                        break;
                }
            }
        }catch (Exception e1){
            e1.printStackTrace();
        }finally {
            if (br != null) {
                try {
                    br.close();

                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        }
        return flag;
    }

    /**
     *
     * @param context Activity的上面的某一層是Context,所以傳值過來的是一個Activity,此處可以寫成Context
     * @param user 用戶信息
     * @return
     */
    @Override
    public boolean register(Context context,User user) {
        BufferedWriter bw=null;
        BufferedReader br=null;
        boolean isregister=false;//判斷是否注冊成功
        try{
            //先讀取文件,查看用戶名是否已注冊
            br=new BufferedReader(new FileReader(myfile));
            boolean flag=myload(user.getUsername());//通過myload函數判斷用戶名是否已存在
            if(!flag){
                //用戶名不存在,即可以使用該用戶名,注冊成功
                isregister=true;
                //把用戶信息寫到文件中
                bw=new BufferedWriter(new FileWriter(myfile,true));
                bw.write(user.getUsername()+"="+user.getPassword());
                bw.newLine();
                bw.flush();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (br!=null&bw != null) {
                try {
                    bw.close();
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        }
        return isregister;
    }
    /**
     * 判斷用戶名是否已存在
     * @param username 用戶注冊時輸入的用戶名
     * @return
     * @throws IOException
     */
    private boolean myload(String username) throws IOException {
        boolean flag = false;
        Properties p = new Properties();
        BufferedReader br = new BufferedReader(new FileReader(myfile));
        p.load(br);
        br.close();
        Set<String> key = p.stringPropertyNames();//獲取所有已注冊的用戶名
        for (String user : key) {
            if (username.equals(user)) {
                flag = true;
                break;
            }
        }
        return flag;
    }

}
View Code

 

5.RegisetrActivity.java:注冊功能的活動代碼

package com.example.library;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{
    private EditText new_username;//注冊頁面的用戶名輸入框
    private EditText new_password;//注冊頁面的密碼輸入框
    private EditText new_again_password;//注冊頁面的再次輸入密碼框
    private Button new_register;//注冊按鈕
    private Button back;//返回按鈕
    private CheckBox ispassword;//顯示密碼按鈕
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        init();//初始化控件
        ischeck(ispassword);
        new_register.setOnClickListener(this);
        back.setOnClickListener(this);


    }

    /**
     * 初始化控件
     */
    private void init() {
        new_username=(EditText)findViewById(R.id.newusername_text);//創建注冊頁面的用戶名輸入框對象
        new_password=(EditText)findViewById(R.id.newpassword_text);//創建注冊頁面的密碼輸入框對象
        new_again_password=(EditText)findViewById(R.id.new_again_password_text);//創建注冊頁面的再次確認密碼輸入框對象
        new_register=(Button)findViewById(R.id.yes_register_button);//創建注冊按鈕對象
        back=(Button)findViewById(R.id.back_button);//創建返回按鈕對象
        ispassword=(CheckBox)findViewById(R.id.new_password_checkbook);//創建顯示密碼按鈕對象
    }
    private void register(){
        //獲取輸入的用戶名與密碼
        String usernametext=new_username.getText().toString().trim();
        String passwordtext=new_password.getText().toString().trim();
        //定義用戶名和密碼規則
        String usernameregex = "[a-zA-Z]{5}";
        String passwordregex = "[0-9]{5}";
        //校驗用戶名
            if (!(usernametext.matches(usernameregex))) {
            // JOptionPane.showMessageDialog(this, "用戶名格式不對,請輸入5位單詞字母)");
    //            new AlertDialog.Builder(MainActivity.this)
    //                    .setTitle("error").setMessage("用戶名格式不對,請輸入5位單詞字母")
    //                    .setPositiveButton("好的",null).show();
            Toast.makeText(RegisterActivity.this,"用戶名格式不對,請輸入5位單詞字母",Toast.LENGTH_LONG).show();
            //清空用戶名框文本,並把輸入光標放回到輸入框
            this.new_username.setText("");
            this.new_username.requestFocus();
            return;
        }
        //校驗密碼
            if (!(passwordtext.matches(passwordregex))) {
            //JOptionPane.showMessageDialog(this, "密碼格式不對,請輸入6-12位任意字符)");
            Toast.makeText(RegisterActivity.this,"密碼格式不正確,請輸入6-12位任意字符",Toast.LENGTH_LONG).show();
    //              new AlertDialog.Builder(MainActivity.this)
    //                      .setTitle("error").setMessage("密碼格式不正確,請輸入6-12位任意字符")
    //                      .setPositiveButton("好的",null).show();
    //
            //清空用戶名框文本,並把輸入光標放回到輸入框
            this.new_password.setText("");
            this.new_password.requestFocus();
            return;
        }
        //校驗兩次輸入的密碼是否一致
        String again_password=new_again_password.getText().toString().trim();
            if(!again_password.equals(new_password)){
            Toast.makeText(RegisterActivity.this,"密碼不一致",Toast.LENGTH_LONG).show();
        }
        //調用注冊功能
        User user=new User(usernametext,passwordtext);
        UserDaoImpl loginImpl=new UserDaoImpl();
        boolean result=loginImpl.register(this,user);//判斷是否注冊成功
        if(result){
            Toast.makeText(RegisterActivity.this,"注冊成功",Toast.LENGTH_LONG).show();
        }else {
                Toast.makeText(RegisterActivity.this, "用戶名已存在", Toast.LENGTH_LONG).show();
                //清空用戶名框文本,並把輸入光標放回到輸入框
                this.new_username.setText("");
                this.new_username.requestFocus();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.yes_register_button:
                register();//校驗輸入的用戶名與密碼
                break;
            case R.id.back_button:
                Intent intent=new Intent(RegisterActivity.this,MainActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }
    /**
     * 設置顯示密碼的點擊操作
     *
     */
    private void ischeck(CheckBox passwordCheck){
        passwordCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    //顯示明文,即設置為可見的密碼
                    new_password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    new_again_password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                }else{
                    //不顯示明文,即設置為不可見的密碼
                    new_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    new_again_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
            }
        });
    }
}
View Code

 

6.Library_function.java:圖書館功能活動代碼

package com.example.library;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Library_function extends AppCompatActivity implements View.OnClickListener {
    private Button addButton;//增添書籍按鈕
    private Button findButton;//查詢書籍按鈕
    private Button alterButton;//修改書籍信息按鈕
    private Button cancelButton;//刪除書籍按鈕
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_library_function);
        init();
        addButton.setOnClickListener(this);
        alterButton.setOnClickListener(this);
        findButton.setOnClickListener(this);
        cancelButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.add_button:
                Intent intent1=new Intent(Library_function.this,Dialog_Activity.class);
                startActivity(intent1);
                break;
            case R.id.find_button:
                Intent intent3=new Intent(Library_function.this,find.class);
                startActivity(intent3);
                break;
            case R.id.alter_button:
                Intent intent2=new Intent(Library_function.this,Alter_activity.class);
                startActivity(intent2);
                break;
            case R.id.cancel_button:
                Intent intent4=new Intent(Library_function.this,cancel.class);
                startActivity(intent4);
                break;
            default:
                break;
        }

    }
    private void init(){
        addButton=(Button)findViewById(R.id.add_button);
        findButton=(Button)findViewById(R.id.find_button);
        alterButton=(Button)findViewById(R.id.alter_button);
        cancelButton=(Button)findViewById(R.id.cancel_button);
    }
}
View Code

 

7.Book.java:書籍的信息類

package com.example.library;

public class Book {
    private String ID;//書的編號
    private String Name;//書名
    private String price;//書的價格


    public  Book() {
        super();
    }
    public Book(String iD, String name, String price) {
        super();
        ID = iD;
        Name = name;
        this.price = price;
    }

    public String getID() {
        return ID;
    }
    public void setID(String iD) {
        ID = iD;
    }
    public String getName() {
        return Name;
    }
    public void setName(String name) {
        Name = name;
    }
    public String getPrice() {
        return price;
    }
    public void setPrice(String price) {
        this.price = price;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Book other = (Book) obj;
        if (ID == null) {
            if (other.ID != null)
                return false;
        } else if (!ID.equals(other.ID))
            return false;
        if (Name == null) {
            if (other.Name != null)
                return false;
        } else if (!Name.equals(other.Name))
            return false;
        if (price == null) {
            if (other.price != null)
                return false;
        } else if (!price.equals(other.price))
            return false;
        return true;
    }
    @Override
    public String toString() {
        return "Book [ID=" + ID + ", Name=" + Name + ", price=" + price + "]";
    }
}
View Code

 

8.BookDao.java:圖書管理系統的4個功能接口

package com.example.library;

/**
 * 圖書管理系統功能的接口
 * 2020.04.26
 */
interface BookDao {
    public void addBook(Book book);//增添書籍

    public String findBook(String bookName);//查詢書籍

    public boolean alterBook(String BookName,String newstr);//修改書籍內容

    public void cancelBook(String bookName,String ID);//刪除書籍
}
View Code

 

9.BookDaoImpl.java:功能實現類

package com.example.library;

import android.os.Environment;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 圖書管理系統的功能實現類
 */
public class BookDaoImpl implements BookDao{
    private static File sdpath= Environment.getExternalStorageDirectory();
    private  static File  file=new File(sdpath,"Library.txt");
    private  static File  file1=new File(sdpath,"temp.txt");

    //創建類的時候就創建文件
    static {
        try {
            if(file.exists()&file1.exists())
                System.out.println("文件已存在");
            else{
                file1.createNewFile();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }
    /**
     * 增添書籍
     * @param book 書的信息
     */
    @Override
    public void addBook(Book book) {
        BufferedWriter bw=null;
        BufferedReader br=null;

        try {
            bw=new BufferedWriter(new FileWriter(file,true));//true代表將數據寫入文件末尾處,而不是文件開始處
            br=new BufferedReader(new FileReader(file));
            String line=null;
            if((line=br.readLine())!=null){
                //如果文件第一行不是空,即文件已經有內容
                bw.write("\r\n");//因為文件最后一行的末尾沒有回車換行符,如果不先加回車換行符,就會直接在最后一行寫,不會新增一行
                bw.write(book.getID()+"-"+book.getName()+"-"+book.getPrice());
                bw.flush();
            }else{//如果文件第一行為空,即文件沒有內容
                bw.write(book.getID()+"-"+book.getName()+"-"+book.getPrice());
                bw.flush();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(bw!=null&br!=null) {
                try {
                    bw.close();
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 查詢書籍
     * @param bookName 要查詢的書籍名稱
     */
    @Override
    public String findBook(String bookName) {
        BufferedReader br=null;
        String result=null;
        try {

            br=new BufferedReader(new FileReader(file));
            String readLine = "";
            while((readLine = br.readLine()) != null){
                String list[]=readLine.split("-");
                if(readLine.contains(bookName)) {
                    result="ID:"+list[0]+"\n書名:"+list[1]+"\n價格:"+list[2];
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(br!=null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;


    }

    /**
     * 修改書籍信息
     * @param oldName 要修改的書籍名稱
     * @param buffer  修改后的書籍全部信息,包括編號、書名、書的價格
     * @return
     */
    @Override
    public boolean alterBook(String oldName, String buffer) {
        RandomAccessFile raf=null;
        try {
            raf=new RandomAccessFile(file, "rw");
            String Line=null;

            while((Line=raf.readLine())!=null) {
                //RandomAccessFile 讀寫文件時,不管文件中保存的數據編碼格式是什么
                // 使用 RandomAccessFile對象方法的 readLine() 都會將編碼格式轉換成 ISO-8859-1
                // 所以 輸出顯示是還要在進行一次轉碼
                String changeLine=new String(Line.getBytes("ISO-8859-1"), "utf-8");
                //查找要替換的內容
                if(changeLine.contains(oldName)) {
                    //得到當前指針的位置,如果不是最后一行,就應該是在oldName\r\n后面;
                    //如果是最后一行,則就在oldName后面
                    long lastpoint=raf.getFilePointer();

                    //如果是最后一行
                    if(lastpoint==raf.length()) {
                        //指針回到行首
                        raf.seek(lastpoint-changeLine.getBytes().length);
                        int currentLength=changeLine.getBytes().length;//原字符串的字節長度,1個中文字符占2字節
                        int targeLength=buffer.getBytes().length;//替換后字符串的字節長度

                        //替換的字符串字節數比源字符串小
                        if(currentLength>targeLength) {
                            int tempLength=currentLength-targeLength;
                            StringBuilder sb=new StringBuilder(buffer);
                            //目的是防止修改的內容沒有沒全替換掉

                            for(int a=0;a<tempLength;a++) {
                                sb.append(" ");
                            }
                            raf.writeBytes(new String(sb.toString().getBytes("utf-8"), "ISO-8859-1"));
                        }else {
                            //替換的字符串字節數比源字符串大或兩者相等
                            raf.writeBytes(new String(buffer.getBytes("utf-8"), "ISO-8859-1"));

                        }
                    }else {//不是最后一行
                        //回到行首,減去2的原因是行末有\r\n,占2字節
                        raf.seek(lastpoint-changeLine.getBytes().length-2);
                        int currentLength=changeLine.getBytes().length;//原字符串的長度
                        int targeLength=buffer.getBytes().length;//替換后字符串的長度
                        //替換的字符串字節數比源字符串小,目的是防止修改的內容沒有沒全替換掉
                        if(currentLength>targeLength) {
                            int tempLength=currentLength-targeLength;
                            StringBuilder sb=new StringBuilder(buffer);
                            //源字符串沒替換的字符用空格代替
                            for(int a=0;a<tempLength;a++) {
                                sb.append(" ");
                            }

                            raf.writeBytes(new String(sb.toString().getBytes("utf-8"), "ISO-8859-1"));
                        }else {
                            //替換的字符串比源字符串大或兩者相等
                            raf.writeBytes(new String(buffer.getBytes("utf-8"), "ISO-8859-1"));
                        }

                    }
                    break;
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(raf!=null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;


    }

    /**
     * 刪除書籍
     * @param bookName 要刪除的書籍名稱
     * @param ID 要刪除的書籍編號
     */
    @Override
    public void cancelBook(String bookName, String ID) {
        boolean flag=false;
        BufferedWriter bw=null;
        BufferedReader br=null;
        StringBuilder sb=null;
        try {
            bw=new BufferedWriter(new FileWriter(file1));
            br=new BufferedReader(new FileReader(file));
            String line=null;
            sb=new StringBuilder();
            while((line=br.readLine())!=null) {
                //要刪除的那一行
                if (line.contains(bookName)) {
                    String[] data = line.split("-");//將書籍編號、書籍名、書籍價格存在數組中
                    if (!ID.equals(data[0]))
                        System.out.println("輸入編號不正確");
                    else {
                        //如果刪除的書籍信息都匹配成功
                        flag = true;

                    }
                }else {//不是要刪除的那一行
                    sb.append(line).append("\r\n");//存儲沒有被刪的書籍信息到字符串sb中
                }
            }
            int lastindex=sb.lastIndexOf("\r\n");//獲取最后一行書籍信息的回車換行符索引
            sb.delete(lastindex,sb.length());//刪除最后一行書籍信息的回車換行符

            //如果輸入的刪除信息都匹配成功,就開始刪除信息
            if(flag) {
                bw.write(sb.toString());//將字符串寫進新的文件中
                //重命名文件必須先關閉流
                bw.close();
                br.close();
                if(file.delete())//重命名前必須刪除同名文件
                    file1.renameTo(file);

            }

        }catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(br!=null&bw!=null) {
                try {
                    bw.close();
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
View Code

 

10.Dialog_Activity.java:增添書籍功能代碼

package com.example.library;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewParent;
import android.widget.Button;
import android.widget.EditText;

public class Dialog_Activity extends AppCompatActivity implements View.OnClickListener{
    private EditText name;//書名文本框
    private EditText ID;//書的編號文本框
    private EditText price;//價格文本框
    private EditText result;//操作結果文本框
    private Button yes_button;//確定文本框
    private Button no_button;//取消文本框
    private BookDaoImpl impl=new BookDaoImpl();//創建實現類
    private Book book;//創建書類對象

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dialog_);
        setTitle("增添書籍");//設置標題
        init();//控件初始化
        yes_button.setOnClickListener(this);
        no_button.setOnClickListener(this);
    }

    /**
     * 初始化各種控件
     */
    private void init(){
        name=(EditText)findViewById(R.id.add_bookname_text);
        ID=(EditText)findViewById(R.id.add_bookID_text);
        price=(EditText)findViewById(R.id.add_bookPrice_text);
        yes_button=(Button)findViewById(R.id.add_yes_button);
        no_button=(Button)findViewById(R.id.add_no_button);
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.add_yes_button:
                getResult();
                break;
            case R.id.add_no_button:
                Intent intent=new Intent(Dialog_Activity.this,Library_function.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    /**
     * 操作的類
     * @param
     */
    private void getResult() {

        String bookname=this.name.getText().toString().trim();//獲取用戶鍵盤錄入的書名
        String bookid=this.ID.getText().toString().trim();//獲取用戶鍵盤錄入編號
        String bookprice=this.price.getText().toString().trim();//獲取用戶鍵盤錄入的價格
        book=new Book(bookid,bookname,bookprice);//將書籍信息放到Book類中
        //調用書籍添加功能
        impl.addBook(book);






    }


}
View Code

 

11.find.java:查詢書籍信息功能代碼

package com.example.library;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class find extends AppCompatActivity implements View.OnClickListener {
    private EditText findBookName;
    private EditText findResult;
    private Button find_yes;
    private Button find_no;
    private BookDaoImpl find_impl;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find);
        setTitle("查詢書籍");
        init();
        find_yes.setOnClickListener(this);
        find_no.setOnClickListener(this);

    }

    private void init() {
        findBookName=(EditText)findViewById(R.id.find_bookname_text);
        findResult=(EditText)findViewById(R.id.find_result_text);
        find_yes=(Button)findViewById(R.id.find_yes_button);
        find_no=(Button)findViewById(R.id.find_no_button);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.find_yes_button:
                getresult();
                break;
            case R.id.find_no_button:
                Intent intent=new Intent(find.this,Library_function.class);
                startActivity(intent);
                break;
            default:
                break;
        }

    }

    private void getresult() {
        String find_Bookname=this.findBookName.getText().toString().trim();
        System.out.println(find_Bookname);
        find_impl=new BookDaoImpl();
        String result=find_impl.findBook(find_Bookname);
        System.out.println(result);
        if(result==null){
            this.findResult.setText("無查詢結果.");

        }else{
            this.findResult.setText(result);
        }
    }
}
View Code

 

12.alter_activity:修改書籍信息功能代碼

package com.example.library;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class Alter_activity extends AppCompatActivity implements View.OnClickListener{

    private EditText alter_name;//原書名文本框
    private EditText alter_new_name;//新書名文本框
    private EditText alter_ID;//書的新編號文本框
    private EditText alter_price;//新價格文本框
    private EditText alter_result;//操作結果文本框
    private Button alter_yes_button;//確定文本框
    private Button alter_no_button;//取消文本框
    private BookDaoImpl alter_impl=new BookDaoImpl();//創建實現類


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alter_activity);
        setTitle("修改書籍");//設置標題
        init();//控件初始化
        alter_yes_button.setOnClickListener(this);
        alter_no_button.setOnClickListener(this);
    }

    /**
     * 初始化各種控件
     */
    private void init(){
        alter_name=(EditText)findViewById(R.id.alter_bookname_text);
        alter_new_name=(EditText)findViewById(R.id.new_alter_bookname_text);
        alter_ID=(EditText)findViewById(R.id.alter_bookID_text);
        alter_price=(EditText)findViewById(R.id.alter_bookPrice_text);
        alter_result=(EditText)findViewById(R.id.alter_result_text) ;
        alter_yes_button=(Button)findViewById(R.id.alter_yes_button);
        alter_no_button=(Button)findViewById(R.id.alter_no_button);
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.alter_yes_button:
                getResult();
                break;
            case R.id.alter_no_button:

                break;
            default:
                break;
        }
    }

    /**
     * 操作的類
     * @param
     */
    private void getResult() {

        String bookname=this.alter_name.getText().toString().trim();//獲取用戶鍵盤錄入的書名
        String newbookname=this.alter_new_name.getText().toString().trim();//獲取用戶輸入的新書名
        String bookid=this.alter_ID.getText().toString().trim();//獲取用戶輸入的新編號
        String bookprice=this.alter_price.getText().toString().trim();//獲取用戶鍵盤錄入的價格
        String buffer=bookid+'-'+newbookname+'-'+bookprice;
        //調用修改功能
        alter_impl.alterBook(bookname,buffer);
        this.alter_result.setText("修改成功");

    }


}
View Code

 

13.cancel.java:刪除書籍信息功能代碼

package com.example.library;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class cancel extends AppCompatActivity implements View.OnClickListener{
    private EditText cancelBookName;
    private EditText cancelID;
    private EditText cancelRecult;
    private Button cancel_yes;
    private Button cancel_no;
    private BookDaoImpl cancelImpl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cancel);
        setTitle("刪除書籍");
        init();
        cancel_yes.setOnClickListener(this);
        cancel_no.setOnClickListener(this);


    }

    private void init() {
        cancelBookName=(EditText)findViewById(R.id.cancel_bookname_text);
        cancelID=(EditText)findViewById(R.id.cancel_bookID_text);
        cancelRecult=(EditText)findViewById(R.id.cancel_result_text);
        cancel_yes=(Button)findViewById(R.id.cancel_yes_button);
        cancel_no=(Button)findViewById(R.id.cancel_no_button);
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.cancel_yes_button:
                getResult();
                break;
            case R.id.cancel_no_button:
                Intent intent=new Intent(cancel.this,Library_function.class);
                startActivity(intent);
                break;
        }

    }

    private void getResult() {

        String cancel_bookName=this.cancelBookName.getText().toString().trim();
        String cancel_ID=this.cancelID.getText().toString().trim();
        cancelImpl=new BookDaoImpl();
        cancelImpl.cancelBook(cancel_bookName,cancel_ID);
        this.cancelRecult.setText("刪除成功");
    }
}
View Code

 

最后:其實過程不難,只是要有耐心,遇到難題要一步步去解決,現在只是txt文件去記錄書籍信息,希望這個月可以完成安卓與數據庫結合的圖書管理系統。

代碼我已經放到github上了,大家可以不用問我,直接去github下載就行,網址在文章開頭。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM