SQLite 和 SQLiteDatabase 的使用

news2024/9/21 18:58:01

实验七:SQLite 和 SQLiteDatabase 的使用

7.1 实验目的

本次实验的目的是让大家熟悉 Android 中对数据库进行操作的相关的接口、类等。SQLiteDatabase 这个是在 android 中数据库操作使用最频繁的一个类。通过它可以实现数据库的创建或打开、创建表、插入数据、删除数据、查询数据、修改数据等操作。

7.2 实验要求

  • 实现便签管理小例程。
  • 创建项目并熟悉文件目录结构
  • 实现便签增删改查功能的实验步骤

7.3 实验内容

【练习 7.1】 便签管理小例程
步骤 1: 项目结构

创建一个名为"便签管理系统"的Android项目,包含以下文件和文件夹:

  • activity_main.xml (启动窗体)
  • insertinfo.xml (新增便签窗体)
  • showinfo.xml (查看便签信息窗体)
  • manageflag.xml (便签管理窗体)
  • MainActivity.java (主活动)
  • InsertFlag.java (新增便签活动)
  • ShowInfo.java (查看便签信息活动)
  • ManageFlag.java (便签管理活动)
  • DBOpenHelper.java (数据库帮助类)
  • FlagDao.java (便签数据访问类)
  • flag.java (便签实体类)
  • AndroidManifest.xml (清单文件)
步骤 2: 配置布局文件
  1. activity_main.xml (启动窗体)

    • 包含两个按钮:btnflaginfo (查看便签信息) 和 btninsertinfo (添加便签)

      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:orientation="vertical">
      
          <LinearLayout
              android:id="@+id/linearLayout1"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:layout_weight="0.06"
              android:orientation="vertical">
      
              <RelativeLayout
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content">
      
                  <Button
                      android:id="@+id/btnflaginfo"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:text="便签信息"
                      android:textColor="#8C6931"
                      android:textSize="20dp" />
      
                  <Button
                      android:id="@+id/btninsertinfo"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:layout_toRightOf="@id/btnflaginfo"
                      android:text="添加便签"
                      android:textColor="#8C6931"
                      android:textSize="20dp" />
              </RelativeLayout>
          </LinearLayout>
      </LinearLayout>
      
  2. Insertinfo.xml (新增便签窗体)

    • 包含一个文本框 txtFlag 用于输入便签内容

    • 包含两个按钮:btnflagSave (保存) 和 btnflagCancel (取消)

      <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/itemflag"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:orientation="vertical">
      
          <LinearLayout
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:layout_weight="3"
              android:orientation="vertical">
      
              <TextView
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_gravity="center"
                  android:gravity="center_horizontal"
                  android:text="新增便签"
                  android:textColor="#000000"
                  android:textSize="40sp"
                  android:textStyle="bold" />
          </LinearLayout>
      
          <LinearLayout
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:layout_weight="1"
              android:orientation="vertical">
      
              <RelativeLayout
                  android:layout_width="fill_parent"
                  android:layout_height="fill_parent"
                  android:padding="5dp">
      
                  <TextView
                      android:id="@+id/tvFlag"
                      android:layout_width="350dp"
                      android:layout_height="wrap_content"
                      android:layout_alignParentRight="true"
                      android:text="请输入便签,最多输入 200 字"
                      android:textColor="#8C6931"
                      android:textSize="23sp" />
      
                  <EditText
                      android:id="@+id/txtFlag"
                      android:layout_width="350dp"
                      android:layout_height="400dp"
                      android:layout_below="@id/tvFlag"
                      android:gravity="top"
                      android:singleLine="false" />
              </RelativeLayout>
          </LinearLayout>
      
          <LinearLayout
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:layout_weight="3"
              android:orientation="vertical">
      
              <RelativeLayout
                  android:layout_width="fill_parent"
                  android:layout_height="fill_parent"
                  android:padding="10dp">
      
                  <Button
                      android:id="@+id/btnflagCancel"
                      android:layout_width="80dp"
                      android:layout_height="wrap_content"
                      android:layout_alignParentRight="true"
                      android:layout_marginLeft="10dp"
                      android:text="取消" />
      
                  <Button
                      android:id="@+id/btnflagSave"
                      android:layout_width="80dp"
                      android:layout_height="wrap_content"
                      android:layout_toLeftOf="@id/btnflagCancel"
                      android:maxLength="200"
                      android:text="保存" />
              </RelativeLayout>
          </LinearLayout>
      </LinearLayout>
      
  3. showinfo.xml (查看便签信息窗体)

    • 包含一个文本视图 textView1 和一个列表视图 lvinfo 用于展示便签信息
    <?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:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="便签信息"
            android:textSize="20dp" />
    
        <LinearLayout
            android:id="@+id/linearLayout2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0.94"
            android:orientation="vertical">
    
            <ListView
                android:id="@+id/lvinfo"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scrollbarAlwaysDrawVerticalTrack="true" />
        </LinearLayout>
    </LinearLayout>
    
  4. manageflag.xml (便签管理窗体)

    • 包含一个文本框 txtFlagManage 和两个按钮:btnFlagManageEdit (修改) 和 btnFlagManageDelete (删除)
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/flagmanage"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">
    
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="3"
            android:orientation="vertical">
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:gravity="center_horizontal"
                android:text="便签管理"
                android:textColor="#000000"
                android:textSize="40sp"
                android:textStyle="bold" />
        </LinearLayout>
    
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:orientation="vertical">
    
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="5dp">
    
                <TextView
                    android:id="@+id/tvFlagManage"
                    android:layout_width="350dp"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:text="请输入便签,最多输入 200 字"
                    android:textColor="#8C6931"
                    android:textSize="23sp" />
    
                <EditText
                    android:id="@+id/txtFlagManage"
                    android:layout_width="350dp"
                    android:layout_height="400dp"
                    android:layout_below="@id/tvFlagManage"
                    android:gravity="top"
                    android:singleLine="false" />
            </RelativeLayout>
        </LinearLayout>
    
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="3"
            android:orientation="vertical">
    
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="10dp">
    
                <Button
                    android:id="@+id/btnFlagManageDelete"
                    android:layout_width="80dp"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_marginLeft="10dp"
                    android:text="删除" />
    
                <Button
                    android:id="@+id/btnFlagManageEdit"
                    android:layout_width="80dp"
                    android:layout_height="wrap_content"
                    android:layout_toLeftOf="@id/btnFlagManageDelete"
                    android:maxLength="200"
                    android:text="修改" />
            </RelativeLayout>
        </LinearLayout>
    </LinearLayout>
    
步骤 3: 配置活动文件
  1. MainActivity.java

    • 初始化界面和按钮
    • 为按钮添加点击事件,分别跳转到 ShowInfoInsertFlag 活动
    package com.example.notemanagementsystem.activity;
    
    import android.os.Bundle;
    import android.app.Activity;
    import android.content.Intent;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    
    import com.wenlong.DBLab.activity.R;
    
    public class MainActivity extends Activity {
        Button btnflaginfo, btninsertinfo;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            btnflaginfo = (Button) findViewById(R.id.btnflaginfo);
            btninsertinfo = (Button) findViewById(R.id.btninsertinfo);
    
            btnflaginfo.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MainActivity.this, ShowInfo.class);
                    startActivity(intent);
    
                }
            });
            btninsertinfo.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MainActivity.this, InsertFlag.class);
                    startActivity(intent);
    
                }
            });
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }
    }
    
  2. InsertFlag.java

    • 处理新增便签的界面逻辑
    • 获取输入的便签内容,保存到数据库,并显示相应的提示信息
    package com.example.notemanagementsystem;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    
    import com.example.notemanagementsystem.DAO.FlagDao;
    import com.example.notemanagementsystem.model.flag;
    
    public class InsertFlag extends Activity {
        EditText txtFlag;// 创建 EditText 组件对象
        Button btnflagSaveButton;// 创建 Button 组件对象
        Button btnflagCancelButton;// 创建 Button 组件对象
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.insertinfo);
            txtFlag = (EditText) findViewById(R.id.txtFlag);
            btnflagSaveButton = (Button) findViewById(R.id.btnflagSave);
            btnflagCancelButton = (Button) findViewById(R.id.btnflagCancel);
            btnflagSaveButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    String strFlag = txtFlag.getText().toString();// 获取便签文本框的值
                    if (!strFlag.isEmpty()) {// 判断获取
                        FlagDao flagDAO = new FlagDao(InsertFlag.this);// 创建FlagDAO 对象
                        flag flag = new flag(
                                flagDAO.getMaxId() + 1, strFlag);// 创建 Tb_flag 对象
                        flagDAO.add(flag);// 添加便签信息
                        // 弹出信息提示
                        Toast.makeText(InsertFlag.this, "〖新增便签〗数据添加成功!",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(InsertFlag.this, "请输入便签!",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });
            btnflagCancelButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
    }
    
  3. ShowInfo.java

    • 展示所有便签信息的界面逻辑
    • 使用 ListView 显示便签列表,点击某一项跳转到 ManageFlag 活动
    package com.example.notemanagementsystem;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    import android.widget.TextView;
    
    import com.example.notemanagementsystem.DAO.FlagDao;
    import com.example.notemanagementsystem.model.flag;
    
    import java.util.List;
    
    public class ShowInfo extends Activity {
        public static final String FLAG = "id";// 定义一个常量,用来作为请求码
        ListView lvinfo;// 创建 ListView 对象
        String[] strInfos = null;// 定义字符串数组,用来存储收入信息
        ArrayAdapter<String> arrayAdapter = null;// 创建 ArrayAdapter 对象
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.showinfo);
            lvinfo = (ListView) findViewById(R.id.lvinfo);
            FlagDao flaginfo = new FlagDao(ShowInfo.this);// 创建 FlagDAO 对象
            // 获取所有便签信息,并存储到 List 泛型集合中
            List<flag> listFlags = flaginfo.getScrollData(0,
                    (int) flaginfo.getCount());
            strInfos = new String[listFlags.size()];// 设置字符串数组的长度
            int n = 0;// 定义一个开始标识
            for (flag tb_flag : listFlags) {
                // 将便签相关信息组合成一个字符串,存储到字符串数组的相应位置
                strInfos[n] = tb_flag.getid() + "|" + tb_flag.getFlag();
                if (strInfos[n].length() > 15)// 判断便签信息的长度是否大于 15
                    strInfos[n] = strInfos[n].substring(0, 15) + "……";// 将位置大于 15之后的字符串用……代替
                n++;// 标识加 1
            }
            arrayAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, strInfos);
            lvinfo.setAdapter(arrayAdapter);
            lvinfo.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position,
                                        long id) {
                    String strInfo = String.valueOf(((TextView) view).getText());// 记录单击的项信息
                    String strid = strInfo.substring(0, strInfo.indexOf('|'));// 从项信息中截取编号
                    Intent intent = null;// 创建 Intent 对象
                    intent = new Intent(ShowInfo.this, ManageFlag.class);// 使用 FlagManage 窗口初始化 Intent 对象
                    intent.putExtra(FLAG, strid);// 设置要传递的数据
                    startActivity(intent);// 执行 Intent,打开相应的 Activity
                }
            });
        }
    }
    
  4. ManageFlag.java

    • 处理便签管理的界面逻辑
    • 获取传递的便签id,显示该便签内容,可进行编辑和删除操作
    package com.example.notemanagementsystem;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    
    import com.example.notemanagementsystem.DAO.FlagDao;
    import com.example.notemanagementsystem.model.flag;
    
    public class ManageFlag extends Activity {
        EditText txtFlag;// 创建 EditText 对象
        Button btnEdit, btnDel;// 创建两个 Button 对象
        String strid;// 创建字符串,表示便签的 id
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.manageflag);
            txtFlag = (EditText) findViewById(R.id.txtFlagManage);
            btnEdit = (Button) findViewById(R.id.btnFlagManageEdit);
            btnDel = (Button) findViewById(R.id.btnFlagManageDelete);
            Intent intent = getIntent();// 创建 Intent 对象
            Bundle bundle = intent.getExtras();// 获取便签 id
            strid = bundle.getString(ShowInfo.FLAG);// 将便签 id 转换为字符串
            final FlagDao flagDAO = new FlagDao(ManageFlag.this);// 创建 FlagDAO 对象
            txtFlag.setText(flagDAO.find(Integer.parseInt(strid)).getFlag());
            // 为修改按钮设置监听事件
            btnEdit.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    flag tb_flag = new flag();// 创建 Tb_flag 对象
                    tb_flag.setid(Integer.parseInt(strid));// 设置便签 id
                    tb_flag.setFlag(txtFlag.getText().toString());// 设置便签值
                    flagDAO.update(tb_flag);// 修改便签信息
                    // 弹出信息提示
                    Toast.makeText(ManageFlag.this, "〖便签数据〗修改成功!",
                            Toast.LENGTH_SHORT).show();
                }
            });
            // 为删除按钮设置监听事件
            btnDel.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    flagDAO.detele(Integer.parseInt(strid));// 根据指定的 id 删除便签信息
                    Toast.makeText(ManageFlag.this, "〖便签数据〗删除成功!",
                            Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
    
步骤 4: 配置数据库相关文件
  1. DBOpenHelper.java

    • 创建数据库,定义便签信息表结构
    package com.example.notemanagementsystem.DAO;
    
    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    
    public class DBOpenHelper extends SQLiteOpenHelper {
        private static final int VERSION = 1;// 定义数据库版本号
        private static final String DBNAME = "flag.db";// 定义数据库名
    
        public DBOpenHelper(Context context) {
            super(context, DBNAME, null, VERSION);
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) // 创建数据库
        {
            db.execSQL("create table tb_flag (_id integer primary key,flag varchar(200)) ");// 创建便签信息表
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) // 覆写基类的 onUpgrade方法,以便数据库版本更新
        {
    
        }
    }
    
  2. FlagDao.java

    • 提供对便签表的增删改查操作
    • 包含获取便签总记录数和最大编号的方法
    package com.example.notemanagementsystem.DAO;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    
    import com.example.notemanagementsystem.DAO.DBOpenHelper;
    import com.example.notemanagementsystem.model.flag;
    
    public class FlagDao {
        private DBOpenHelper helper;// 创建 DBOpenHelper 对象
        private SQLiteDatabase db;// 创建 SQLiteDatabase 对象
    
        public FlagDao(Context context)// 定义构造函数
        {
            helper = new DBOpenHelper(context);// 初始化 DBOpenHelper 对象
        }
    
        /**
         * 添加便签信息
         *
         * @param tb_flag
         */
        public void add(flag flag) {
            db = helper.getWritableDatabase();// 初始化 SQLiteDatabase 对象
            db.execSQL("insert into tb_flag (_id,flag) values (?,?)", new Object[]{
                    flag.getid(), flag.getFlag()});// 执行添加便签信息操作
        }
    
        /**
         * 更新便签信息
         *
         * @param tb_flag
         */
        public void update(flag tb_flag) {
            db = helper.getWritableDatabase();// 初始化 SQLiteDatabase 对象
            db.execSQL("update tb_flag set flag = ? where _id = ?", new Object[]{
                    tb_flag.getFlag(), tb_flag.getid()});// 执行修改便签信息操作
        }
    
        /**
         * 查找便签信息
         *
         * @param id
         * @return
         */
        public flag find(int id) {
            db = helper.getWritableDatabase();// 初始化 SQLiteDatabase 对象
            Cursor cursor = db.rawQuery(
                    "select _id,flag from tb_flag where _id = ?",
                    new String[]{String.valueOf(id)});// 根据编号查找便签信息,并存储到 Cursor 类中
            if (cursor.moveToNext())// 遍历查找到的便签信息
            {
                // 将遍历到的便签信息存储到 Tb_flag 类中
                return new flag(cursor.getInt(cursor.getColumnIndex("_id")), cursor.getString(cursor.getColumnIndex("flag")));
            }
            return null;// 如果没有信息,则返回 null
        }
    
        /**
         * 刪除便签信息
         *
         * @param ids
         */
        public void detele(Integer... ids) {
            if (ids.length > 0)// 判断是否存在要删除的 id
            {
                StringBuffer sb = new StringBuffer();// 创建 StringBuffer 对象
                for (int i = 0; i < ids.length; i++)// 遍历要删除的 id 集合
                {
                    sb.append('?').append(',');// 将删除条件添加到 StringBuffer 对象中
                }
                sb.deleteCharAt(sb.length() - 1);// 去掉最后一个“,“字符
                db = helper.getWritableDatabase();// 创建 SQLiteDatabase 对象
                // 执行删除便签信息操作
                db.execSQL("delete from tb_flag where _id in (" + sb + ")",
                        (Object[]) ids);
            }
        }
    
        /**
         * 获取便签信息
         *
         * @param start 起始位置
         * @param count 每页显示数量
         * @return
         */
        public List<flag> getScrollData(int start, int count) {
            List<flag> lisTb_flags = new ArrayList<flag>();// 创建集合对象
            db = helper.getWritableDatabase();// 初始化 SQLiteDatabase 对象
            // 获取所有便签信息
            Cursor cursor = db.rawQuery("select * from tb_flag limit ?,?",
                    new String[]{String.valueOf(start), String.valueOf(count)});
            while (cursor.moveToNext())// 遍历所有的便签信息
            {
                // 将遍历到的便签信息添加到集合中
                lisTb_flags.add(new flag(cursor.getInt(cursor.getColumnIndex("_id")), cursor.getString(cursor.getColumnIndex("flag"))));
            }
            return lisTb_flags;// 返回集合
        }
    
        /**
         * 获取总记录数
         *
         * @return
         */
        public long getCount() {
            db = helper.getWritableDatabase();// 初始化 SQLiteDatabase 对象
            Cursor cursor = db.rawQuery("select count(_id) from tb_flag", null);// 获取便签信息的记录数
            if (cursor.moveToNext())// 判断 Cursor 中是否有数据
            {
                return cursor.getLong(0);// 返回总记录数
            }
            return 0;// 如果没有数据,则返回 0
        }
    
        /**
         * 获取便签最大编号
         *
         * @return
         */
        public int getMaxId() {
            db = helper.getWritableDatabase();// 初始化 SQLiteDatabase 对象
            Cursor cursor = db.rawQuery("select max(_id) from tb_flag", null);// 获取便签信息表中的最大编号
            while (cursor.moveToLast()) {// 访问 Cursor 中的最后一条数据
                return cursor.getInt(0);// 获取访问到的数据,即最大编号
            }
            return 0;// 如果没有数据,则返回 0
        }
    }
    
  3. flag.java

    • 定义便签实体类,包含编号和便签内容
    package com.example.notemanagementsystem.model;
    
    public class flag {
        private int _id;// 存储便签编号
        private String flag;// 存储便签信息
    
        public flag()// 默认构造函数
        {
            super();
        }
    
        // 定义有参构造函数,用来初始化便签信息实体类中的各个字段
        public flag(int id, String flag) {
            super();
            this._id = id;// 为便签号赋值
            this.flag = flag;// 为便签信息赋值
        }
    
        public int getid()// 设置便签编号的可读属性
        {
            return _id;
        }
    
        public void setid(int id)// 设置便签编号的可写属性
        {
            this._id = id;
        }
    
        public String getFlag()// 设置便签信息的可读属性
        {
            return flag;
        }
    
        public void setFlag(String flag)// 设置便签信息的可写属性
        {
            this.flag = flag;
        }
    }
    
步骤 5: 配置清单文件
  1. AndroidManifest.xml

    • 配置主活动为 MainActivity
    • 配置其他三个活动: ShowInfo, InsertFlag, ManageFlag
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.wenlong.DBLab.activity"
        android:versionCode="1"
        android:versionName="1.0">
    
        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="18" />
        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme">
            <activity
                android:name="com.example.notemanagementsystem.MainActivity"
                android:label="@string/app_name">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity
                android:name="com.example.notemanagementsystem.ShowInfo"
                android:icon="@drawable/ic_launcher"
                android:label="便签信息"></activity>
            <activity
                android:name="com.example.notemanagementsystem.InsertFlag"
                android:icon="@drawable/ic_launcher"
                android:label="添加便签"></activity>
            <activity
                android:name="com.example.notemanagementsystem.ManageFlag"
                android:icon="@drawable/ic_launcher"
                android:label="便签管理"></activity>
        </application>
    </manifest>
    
步骤 6: 运行与测试

1.文档结构

image-20231124152548336

2.运行效果

image-20231124152727243

image-20231124152751315

【拓展题】编写 Android 项目,实现商品库存数据库管理小系统。
步骤一:创建新的 Android 项目
  1. 打开 Android Studio。
  2. 选择 “File” -> “New” -> “New Project…”。
  3. 在弹出的对话框中,输入项目名称为 “InventoryManagementSystem”,选择语言为 Java,选择 “Phone and Tablet” -> “Empty Activity”,然后点击 “Finish”。
步骤二:创建数据库帮助类(DBOpenHelper)

在项目中创建一个用于管理数据库的帮助类。

DBOpenHelper.java
package com.example.inventorymanagementsystem.database;

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

public class DBOpenHelper extends SQLiteOpenHelper {
    private static final String DB_NAME = "inventory.db";
    private static final int DB_VERSION = 1;

    public DBOpenHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // 创建商品表
        db.execSQL("CREATE TABLE IF NOT EXISTS products (" +
                "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "name TEXT," +
                "quantity INTEGER," +
                "price REAL)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 数据库升级操作
    }
}
步骤三:创建商品实体类(Product)

创建一个用于表示商品的实体类。

Product.java

package com.example.inventorymanagementsystem.model;

public class Product {
    private int id;
    private String name;
    private int quantity;
    private double price;

    public Product() {
    }

    public Product(String name, int quantity, double price) {
        this.name = name;
        this.quantity = quantity;
        this.price = price;
    }

    // Getter and setter methods
}
步骤四:创建商品数据操作类(ProductDAO)

创建一个用于执行商品数据操作的类。

ProductDAO.java

package com.example.inventorymanagementsystem.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.inventorymanagementsystem.model.Product;
import java.util.ArrayList;
import java.util.List;

public class ProductDAO {
    private SQLiteDatabase db;

    public ProductDAO(Context context) {
        DBOpenHelper dbHelper = new DBOpenHelper(context);
        db = dbHelper.getWritableDatabase();
    }

    public long addProduct(Product product) {
        ContentValues values = new ContentValues();
        values.put("name", product.getName());
        values.put("quantity", product.getQuantity());
        values.put("price", product.getPrice());
        return db.insert("products", null, values);
    }

    public List<Product> getAllProducts() {
        List<Product> productList = new ArrayList<>();
        Cursor cursor = db.query("products", null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            Product product = new Product();
            product.setId(cursor.getInt(cursor.getColumnIndex("_id")));
            product.setName(cursor.getString(cursor.getColumnIndex("name")));
            product.setQuantity(cursor.getInt(cursor.getColumnIndex("quantity")));
            product.setPrice(cursor.getDouble(cursor.getColumnIndex("price")));
            productList.add(product);
        }
        cursor.close();
        return productList;
    }

    // 添加其他数据库操作方法,如更新商品信息、删除商品等
}
步骤五:创建商品管理界面(MainActivity)

res/layout 文件夹中创建一个用于显示商品列表和添加商品的界面布局文件。

activity_main.xml

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

    <ListView
        android:id="@+id/listViewProducts"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@android:color/darker_gray"
        android:dividerHeight="1dp" />

    <Button
        android:id="@+id/btnAddProduct"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add Product"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_margin="16dp"/>
</RelativeLayout>

activity_add_product.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <EditText
        android:id="@+id/edtProductName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="商品名称" />

    <EditText
        android:id="@+id/edtProductQuantity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:hint="数量" />

    <EditText
        android:id="@+id/edtProductPrice"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"
        android:hint="价格" />

    <Button
        android:id="@+id/btnAddProduct"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="添加商品" />
</LinearLayout>

MainActivity.java

package com.example.inventorymanagementsystem;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.inventorymanagementsystem.database.ProductDAO;
import com.example.inventorymanagementsystem.model.Product;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private ListView listViewProducts;
    private Button btnAddProduct;
    private ProductDAO productDAO;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listViewProducts = findViewById(R.id.listViewProducts);
        btnAddProduct = findViewById(R.id.btnAddProduct);
        productDAO = new ProductDAO(this);

        updateProductList();

        btnAddProduct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AddProductActivity.class);
                startActivity(intent);

            }
        });

    }


    private void updateProductList() {
        List<Product> productList = productDAO.getAllProducts();
        ArrayAdapter<Product> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, productList);


        listViewProducts.setAdapter(adapter);
    }
}

AddProductActivity.java

package com.example.inventorymanagementsystem;

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

import androidx.appcompat.app.AppCompatActivity;
import com.example.inventorymanagementsystem.database.ProductDAO;
import com.example.inventorymanagementsystem.model.Product;

public class AddProductActivity extends AppCompatActivity {
    private EditText edtProductName, edtProductQuantity, edtProductPrice;
    private Button btnAddProduct;
    private ProductDAO productDAO;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_product);

        edtProductName = findViewById(R.id.edtProductName);
        edtProductQuantity = findViewById(R.id.edtProductQuantity);
        edtProductPrice = findViewById(R.id.edtProductPrice);
        btnAddProduct = findViewById(R.id.btnAddProduct);

        productDAO = new ProductDAO(this);

        btnAddProduct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addProduct();
            }
        });
    }

    private void addProduct() {
        // 获取用户输入的商品信息
        String productName = edtProductName.getText().toString();
        String quantityStr = edtProductQuantity.getText().toString();
        String priceStr = edtProductPrice.getText().toString();

        if (!productName.isEmpty() && !quantityStr.isEmpty() && !priceStr.isEmpty()) {
            int quantity = Integer.parseInt(quantityStr);
            double price = Double.parseDouble(priceStr);

            // 创建商品对象
            Product newProduct = new Product(productName, quantity, price);

            // 将商品添加到数据库
            long result = productDAO.addProduct(newProduct);
            if (result != -1) {
                Toast.makeText(AddProductActivity.this, "商品添加成功", Toast.LENGTH_SHORT).show();
                finish(); // 关闭当前界面
            } else {
                Toast.makeText(AddProductActivity.this, "商品添加失败", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(AddProductActivity.this, "请填写完整的商品信息", Toast.LENGTH_SHORT).show();
        }
    }
}
步骤六:运行效果

image-20231124162406148

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1249634.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Joint Cross-Modal and Unimodal Features for RGB-D Salient Object Detection

提出的模型 the outputs H i m _i^m im​ from the unimodal RGB or depth branch in MFFM FFM means ‘Feature Fusion Module’ 作者未提供代码

【Vue】图片切换

上一篇&#xff1a; vue的指令 https://blog.csdn.net/m0_67930426/article/details/134599378?spm1001.2014.3001.5502 本篇所需要的指令有&#xff1a; v-on v-bind v-show <!DOCTYPE html> <html lang"en"> <head><meta charset"…

【JVM】一篇通关JVM垃圾回收

目录 1. 如何判断对象可以回收1-1. 引用计数法1-2. 可达性分析算法1-3. 四种引用强引用软引用弱引用虚引用终结器引用 2. 垃圾回收算法3. 分代垃圾回收4. 垃圾回收器5. 垃圾回收调优 1. 如何判断对象可以回收 1-1. 引用计数法 引用计数法 只要一个对象被其他变量所引用&…

JSP:JDBC

JDBC&#xff08;Java Data Base Connectivity的缩写&#xff09;是Java程序操作数据库的API&#xff0c;也是Java程序与数据库相交互的一门技术。 JDBC是Java操作数据库的规范&#xff0c;由一组用Java语言编写的类和接口组成&#xff0c;它对数据库的操作提供基本方法&#…

2023-11-24--oracle--实验--[Merge 语句]

oracle--实验---Merge语句 1.认知Merge 语句 • merge 语句是 sql 语句的一种。在 SQL server 、 Oracle 数据库中可用&#xff0c; MySQL 中不可用。 • merge 用来合并 update 和 insert 语句。目的&#xff1a;通过 merge 语句&#xff0c;根据一张表&#xff08; 原数据表…

superset 后端增加注册接口

好烦啊-- &#xff1a;< 1.先定义modes: superset\superset\models\user.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information…

JSP EL表达式之 empty

好 本文我们还是继续说EL表达式 我们来讲一个非空判断的好手 empty 我们直接编写代码如下 <% page contentType"text/html; charsetUTF-8" pageEncoding"UTF-8" %> <%request.setCharacterEncoding("UTF-8");%> <!DOCTYPE html&…

探索亚马逊云科技云存储服务的性能

文章作者&#xff1a;Libai 引言 随着企业越来越多地依赖云存储解决方案&#xff0c;确保存储性能的最佳状态变得至关重要。在本文中&#xff0c;我们将探讨在亚马逊云科技云存储服务上进行存储性能基准测试的重要性&#xff0c;以及如何帮助企业做出资源分配和优化的明智决策…

小程序中的大道理之二--抽象与封装

继续扒 接着 上一篇 的叙述, 健壮性也有了, 现在是时候处理点实际的东西了, 但我们依然不会一步到底, 让我们来看看. 一而再地抽象(Abstraction Again) 让我们继续无视那些空格以及星号等细节, 我们看到什么呢? 我们只看到一整行的内容, 当传入 3 时就有 3 行, 传入 4 时就…

postgresql从入门到精通 - 第35讲:中间件PgBouncer部署|PostgreSQL教程

PostgreSQL从小白到专家&#xff0c;是从入门逐渐能力提升的一个系列教程&#xff0c;内容包括对PG基础的认知、包括安装使用、包括角色权限、包括维护管理、、等内容&#xff0c;希望对热爱PG、学习PG的同学们有帮助&#xff0c;欢迎持续关注CUUG PG技术大讲堂。 第35讲&#…

Linux加强篇002-部署Linux系统

目录 前言 1. shell语言 2. 执行命令的必备知识 3. 常用系统工作命令 4. 系统状态检测命令 5. 查找定位文件命令 6. 文本文件编辑命令 7. 文件目录管理命令 前言 悟已往之不谏&#xff0c;知来者之可追。实迷途其未远&#xff0c;觉今是而昨非。舟遥遥以轻飏&#xff…

SpringBoot : ch05 整合Mybatis

前言 随着Java Web应用程序的快速发展&#xff0c;开发人员需要越来越多地关注如何高效地构建可靠的应用程序。Spring Boot作为一种快速开发框架&#xff0c;旨在简化基于Spring的应用程序的初始搭建和开发过程。而MyBatis作为一种优秀的持久层框架&#xff0c;提供了对数据库…

【微服务专题】SpringBoot自动配置源码解析

目录 前言阅读对象阅读导航前置知识笔记正文0、什么是自动配置0.1 基本概念0.2 SpringBoot中的【约定大于配置】0.3 从SpringMVC看【约定大于配置】0.4 从Redis看【约定大于配置】 一、EnableAutoConfiguration源码解析二、SpringBoot常用条件注解源码解析2.1 自定义条件注解2.…

web前端开发基础----标准流布局和非标准流布局

1&#xff0c;标准流布局 标准流&#xff0c;也称文档流或普通流&#xff0c;是所有元素默认的布局方式。 在标准流中&#xff0c;元素按照其在 HTML 中出现的顺序&#xff0c;自上而下依次排列&#xff0c;并占据其父容器内的可用空间。 标准流中的元素按照其自然尺寸和位置进…

Oracle研学-介绍及安装

一 ORACLE数据库特点: 支持多用户&#xff0c;大事务量的事务处理数据安全性和完整性控制支持分布式数据处理可移植性(跨平台&#xff0c;linux转Windows) 二 ORACLE体系结构 数据库&#xff1a;oracle是一个全局数据库&#xff0c;一个数据库可以有多个实例&#xff0c;每个…

【Rust日报】2023-11-22 Floneum -- 基于 Rust 的一款用于 AI 工作流程的图形编辑器

Floneum -- 基于 Rust 的一款用于 AI 工作流程的图形编辑器 Floneum 是一款用于 AI 工作流程的图形编辑器&#xff0c;专注于社区制作的插件、本地 AI 和安全性。 Floneum 有哪些特性&#xff1a; 可视化界面&#xff1a;您无需任何编程知识即可使用Floneum。可视化图形编辑器可…

【数据库篇】关系模式的表示——(1)问题的提出

1、关系模式的表示 R&#xff1a;表示关系的名字比如&#xff1a;sc选课表&#xff0c;student学生表。 U&#xff1a;表示一个关系模式的所有属性&#xff0c;比如student表&#xff1a;U&#xff08;sno&#xff0c;sname&#xff0c;sage&#xff0c;ssex&#xff09;。 …

代码随想录算法训练营第五十四天|392.判断子序列 115.不同的子序列

文档讲解&#xff1a;代码随想录 视频讲解&#xff1a;代码随想录B站账号 状态&#xff1a;看了视频题解和文章解析后做出来了 392.判断子序列 class Solution:def isSubsequence(self, s: str, t: str) -> bool:dp [[0] * (len(t)1) for _ in range(len(s)1)]for i in ra…

mysql 变量和配置详解

MySQL 中还有一些特殊的全局变量&#xff0c;如 log_bin、tmpdir、version、datadir&#xff0c;在 MySQL 服务实例运行期间它们的值不能动态修改&#xff0c;也就是不能使用 SET 命令进行重新设置&#xff0c;这种变量称为静态变量。数据库管理员可以使用前面提到的修改源代码…

吴恩达《机器学习》10-1-10-3:决定下一步做什么、评估一个假设、模型选择和交叉验证集

一、决定下一步做什么 在机器学习的学习过程中&#xff0c;我们已经接触了许多不同的学习算法&#xff0c;逐渐深入了解了先进的机器学习技术。然而&#xff0c;即使在了解了这些算法的情况下&#xff0c;仍然存在一些差距&#xff0c;有些人能够高效而有力地运用这些算法&…