SQLite 和 SQLiteDatabase 的使用

实验七: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.mfbz.cn/a/185360.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

保姆级 ARM64 CPU架构下安装部署Docker + rancher + K8S 说明文档

1 K8S 简介 K8S是Kubernetes的简称&#xff0c;是一个开源的容器编排平台&#xff0c;用于自动部署、扩展和管理“容器化&#xff08;containerized&#xff09;应用程序”的系统。它可以跨多个主机聚集在一起&#xff0c;控制和自动化应用的部署与更新。 K8S 架构 Kubernete…

【nlp】3.6 Tansformer模型构建(编码器与解码器模块耦合)

Tansformer模型构建(编码器与解码器模块耦合) 1. 模型构建介绍2 编码器-解码器结构的代码实现3 Tansformer模型构建过程的代码实现4 小结1. 模型构建介绍 通过上面的小节, 我们已经完成了所有组成部分的实现, 接下来就来实现完整的编码器-解码器结构耦合. Transformer总体架…

聚类笔记:HDBSCAN

1 算法介绍 DBSCAN/OPTICS层次聚类主要由以下几步组成 空间变换构建最小生成树构建聚类层次结构(聚类树)压缩聚类树提取簇 2 空间变换 用互达距离来表示两个样本点之间的距离 ——>密集区域的样本距离不受影响——>稀疏区域的样本点与其他样本点的距离被放大——>…

Unity Android FireBase bugly报错查询

报错如下图&#xff0c;注意&#xff0c;标红的三处 使用的il2cpp和架构是arm64-v8a 那我们就可以根据这些去找对应的符号表&#xff0c;在unity安装目录下 Unity2020.3.33f1\Editor\Data\PlaybackEngines\AndroidPlayer\Variations\il2cpp\Release\Symbols\arm64-v8a 找到l…

缓存组件状态,提升用户体验:探索 keep-alive 的神奇世界

&#x1f90d; 前端开发工程师&#xff08;主业&#xff09;、技术博主&#xff08;副业&#xff09;、已过CET6 &#x1f368; 阿珊和她的猫_CSDN个人主页 &#x1f560; 牛客高级专题作者、在牛客打造高质量专栏《前端面试必备》 &#x1f35a; 蓝桥云课签约作者、已在蓝桥云…

晨控CK-FR03-EIP读卡器与欧姆龙NX/NJ系列EtherNet/IP通讯手册

晨控CK-FR03-EIP读卡器与欧姆龙NX/NJ系列EtherNet/IP通讯手册 CK-FR03-EIP是一款基于射频识别技术的高频RFID标签读卡器&#xff0c;读卡器工作频率为13.56MHZ&#xff0c;支持对I-CODE 2、I-CODE SLI等符合ISO15693国际标准协议格式标签的读取。 读卡器同时支持标准工业通讯…

Linux文件查看命令

1.cat加上文件名 &#xff08;因为所有文件内容都会打印到屏幕上&#xff0c;所以内容少时使用这个&#xff0c;总不能用cat来定义一本小说&#xff09; 3.往文件中写入数据——cat加上>(重定向符&#xff09;加上文件名&#xff0c;写完之后&#xff0c;按键 cat原本是把…

Mac OS 干货教学-超详细Wifi破解教学

Mac OS 干货教学&#x1f525;-超详细Wifi破解教学 尊重原创&#xff0c;编写不易 &#xff0c;帮忙点赞关注一下~转载小伙伴请注明出处&#xff01;谢谢 PS&#xff1a;学术交流&#xff0c;私自破解他人wifi可能要负担法律责任或让办公电脑被Hack黑客风险&#xff01;本次本…

python之pyqt专栏2-项目文件解析

项目结构 在上一篇文章python之pyqt专栏1-环境搭建&#xff0c;创建新的pyqt项目&#xff0c;下面我们来看一下这个项目下的文件。 从下面的文件结构图可以看到&#xff0c;该项目下有3个文件&#xff0c;untitled.ui,untitled.py 以及main.py。 QtDesigner可以UI界面的方式&am…

python 将当前时间转成CP56time2a BIN码

def cp56time2a_hex_str():# 获取当前时间now datetime.now()# 将当前时间格式化为CP56time2a格式s now.strftime("%Y%m%d%H%M%S")[2:]cp56time2a [s[i:i 2] for i in range(0, len(s), 2)]seconds cp56time2a[-1:][0]cp56time2a cp56time2a[:-1]seconds_hex …

openstack(2)

目录 块存储服务 安装并配置控制节点 安装并配置一个存储节点 验证操作 封装镜像 上传镜像 块存储服务 安装并配置控制节点 创建数据库 [rootcontroller ~]# mysql -u root -pshg12345 MariaDB [(none)]> CREATE DATABASE cinder; MariaDB [(none)]> GRANT ALL PR…

bat批处理文件

常用的bat批处理命令 1、遍历移动文件最好将文件编码保存为 ANSI编码 新的改变 1、遍历移动文件 把子目录里面的文件批量移动到当前目录 &#xff08;或根目录&#xff09; 项目中要批量导入附件&#xff0c;但是收集的子公司员工信息&#xff0c;都是每个人一个文件夹的&…

需求变更导致估算不精准 6大措施

需求变更可能导致估算不精准、项目成本增加、进度延迟等问题&#xff0c;如果不能准确地估算项目&#xff0c;往往会造成资源浪费和开发效率的降低&#xff0c;因此亟需解决因需求变更导致地估算不精准的问题。 一般来说&#xff0c;主要是从以下6个方面入手解决&#xff1a; 1…

python实现存款日利息计算器(窗口界面形式)

输入存款金额&#xff0c;7日年化收益率&#xff0c;输出每日利息 完整源码如下&#xff1a; import tkinter as tk from tkinter import messageboxdef calculate_interest():deposit float(entry_deposit.get())interest_rate float(entry_interest_rate.get())daily_int…

基于Zigbee的教室智能环境监控系统(论文+源码)

1.系统设计 此次研究的目的是设计一款基于Zigbee的教室智能环境监控系统&#xff0c;其系统框图如下图2.1。在此拟由CC2530单片机作为核心进行设计。同时结合多种传感器&#xff0c;如温度传感器&#xff0c;用来检测环境的温度。光照传感器&#xff0c;用来通过检测光照强度&…

告别传统Office,办公软件将如何选择

各家奶茶店的商战正如火如荼地进行着&#xff0c;各种办公软件之间的竞争亦是弥漫着无形的硝烟。WPS虽然凭借其操作便利、简单易上手的优势获得不少打工人的青睐&#xff0c;即使是在手机端&#xff0c;也可进行简单的数据处理。但是&#xff0c;正所谓“术业有专攻”&#xff…

前端入门(三)Vue生命周期、组件技术、事件总线、

文章目录 Vue生命周期Vue 组件化编程 - .vue文件非单文件组件组件的注意点组件嵌套Vue实例对象和VueComponent实例对象Js对象原型与原型链Vue与VueComponent的重要内置关系 应用单文件组件构建 Vue脚手架 - vue.cli项目文件结构refpropsmixin插件scoped样式 Vue生命周期 1、bef…

【STM32单片机】LED点阵花样显示设计

文章目录 一、功能简介二、软件设计三、实验现象联系作者 一、功能简介 本项目使用STM32F103C8T6单片机控制器&#xff0c;使用8*8LED点阵模块、按键模块等。 主要功能&#xff1a; 系统运行后&#xff0c;默认以静态模式显示&#xff0c;此时点阵左右循环切换图像。 当按下K…

C++之unordered_map/set的使用

前面我们已经学习了STL中底层为红黑树结构的一系列关联式容器——set/multiset 和 map/multimap(C98). unordered系列关联式容器 在C98中, STL提供了底层为红黑树结构的一系列关联式容器, 在查询时效率可达到log2N,即最差情况下需要比较红黑树的高度次, 当树中的节点非常多时,…

牛气霸屏-快抖云推独立版V1.6.7

介绍 快抖云推全插件独立版是最近很火的牛气霸屏系统独立版&#xff0c;牛气霸屏系统就是商家通过系统在线创建抖音或快手霸屏活动&#xff0c;并生成该活动的爆客二维码&#xff0c;用户通过扫二维码即可参加活动&#xff08;活动可以是领取卡劵&#xff0c;抽奖等&#xff0…