Ormlite 框架是第三方对数据库操作的封装的一个框架,为了提高开发效率,尤其是对某些
数据库操作特别频繁的 app,建议使用 OrmLite 框架。它是一个非常轻量级的数据库操作框架,
它的底层是根据反射机制来实现的。
从官网下载core包以及Android包,并将其添加到项目中。
package net.nell.testormlite;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
//将数据库与表建立对应关系,即映射
@DatabaseTable(tableName = "person")
public class Person {
//将成员变量与表的列对应(一 一对应)
//generatedId = true表示定义成主键
// 一般id(字段名)都自定义
@DatabaseField(columnName = "id",generatedId = true)
public Integer id;
@DatabaseField(columnName = "name")
public String name;
@DatabaseField(columnName = "age")
public Integer age;
//必须要有个无参构造方法(Ormlite)
public Person() {
}
public Person(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
//方便打印对象的成员变量
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
package net.nell.testormlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import java.sql.SQLException;
import java.util.List;
public class MainActivity extends AppCompatActivity {
//在数据库中,表需要创建才能使用
class Test extends OrmLiteSqliteOpenHelper{
public Test(Context context){
super(context,"test.db",null,1);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource,Person.class);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//定义对象
Person person01 = new Person(1,"nell",12);
Person person02 = new Person(2,"li",15);
Test test = new Test(this);
try {
Dao<Person,Integer> dao = test.getDao(Person.class);
//增加数据
dao.create(person01);
dao.create(person02);
//删除数据
dao.deleteById(2);
//修改数据 先查询后修改
Person p = dao.queryForId(1);
p.name = "nellli";
dao.update(p);
//查看数据
List<Person> personDatas = dao.queryForAll();
System.out.println("查询到的内容为:");
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
由于在昨天的任务上要进行数据库的导入,所以我们需要在昨天的页面内容中进行修改。
首先,我们将数据库包像上文中所述导入项目中。
导入数据库后,我们在基于昨天所编写的界面,所得项目大体结构如下:
在此基础上,我们会发现相比较昨天的页面结构,今天我将联系人的那个页面换到了activity_Second.xml文件,将添加联系人的页面换到了activity_Third.xml文件。为了方便展示联系人,我们在联系人页面也添加了列表。下图为未进行修饰的结果。
package net.nell.testormlite;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
//将数据库与表建立对应关系,即映射
@DatabaseTable(tableName = "phone")
public class Phone {
//将成员变量与表的列对应(一 一对应)
//generatedId = true表示定义成主键
// 一般id(字段名)都自定义
@DatabaseField(columnName = "id",generatedId = true)
public Integer id;
@DatabaseField(columnName = "name")
public String name;
@DatabaseField(columnName = "work")
public Integer work;
@DatabaseField(columnName = "phone")
public Integer phone;
//必须要有个无参构造方法(Ormlite)
public Phone() {
}
public Phone(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.work = work;
this.phone = phone;
}
//方便打印对象的成员变量
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", work=" + work +'\'' +
",phone=" + phone +
'}';
}
}
package net.nell.testormlite;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
public class NewActivity extends AppCompatActivity {
private TextView newOff,newCreate;
private EditText newEdtName,newEdtWord,newEdtPhone;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//加载注册显示布局页面
setContentView(R.layout.avtivity_third);
//获取控件 初始化控件
newOff = findViewById(R.id.new_off);
newCreate = findViewById(R.id.new_create);
newEdtName = findViewById(R.id.new_edtName);
newEdtWord = findViewById(R.id.new_edtWork);
newEdtPhone = findViewById(R.id.new_edtPhone);
Data data = new Data(this);
//点击√创建 增加数据
newCreate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//增加数据
String name = newEdtName.getText().toString().trim();
String work = newEdtWord.getText().toString().trim();
String phone = newEdtPhone.getText().toString().trim();
//创建对象,传入数据到表的行
Phone phones = new Phone(null, name, work, phone);
//判断内容不能为空,才能添加数据成功
if(!name.equals("") && !phone.equals("")){
try {
//<类,id类型>
Dao<Phone,Integer> dao = data.getDao(Phone.class);
dao.create(phones);
//吐司显示提示信息
Toast.makeText(NewActivity.this, "添加" + name + "联系人成功"
,Toast.LENGTH_SHORT).show();
} catch (SQLException | java.sql.SQLException e) {
e.printStackTrace();
}
}else{
Toast.makeText(NewActivity.this, "联系人信息必须包括有姓名以及" +
"电话号码,请重新输入!"
,Toast.LENGTH_LONG).show();
}
}
});
//点击×关闭界面 也相当于取消
newOff.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
finish();
}
});
}
//创建数据库
static class Data extends OrmLiteSqliteOpenHelper {
public Data(Context context) {
super(context, "phoneMessages.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
//真正的生成表
TableUtils.createTable(connectionSource, Phone.class);
} catch (SQLException | java.sql.SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource,
int oldVersion, int newVersion) {
}
}
}
package net.nell.testormlite;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.j256.ormlite.dao.Dao;
import java.sql.SQLException;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private TextView homeAdd;
private EditText homeFind;
private ListView homeList;
private ArrayAdapter adapter;//桥梁 也就是适配器
NewActivity.Data data = new NewActivity.Data(this);//接收添加界面的数据 也就是存到了数据库的数据
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//获取控件
homeAdd = findViewById(R.id.home_add);
homeFind = findViewById(R.id.home_find);
homeList = findViewById(R.id.home_list);
//添加功能
// 通过意图来实现界面跳转 到添加联系人界面
homeAdd.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent intent= new Intent(MainActivity.this, NewActivity.class);
//启动activity
startActivity(intent);
}
});
//列表位置
//获取数据库内的数据 显示添加的信息
try {
Dao<Phone,Integer> dao = data.getDao(Phone.class);
//删除数据库中的所有数据
// File dbFile = new File("/data/data/com.example.taskthree/databases/phoneMessages.db");
// dbFile.delete();
//从数据库中查找到name数据
List<Phone> names = dao.queryBuilder().selectColumns("name").query();
//将names类型转成String
String[] datas = new String[names.size()];
for(int i=0; i< names.size(); i++){
datas[i] = names.get(i).name;
}
//初始化适配器
adapter = new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1,datas);
homeList.setAdapter(adapter);
} catch (SQLException e) {
e.printStackTrace();
}
//搜索栏的位置
//添加监听
homeFind.setOnEditorActionListener(new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//按下回车获取到数据
String text = homeFind.getText().toString().trim();
//在数据库中进行模糊查找
try {
Dao<Phone,Integer> dao = data.getDao(Phone.class);
List<Phone> names = dao.queryBuilder().where().like("name",
"%"+text+"%").query();
//添加数据
String[] datas = new String[names.size()];
for(int i=0; i< names.size(); i++){
datas[i] = names.get(i).name;
}
//初始化适配器
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_expandable_list_item_1,datas);
homeList.setAdapter(adapter);
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
});
}
}
运行效果,添加联系人。
在该项目中,我为了新添加了两个xml文件,其实我们完全可以充分使用原来的activity_main.xml文件进行该程序的完成。本次人物的完成时间花费较长,原因是因为ormlite数据库的相关知识不够成熟,运用不好。下来还会进行该方面知识的深入学习,希望下一次可以更快的解决这样的程序。