AndroidStudio开发_数据存储和访问

实验目的:

分别使用sqlite3工具和Android代码的方式建立SQLite数据库。在完成建立数据库的工作后,编程实现基本的数据库操作功能,包括数据的添加、删除和更新,

实验要求:

  1. 创建一个学生管理的应用,基本信息包含学生姓名,班级,学号。采用数据库存储这些信息。
  2. 应用应该至少包含信息录入和删除功能。
  3. 数据显示考虑采用ListView。

要求用ListView,尝试过效果不好,先放着,如果尝试到好的效果,会修改

数据类型类

package com.example.op6;

public class People {
        public int ID = -1;
        public String Name;
        public String Class;
        public String Number;

        @Override
        public String toString(){
            String result = "";
            result += "ID:" + this.ID + ",";
            result += "姓名:" + this.Name + ",";
            result += "班级:" + this.Class + ", ";
            result += "学号:" + this.Number;
            return result;
        }


}

 数据库适配器

package com.example.op6;
import android.annotation.SuppressLint;
import android.content.*;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

public class DBAdapter {
    private static final String DB_NAME = "student.db";
    private static final String DB_TABLE = "peopleinfo";
    private static final int DB_VERSION = 1;
    public static final String KEY_ID = "_id";
    public static final String KEY_NAME = "name";
    public static final String KEY_CLASS = "class";
    public static final String KEY_NUMBER = "number";
    private SQLiteDatabase db;
    private final Context context;

    private DBOpenHelper dbOpenHelper;

    private static class DBOpenHelper extends SQLiteOpenHelper {
        public DBOpenHelper(@Nullable Context context, @Nullable String name, SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        private static final String DB_CREATE = "create table " +
                DB_TABLE + " (" + KEY_ID + " integer primary key autoincrement, " +
                KEY_NAME + " text not null, " + KEY_CLASS + " text not null," + KEY_NUMBER + " text not null);";

        @Override
        public void onCreate(SQLiteDatabase _db) {
            _db.execSQL(DB_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase _db, int i, int i1) {
            _db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
            onCreate(_db);
        }
    }

    public DBAdapter(Context _context) {
        context = _context;
    }

    public void open() throws SQLiteException {
        dbOpenHelper = new DBOpenHelper(context, DB_NAME, null, DB_VERSION);

        try {
            db = dbOpenHelper.getWritableDatabase();
        } catch (SQLiteException ex) {
            db = dbOpenHelper.getReadableDatabase();
        }
    }

    public void close() {
        if (db != null) {
            db.close();
            db = null;
        }
    }

    public long insert(People people) {
        ContentValues newValues = new ContentValues();
        newValues.put(KEY_NAME, people.Name);
        newValues.put(KEY_CLASS, people.Class);
        newValues.put(KEY_NUMBER, people.Number);
        return db.insert(DB_TABLE, null, newValues);
    }

    public long deleteAllData() {
        return db.delete(DB_TABLE, null, null);
    }
    public long deleteOneData(long id) {
        return db.delete(DB_TABLE,  KEY_ID + "=" + id, null);
    }
    public long updateOneData(long id , People people){
        ContentValues updateValues = new ContentValues();
        updateValues.put(KEY_NAME, people.Name);
        updateValues.put(KEY_CLASS, people.Class);
        updateValues.put(KEY_NUMBER, people.Number);
        return db.update(DB_TABLE, updateValues,  KEY_ID + "=" + id, null);
    }

    @SuppressLint("Range")
    private People[] ConvertToPeople(Cursor cursor){
        int resultCounts = cursor.getCount();
        if (resultCounts == 0 || !cursor.moveToFirst()){
            return null;		}
        People[] peoples = new People[resultCounts];
        for (int i = 0 ; i<resultCounts; i++){
            peoples[i] = new People();
            peoples[i].ID = cursor.getInt(0);
            peoples[i].Name = cursor.getString(cursor.getColumnIndex(KEY_NAME));
            peoples[i].Class = cursor.getString(cursor.getColumnIndex(KEY_CLASS));
            peoples[i].Number = cursor.getString(cursor.getColumnIndex(KEY_NUMBER));
            cursor.moveToNext();}
        return peoples;
    }

    public People[] getOneData(long id) {
        Cursor results =  db.query(DB_TABLE, new String[] { KEY_ID, KEY_NAME, KEY_CLASS, KEY_NUMBER}, KEY_ID + "=" + id, null, null, null, null);
        return ConvertToPeople(results);
    }

    public People[] getAllData() {
        Cursor results = db.query(DB_TABLE, new String[] { KEY_ID, KEY_NAME, KEY_CLASS, KEY_NUMBER}, null, null, null, null, null);
        return ConvertToPeople(results);
    }


}
package com.example.op6;

import androidx.appcompat.app.AppCompatActivity;

import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    EditText e_xm,e_nl,e_sg,e_id;
    TextView t_1;
    ListView listView;
    Button b_add,b_allsee,b_clearsee,b_alldel,b_delid,b_seeid,b_updid;
    DBAdapter dbAdapter;
    SQLiteDatabase db;

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

        listView=findViewById(R.id.list);
        List<String> list=new ArrayList<>();
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list);
        e_xm=findViewById(R.id.e_xm);
        e_nl=findViewById(R.id.e_nl);
        e_sg=findViewById(R.id.e_sg);
        b_add=findViewById(R.id.b_add);
        b_allsee=findViewById(R.id.b_allsee);
        b_clearsee=findViewById(R.id.b_clearall);
        b_alldel=findViewById(R.id.b_delall);
        b_delid=findViewById(R.id.b_delid);
        b_seeid=findViewById(R.id.b_seeid);
        b_updid=findViewById(R.id.b_updid);
        e_id=findViewById(R.id.e_id);
        t_1=findViewById(R.id.t_1);
        dbAdapter=new DBAdapter(this);
        dbAdapter.open();

        b_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                People t=new People();
                t.Name=e_xm.getText().toString();
                t.Class=e_nl.getText().toString();
                t.Number=e_sg.getText().toString();
                long colunm=dbAdapter.insert(t);
                if (colunm == -1 ){
                    t_1.setText("添加过程错误!");

                } else {
                    t_1.setText("ID:"+String.valueOf(colunm)+"   姓名:"+t.Name+"   班级:"+t.Class+"   学号:"+t.Number);
//                    list.add("ID:"+String.valueOf(colunm)+"   姓名:"+t.Name+"   班级:"+t.Class+"   学号:"+t.Number);
//                   listView.setAdapter(adapter);
                }
            }
        });

        b_allsee.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                People [] peoples =dbAdapter.getAllData();
                if (peoples == null){
                    t_1.setText("数据库中没有数据");
                    return;
                }
                String t="数据库:\n";
                for(int i=0;i<peoples.length;++i){
                    t+=peoples[i].toString()+"\n";

                }
                t_1.setText(t);
            }
        });

        b_clearsee.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                t_1.setText("");
            }
        });

        b_alldel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dbAdapter.deleteAllData();
                t_1.setText("已删除所有数据!");
            }
        });

        b_delid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int id=Integer.parseInt(e_id.getText().toString());
                long result=dbAdapter.deleteOneData(id);
                String msg = "删除ID为"+e_id.getText().toString()+"的数据" + (result>0?"成功":"失败");
                t_1.setText(msg);
            }
        });

        b_seeid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int id=Integer.parseInt(e_id.getText().toString());
                People people[]=dbAdapter.getOneData(id);
                if(people==null){
                    t_1.setText("Id为"+id+"的记录不存在!");
                }
                else{
                    t_1.setText("查询成功:\n"+people[0].toString());
                }
            }
        });

        b_updid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int id=Integer.parseInt(e_id.getText().toString());
                People t=new People();
                t.Name=e_xm.getText().toString();
                t.Class=e_nl.getText().toString();
                t.Number=e_sg.getText().toString();
                long n=dbAdapter.updateOneData(id,t);
                if (n<0){
                    t_1.setText("更新过程错误!");
                } else {
                    t_1.setText("成功更新数据,"+String.valueOf(n)+"条");
                }
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        dbAdapter.close();
    }

}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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"
    android:orientation="vertical"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="姓名"/>

        <EditText
            android:id="@+id/e_xm"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="100px"
            android:singleLine="true"
            />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="班级:"/>

        <EditText
            android:id="@+id/e_nl"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="100px"
            android:singleLine="true"
            />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="学号:"/>

        <EditText
            android:id="@+id/e_sg"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="100px"
            android:singleLine="true"
            />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <Button
            android:id="@+id/b_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAlignment="center"
            android:layout_weight="1"
            android:text="添加数据"/>

        <Button
            android:id="@+id/b_allsee"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAlignment="center"
            android:layout_weight="1"
            android:text="全部显示"/>
        <Button
            android:id="@+id/b_clearall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAlignment="center"
            android:layout_weight="1"
            android:text="清除数据"/>
        <Button
            android:id="@+id/b_delall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAlignment="center"
            android:layout_weight="1"
            android:text="全部删除"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ID:" />

        <EditText
            android:id="@+id/e_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:singleLine="true" />

        <Button
            android:id="@+id/b_delid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textAlignment="center"
            android:text="ID删除"/>
        <Button
            android:id="@+id/b_seeid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textAlignment="center"
            android:text="ID查询"/>
        <Button
            android:id="@+id/b_updid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textAlignment="center"
            android:text="ID更新"/>
    </LinearLayout>

    <TextView
        android:id="@+id/t_1"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="" />
    <ListView
        android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </ListView>

</LinearLayout>

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值