要求:开发一个手机端上报体温的手机APP,上报内容包括姓名、日期(自动生成)、时间(自动生成)和体温。
创建Sqlite数据库
先创建一个类继承SQLiteOpenHelper类,再实现里面的方法,创建构造方法然后创建子类对象,再调用getReadableDatabase()/getWritableDatabase()方法。
1 package com.example.application; 2 3 import android.content.Context; 4 import android.database.sqlite.SQLiteDatabase; 5 import android.database.sqlite.SQLiteOpenHelper; 6 import android.util.Log; 7 8 import androidx.annotation.Nullable; 9 10 public class DatabaseHelper extends SQLiteOpenHelper { 11 private static final String TAG="DatabaseHelper"; 12 public DatabaseHelper(@Nullable Context context) { 13 super(context, Constants.DATABASE_NAME, null, Constants.VERSION_CODE); 14 } 15 16 @Override 17 public void onCreate(SQLiteDatabase db) { 18 //创建时的回调 19 Log.d(TAG,"创建数据库..."); 20 String sql="create table "+Constants.TABLE_NAME+" (id integer primary key autoincrement, name varchar,date varchar,time varchar,location varchar,temperature varchar)"; 21 db.execSQL(sql); 22 } 23 24 @Override 25 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 26 //升级时的回调 27 Log.d(TAG,"升级数据库..."); 28 } 29 }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //创建数据库 DatabaseHelper helper=new DatabaseHelper(this); helper.getWritableDatabase(); bt_add=(Button)findViewById(R.id.add_data); tv_date = (TextView) findViewById(R.id.textView1); tv_time = (TextView) findViewById(R.id.textView2); et_name=(EditText)findViewById(R.id.edit_text1) ; et_temperature=(EditText)findViewById(R.id.edit_text3) ; } public void insertData(View view) { DatabaseHelper helper=new DatabaseHelper(this); SQLiteDatabase sqldb=helper.getWritableDatabase(); ContentValues contentvalues=new ContentValues(); contentvalues.put("name",et_name.getText().toString()); contentvalues.put("date",tv_date.getText().toString()); contentvalues.put("time",tv_time.getText().toString()); contentvalues.put("location",et_location.getText().toString()); contentvalues.put("temperature",et_temperature.getText().toString()); if(et_name.getText().toString().equals("")|| et_location.getText().toString().equals("")||et_temperature.getText().toString().equals("")){ Toast.makeText(this,"请将信息填写完整",Toast.LENGTH_SHORT).show(); }else { long flag = sqldb.insert(TABLE_NAME, null, contentvalues); Toast.makeText(this, "登记成功", Toast.LENGTH_LONG).show(); } sqldb.close(); }