安卓开发学习——day7

文章目录

  • 前言
  • 一、Ormlte
  • 二、使用Ormlite
    • 1.引入库
    • 2.新建ContactsInfo(联系人信息表)
    • 3.新建DatabaseHelper(生成数据库结构信息)
    • 4.测试
  • 三、完善通讯录的关于Ormlite的功能
    • 1.添加联系人
    • 2.读取联系人
    • 3.查找联系人
    • 4.效果图
  • 遇到的问题
      • 问题1
  • 总结


前言

ormlite看起来挺简单,其实做起来挺恼火的,昨天做了很久,但是没实现效果,就没有写博客


一、Ormlte

Ormlite全称Object Relational Mapping,是一个非常轻量级的数据库操作框架,它的底层是根据反射机制来实现的。
ormlite的使用:
新建表,借用别人的图:
安卓开发学习——day7_第1张图片
增删改查:ORMLite简介和增删改查方法的使用

二、使用Ormlite

1.引入库

这个我在上一个里面写到了:安卓开发学习——day6

2.新建ContactsInfo(联系人信息表)

注意:生成空的构造方法,不然报错;生成get|set方法,方便调用

package com.example.task3.entity;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

//表名
@DatabaseTable(tableName = "contacts")
public class ContactsInfo {
     
    @DatabaseField(columnName = "id", generatedId = true)
    public int id; //设置主键

    @DatabaseField(columnName = "contactName")
    private String contactName;

    @DatabaseField(columnName = "contactCompany")
    private String contactCompany;

    @DatabaseField(columnName = "contactTel")
    private String contactTel;

    public ContactsInfo() {
     
    }

    public int getId() {
     
        return id;
    }

    public void setId(int id) {
     
        this.id = id;
    }

    public String getContactName() {
     
        return contactName;
    }

    public void setContactName(String contactName) {
     
        this.contactName = contactName;
    }

    public String getContactCompany() {
     
        return contactCompany;
    }

    public void setContactCompany(String contactCompany) {
     
        this.contactCompany = contactCompany;
    }

    public String getContactTel() {
     
        return contactTel;
    }

    public void setContactTel(String contactTel) {
     
        this.contactTel = contactTel;
    }
}

3.新建DatabaseHelper(生成数据库结构信息)

继承继承OrmLiteSqliteOpenHelper类,重写 onCreate\onUpgrade方法

package com.example.task3.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.example.task3.entity.ContactsInfo;
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;


/**
 * 定义数据库的工具类,继承OrmLiteSqliteOpenHelper类,重写 onCreate\onUpgrade方法
 */
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
     

    //定义数据库存放位置,便于以后查看
    public static final String DATABASE_PATH = "mydb.db";
    //定义数据库的版本号,当数据库需要升级时进行更改
    public static final int DATABASE_VERSION = 1;

    public DatabaseHelper(Context context) {
     
        super(context, DATABASE_PATH, null, DATABASE_VERSION);
    }

    public Dao<ContactsInfo, Integer> contactsInfoDao;

    public Dao<ContactsInfo, Integer> getContactsInfoDao() {
     
        if (contactsInfoDao == null) {
     
            try {
     
                contactsInfoDao = getDao(ContactsInfo.class);
            } catch (SQLException e) {
     
                e.printStackTrace();
            }
        }

        return contactsInfoDao;
    }


    /***
     * 第一次创建数据库创建
     * @param database
     * @param connectionSource
     */
    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
     
        try {
     
            TableUtils.createTable(connectionSource, ContactsInfo.class);
        } catch (SQLException e) {
     
            e.printStackTrace();
        }
    }

    /***
     * 升级数据库时调用
     * @param database
     * @param connectionSource
     * @param oldVersion
     * @param newVersion
     */
    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
     
        if (newVersion > oldVersion) {
     
            try {
     
                TableUtils.dropTable(connectionSource, ContactsInfo.class, true);
                TableUtils.createTableIfNotExists(connectionSource, ContactsInfo.class);
            } catch (SQLException e) {
     
                e.printStackTrace();
            }
        }
    }

    @Override
    public void close() {
     
        super.close();
        if (contactsInfoDao != null) {
     
            contactsInfoDao = null;
        }
    }
}

4.测试

xml只需要3个输入框和两个按钮

package com.example.task3;

import android.database.SQLException;
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.task3.db.DatabaseHelper;
import com.example.task3.entity.ContactsInfo;
import com.j256.ormlite.dao.Dao;

import java.util.List;

public class TestOrmActivity extends AppCompatActivity implements View.OnClickListener {
     

    private EditText edtName;
    private EditText edtCompany;
    private EditText edtTel;

    private Button btnInsert;
    private Button btnRead;

    private DatabaseHelper dbHelper;

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

        edtName = findViewById(R.id.edt_name);
        edtCompany = findViewById(R.id.edt_company);
        edtTel = findViewById(R.id.edt_tel);

        btnInsert = findViewById(R.id.btn_);
        btnRead = findViewById(R.id.btn_read);

        btnInsert.setOnClickListener(this);
        btnRead.setOnClickListener(this);


    }



    @Override
    public void onClick(View view) {
     
        if (dbHelper==null){
     
            dbHelper = new DatabaseHelper(TestOrmActivity.this);
        }
        int id = view.getId();
        switch (id){
     
            case R.id.btn_:
                //插入数据
                String name  = edtName.getText().toString();
                String company = edtCompany.getText().toString();
                String tel = edtTel.getText().toString();
                //获取操作表的dao对象
                Dao<ContactsInfo,Integer> contactsInfoDao = dbHelper.getContactsInfoDao();
                //插入对应的数据
                ContactsInfo contactsInfo = new ContactsInfo();
                contactsInfo.setContactName(name);
                contactsInfo.setContactCompany(company);
                contactsInfo.setContactTel(tel);
                try {
     
                    //通过操作实体对象的形式将数据插入到表中
                    contactsInfoDao.createIfNotExists(contactsInfo);
                } catch (SQLException | java.sql.SQLException e) {
     
                    e.printStackTrace();
                }


                break;
            case R.id.btn_read:
                //读取数据
                Dao<ContactsInfo ,Integer> contactsInfoList = dbHelper.getContactsInfoDao();
                try {
     
                    List<ContactsInfo> contactsInfoDataList =  contactsInfoList.queryForAll();

                    StringBuffer strBuffer = new StringBuffer();
                    for(int i =0;i<contactsInfoDataList.size();i++){
     
                        strBuffer.append("第"+i+"位置的word="+contactsInfoDataList.get(i).getContactName()+";单词的含义"+contactsInfoDataList.get(i).getContactTel()+"\n");
                    }

                    Toast.makeText(TestOrmActivity.this, strBuffer.toString(), Toast.LENGTH_SHORT).show();

                } catch (SQLException | java.sql.SQLException e) {
     
                    e.printStackTrace();
                }

                break;

        }
    }
}


安卓开发学习——day7_第2张图片

三、完善通讯录的关于Ormlite的功能

1.添加联系人

package com.example.task3;

import android.content.Intent;
import android.database.SQLException;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.task3.db.DatabaseHelper;
import com.example.task3.entity.ContactsInfo;
import com.j256.ormlite.dao.Dao;

public class AddActivity extends AppCompatActivity implements View.OnClickListener {
     
    private ImageView ok;
    private ImageView cancel;
    private EditText edtName;
    private EditText edtCompany;
    private EditText edtTel;

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

        ok = findViewById(R.id.ok);
        cancel = findViewById(R.id.cancel);
        edtName = findViewById(R.id.edt_name);
        edtCompany = findViewById(R.id.edt_company);
        edtTel = findViewById(R.id.edt_tel);

        ok.setOnClickListener(this);
        cancel.setOnClickListener(this);

    }

    private DatabaseHelper dbHelper;

    @Override
    public void onClick(View v) {
     
        if (dbHelper == null) {
     
            dbHelper = new DatabaseHelper(AddActivity.this);
        }
        int id = v.getId();
        switch (id) {
     
            case R.id.ok:
                //插入数据
                String name = edtName.getText().toString();
                String company = edtCompany.getText().toString();
                String tel = edtTel.getText().toString();
                //获取操作表的dao对象
                Dao<ContactsInfo, Integer> contactsInfoDao = dbHelper.getContactsInfoDao();
                //插入对应的数据
                ContactsInfo contactsInfo = new ContactsInfo();
                contactsInfo.setContactName(name);
                contactsInfo.setContactCompany(company);
                contactsInfo.setContactTel(tel);
                try {
     
                    //通过操作实体对象的形式将数据插入到表中
                    contactsInfoDao.createIfNotExists(contactsInfo);
                } catch (SQLException | java.sql.SQLException e) {
     
                    e.printStackTrace();
                }

                Toast.makeText(AddActivity.this, "添加" + edtName.getText().toString() + "成功"
                        , Toast.LENGTH_LONG).show();

                Intent intent = new Intent(AddActivity.this, MainActivity.class);
                startActivity(intent);

                break;
            case R.id.cancel:
                intent = new Intent(AddActivity.this, MainActivity.class);
                startActivity(intent);

                break;

        }
    }
}

2.读取联系人

package com.example.task3;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.task3.db.DatabaseHelper;
import com.example.task3.entity.ContactsInfo;
import com.j256.ormlite.dao.Dao;

import java.sql.SQLException;
import java.util.List;

public class MainActivity extends AppCompatActivity{
     

    private TextView tvAdd;
    private EditText edtSo;
    private ListView lvContacts;
    private ImageView find;

    private ContactAdapter adapter;

    DatabaseHelper dbHelper = new DatabaseHelper(this);


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

        tvAdd = findViewById(R.id.tv_add);
        edtSo = findViewById(R.id.edt_find_contact);
        lvContacts = findViewById(R.id.lv_contacts);
        find = findViewById(R.id.find);

        try {
     
            Dao<ContactsInfo, Integer> dao = dbHelper.getDao(ContactsInfo.class);

            List<ContactsInfo> contact = dao.queryBuilder().selectColumns("contactName").query();

            adapter = new ContactAdapter(MainActivity.this,contact);
            lvContacts.setAdapter(adapter);
        } catch (SQLException e) {
     
            e.printStackTrace();
        }

        edtSo.setOnEditorActionListener(new TextView.OnEditorActionListener() {
     
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
     
                String text = edtSo.getText().toString().trim();
                try {
     
                    Dao<ContactsInfo, Integer> dao = dbHelper.getDao(ContactsInfo.class);
                    List<ContactsInfo> contact = dao.queryBuilder().where().like("contactName","%"+text+"%").query();

                    //初始化适配器
                    ContactAdapter findAdapter = new ContactAdapter(MainActivity.this, contact);
                    lvContacts.setAdapter(findAdapter);
                } catch (SQLException e) {
     
                    e.printStackTrace();
                }
                return false;
            }
        });



        tvAdd.setOnClickListener(new View.OnClickListener() {
     
            @Override
            public void onClick(View v) {
     
                Intent intent = new Intent(MainActivity.this, AddActivity.class);

                startActivity(intent);
            }
        });


    }

}

3.查找联系人

4.效果图

安卓开发学习——day7_第3张图片

遇到的问题

问题1

ormlite E/SQLiteLog: (1) no such table: contacts

解决方法:
已经创建过诸如contacts表之后,部署到手机上,此时数据库已经初始化完成.但是现在有需求又新加了一个表,此时代码都写完了,此时部署到手机上,调用新表里面的ContactInfoDao.create(bean)方法会出现no such table错误.
把原来安装的app卸载重新部署。

总结

ormlite数据库因为没有找到较为完整的教程,所以用时比较久,写的还不够完善。

你可能感兴趣的:(安卓学习)