Ormlite快速实战

github代码直通车

啥也不说了,先上效果图:
创建数据:


Ormlite快速实战_第1张图片
giphy.gif

修改数据:


Ormlite快速实战_第2张图片
giphy.gif

删除数据:


Ormlite快速实战_第3张图片
giphy.gif

引入Ormlite库:

    compile 'com.j256.ormlite:ormlite-android:5.0'

各种注解含义:

  • @DatabaseTable(tableName = "tb_note")
    表示根据该类创建名为tb_note的表

  • @DatabaseField(columnName = "title")
    表示在表中创建名为title的字段

  • @DatabaseField(defaultValue="男")
    表示该属性值默认为“男”

  • @DatabaseField(id = true)
    作为数据库的id

  • @DatabaseField(generatedid = "")
    数据库自增长id

  • @DatabaseField(useGetSet = true)
    是否使用get set方法进行映射,为true时表示使用get set方法,
    建议设置为true,可以提升性能

ORMLite为我们提供了全面的字段属性的支持,更多属性:

cloumnName:指定字段名,不指定则变量名作为字段名
canBeNull:是否可以为null
dataType:指定字段的类型
foreign 指定这个字段的对象是一个外键,外键值是这个对象的id
foreignAutoCreate 外键不存在时是否自动添加到外间表中
foreignAutoRefresh 外键值,自动刷新
foreignColumnName外键字段指定的外键表中的哪个字段
generatedId:指定字段为自增长的id,不能id,generatedIdSequence通用
id:指定字段为id
index:索引
persisted:指定是否持久化此变量,默认true
throwIfNull,如果空值抛出异常
useGetSet:指定ormlite访问变量使用set,get方法默认使用的是反射机制直接访问变量
unique:字段值唯一
uniqueIndex 唯一索引
uniqueCombo整列的值唯一

创建实体类并设置属性对应:

ORMlite通过Java注解的方式来建立起与数据库的映射关系。注:实体类带有参构造函数,必须要有无参构造函数。
创建实体类对应Note表:

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

@DatabaseTable(tableName = "tb_note")
public class NoteBean {
    @DatabaseField(id = true,columnName = "noteid")
    private int noteId;
    @DatabaseField(columnName = "title")
    private String title;
    @DatabaseField(columnName = "content")
    private String content;
    @DatabaseField(columnName = "date")
    private String date;
    @DatabaseField(columnName = "textnum")
    private int textNum;

    public NoteBean(){}

    public NoteBean(int noteId,String title, String content, String date, int textNum) {
        this.noteId = noteId;
        this.title = title;
        this.content = content;
        this.date = date;
        this.textNum = textNum;
    }

    public int getNoteId() {
        return noteId;
    }

    public void setNoteId(int noteId) {
        this.noteId = noteId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public int getTextNum() {
        return textNum;
    }

    public void setTextNum(int textNum) {
        this.textNum = textNum;
    }
}

创建Ormlite数据库操作类:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
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.HashMap;
import java.util.Map;

public class OrmliteOpenHelper extends OrmLiteSqliteOpenHelper{
    private static final String TABLE_NAME = "sqlite.db";

    private Map daos = new HashMap();

    private OrmliteOpenHelper(Context context) {
        super(context, TABLE_NAME, null, 1);
    }

    private static OrmliteOpenHelper instance;

    /**
     * 单例获取该Helper
     *
     * @param context
     * @return
     */
    public static synchronized OrmliteOpenHelper getHelper(Context context) {
        context = context.getApplicationContext();
        if (instance == null) {
            synchronized (OrmliteOpenHelper.class) {
                if (instance == null)
                    instance = new OrmliteOpenHelper(context);
            }
        }
        return instance;
    }

    public OrmliteOpenHelper(Context context, String databaseName, SQLiteDatabase.CursorFactory factory, int databaseVersion) {
        super(context, databaseName, factory, databaseVersion);
    }

    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
        try {
            //根据实体类创建对应表
            TableUtils.createTable(connectionSource,NoteBean.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        try {
            //根据实体类删除对应表
            TableUtils.dropTable(connectionSource,NoteBean.class,true);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取类对应操作Dao类
     * @param clazz
     * @return
     * @throws SQLException
     */
    public synchronized Dao getDao(Class clazz) throws SQLException {
        Dao dao = null;
        String className = clazz.getSimpleName();

        if (daos.containsKey(className)) {
            dao = daos.get(className);
        }
        if (dao == null) {
            dao = super.getDao(clazz);
            daos.put(className, dao);
        }
        return dao;
    }


    /**
     * 释放资源
     */
    @Override
    public void close() {
        super.close();

        for (String key : daos.keySet()) {
            Dao dao = daos.get(key);
            dao = null;
        }
    }
}

创建数据库操作Dao类,使用Ormlite自带方法实现增删查改
import android.content.Context;
import com.j256.ormlite.dao.Dao;
import java.sql.SQLException;
import java.util.List;

public class NoteDao{
    private Dao noteDao;

    public NoteDao(Context context){
        try {
            noteDao = OrmliteOpenHelper.getHelper(context).getDao(NoteBean.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void insert(NoteBean noteBean){
        try {
            noteDao.create(noteBean);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void del(NoteBean noteBean){
        try {
            noteDao.delete(noteBean);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void update(NoteBean noteBean){
        try {
            noteDao.update(noteBean);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public NoteBean queryForId(int id){
        try {
            return noteDao.queryForId(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List queryAll(){
        try {
            return noteDao.queryForAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

}

MainActivity类:

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private CommonAdapter adapter;
    private ArrayList datas = new ArrayList<>();
    private NoteDao noteDao;

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

        init();
    }

    @Override
    protected void onResume() {
        super.onResume();

        loadData();
    }

    private void init() {
        noteDao = new NoteDao(this);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        adapter = new CommonAdapter(getApplicationContext(),R.layout.item,datas) {
            @Override
            protected void convert(ViewHolder holder, NoteBean noteBean, int position) {
                holder.setText(R.id.tv_title,noteBean.getTitle());
                holder.setText(R.id.tv_content,noteBean.getContent());
                holder.setText(R.id.tv_date,noteBean.getDate());
                holder.setText(R.id.tv_num,"字数 " + noteBean.getTextNum());
            }
        };
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Intent intent = new Intent(MainActivity.this,InputActivity.class);
                intent.putExtra("id",datas.get(position).getNoteId());
                startActivity(intent);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                noteDao.del(datas.get(position));
                loadData();
                return false;
            }
        });
    }

    private void loadData(){
        datas.clear();
        List list = noteDao.queryAll();
        datas.addAll(list);
        adapter.notifyDataSetChanged();
    }

    public void addData(View view){
        Intent intent = new Intent(this,InputActivity.class);
        startActivity(intent);
    }
}

InputActivity输入:

import android.icu.text.SimpleDateFormat;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.util.Date;

public class InputActivity extends AppCompatActivity {
    private EditText etTitle;
    private EditText etContent;
    private TextView tvSave;
    private int noteId;
    private NoteBean noteBean;
    //-1表示创建笔记,否则为修改
    private int CREATE_TYPE = -1;
    private String dateFormate = "YYYY-MM-dd hh:mm:ss";

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

        init();
    }

    private void init(){
        etTitle = (EditText) findViewById(R.id.et_title);
        etContent = (EditText) findViewById(R.id.et_content);
        tvSave = (TextView) findViewById(R.id.tv_save);

        noteId = getIntent().getIntExtra("id",CREATE_TYPE);

        if(noteId != CREATE_TYPE){
            noteBean = new NoteDao(this).queryForId(noteId);
            etTitle.setText(noteBean.getTitle());
            etContent.setText(noteBean.getContent());

            tvSave.setText("修改");
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void save(View view){
        String title = etTitle.getText().toString().trim();
        String content = etContent.getText().toString().trim();

        if(!TextUtils.isEmpty(title) && !TextUtils.isEmpty(content)){
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormate);
            String date = sdf.format(new Date());
            if(noteId != CREATE_TYPE){  //修改模式
                noteBean.setTitle(title);
                noteBean.setContent(title);
                new NoteDao(this).update(noteBean);
            }else{   //创建模式
                NoteBean bean = new NoteBean((int) System.currentTimeMillis(),title,content,date,content.length());
                new NoteDao(this).insert(bean);
            }

            finish();
        }
    }

}

你可能感兴趣的:(Ormlite快速实战)