在StudentDao类文件中代码如下:
public class StudentDao {
Context context;
final String tableName = "student";
public StudentDao(Context mContext) {
context = mContext;
}
// 添加
public void addStudent(Student student) {
DbUtil mDbUtil = new DbUtil(context);
SQLiteDatabase mSQLiteDatabase = mDbUtil.getWritableDatabase();
// 执行insert语句的方式
ContentValues values = new ContentValues();
values.put("id", student.getId());
values.put("age", student.getAge());
values.put("name", student.getName());
mSQLiteDatabase.insert(tableName, null, values);
// 关闭
mSQLiteDatabase.close();
mDbUtil.close();
}
}
在DbUtil类文件中代码如下:
public class DbUtil extends SQLiteOpenHelper {
//创建库文件
public DbUtil(Context context) {
super(context, "test.db", null, 2);
}
//创建表
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table student(id int,name varchar(20))");
db.execSQL("create table teacher(id int,name varchar(20))");
Log.e("DbUtil", "onCreate");
}
}
问题1:在StudentDao类中,StudentDao构造函数有什么作用(可以说详细一点吗)?
问题2:在StudentDao类中,这一句代码DbUtil mDbUtil = new DbUtil(context)这一句代码是创建一个数据库吗?
问题1:在StudentDao类中,StudentDao构造函数有什么作用?
就是传进来一个数据库对象(如test.db),然后看情况调用里面的方法(addStudent)
问题2:在StudentDao类中,这一句代码DbUtil mDbUtil = new DbUtil(context)这一句代码是创建一个数据库吗?
创建context这个对象(test.db)的数据库
至于context的这个东西,一般翻译成“上下文”,原文描述:
Interface to global information about an application environment. This is an abstract class whose implementation
is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls
for application-level operations such as launching activities, broadcasting and receiving intents, etc
获取程序的资源什么的时候,要用到它
其实context你没有必要深究的,你只需要知道做什么事情的时候需要它就可以了,一般都是用来获取你的资源文件什么的
就是指的你当前的activity的上下文,当前环境的辨识