Android 快速开发系列 ORMLite 框架最佳实践之实现历史记录搜索

首先在build.gald中添加compile 'com.j256.ormlite:ormlite-android:4.48'的引用

 1 compile 'com.j256.ormlite:ormlite-android:4.48' 

之后开始创建DatabaseHelper数据库版主类 基于ormlite,这里以SearchHistroy2.class为例,可以添加很多个运用到数据库的类

 1 public class DatabaseHelper extends OrmLiteSqliteOpenHelper{
 2 
 3     private static final String TABLE_NAME = "pspsp.db";
 4     private static final int DB_VERSION = 3;
 5 
 6     private Map<String, Dao> daos = new HashMap<String, Dao>();
 7 
 8     private DatabaseHelper(Context context)
 9     {
10         super(context, TABLE_NAME, null, DB_VERSION);
11     }
12     @Override
13     public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
14         try
15         {
16             TableUtils.createTable(connectionSource, SearchHistroy2.class);
17         } catch (SQLException e)
18         {
19             e.printStackTrace();
20         }
21     }
22 
23     @Override
24     public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
25         try
26         {
27             TableUtils.dropTable(connectionSource, SearchHistroy2.class, true);
28             onCreate(database, connectionSource);
29         } catch (SQLException e)
30         {
31             e.printStackTrace();
32         }
33     }
34 
35     private static DatabaseHelper instance;
36 
37     /**
38      * 单例获取该Helper
39      *
40      * @param context
41      * @return
42      */
43     public static synchronized DatabaseHelper getHelper(Context context)
44     {
45         context = context.getApplicationContext();
46         if (instance == null)
47         {
48             synchronized (DatabaseHelper.class)
49             {
50                 if (instance == null)
51                     instance = new DatabaseHelper(context);
52             }
53         }
54 
55         return instance;
56     }
57 
58     public synchronized Dao getDao(Class clazz) throws SQLException
59     {
60         Dao dao = null;
61         String className = clazz.getSimpleName();
62 
63         if (daos.containsKey(className))
64         {
65             dao = daos.get(className);
66         }
67         if (dao == null)
68         {
69             dao = super.getDao(clazz);
70             daos.put(className, dao);
71         }
72         return dao;
73     }
74 
75     /**
76      * 释放资源
77      */
78     @Override
79     public void close()
80     {
81         super.close();
82 
83         for (String key : daos.keySet())
84         {
85             Dao dao = daos.get(key);
86             dao = null;
87         }
88     }
89 
90 }

好!主类写好了,下面我们要对每个Bean创建一个XXXDao来处理当前Bean的数据库操作,当然真正去和数据库打交道的对象,通过上面代码中的getDao(T t)进行获取

getDao为一个泛型方法,会根据传入Class对象进行创建Dao,并且使用一个Map来保持所有的Dao对象,只有第一次调用时才会去调用底层的getDao()。

 1 public class SearchDao2 {
 2 
 3     private Context context;
 4     private Dao<SearchHistroy2, Integer> userDaoOpe;
 5     private DatabaseHelper helper;
 6 
 7     public SearchDao2(Context context) {
 8         this.context = context;
 9         try {
10             helper = DatabaseHelper.getHelper(context);
11             userDaoOpe = helper.getDao(SearchHistroy2.class);
12         } catch (SQLException e) {
13             e.printStackTrace();
14         }
15     }
16     /**
17      * 增加一个用户
18      *
19      * @param model
20      */
21     public void add(SearchHistroy2 model) {
22         try {
23             SearchHistroy2 searchHistroy = userDaoOpe.queryBuilder().where().eq("name", model.getName()).queryForFirst();
24             if (searchHistroy == null || StringUtils.isEmpty(searchHistroy.getName()) && !StringUtils.isEmpty(model.getName())) {
25                 userDaoOpe.create(model);
26             }
27         } catch (SQLException e) {
28             e.printStackTrace();
29         }
30     }
31     /**
32      * 清楚所有
33      */
34     public void deteAll() {
35         try {
36             userDaoOpe.deleteBuilder().delete();
37         } catch (SQLException e) {
38             e.printStackTrace();
39         }
40 
41     }
42 
43     /**
44      * 获取所有查询记录
45      *
46      * @return
47      */
48     public List<SearchHistroy2> getAllList() {
49         try {
50             return userDaoOpe.queryForAll();
51         } catch (SQLException e) {
52             e.printStackTrace();
53             return new ArrayList<SearchHistroy2>();
54         }
55     }
56 }

其实在写Dao文件之前应该现在数据中建表

@DatabaseTable(tableName = "search_history2")
public class SearchHistroy2 {

    @DatabaseField(generatedId = true)
    private int id;

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

    private boolean isDelete=false;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isDelete() {
        return isDelete;
    }

    public void setIsDelete(boolean isDelete) {
        this.isDelete = isDelete;
    }

    //    @DatabaseField(canBeNull = true, foreign = true, columnName = "user_id")
//    private User user;
}

数据库建表以及对表的增删改查的方法准备好了,现在就以历史列表的搜索为例进行增删改查了

 

@ContentView(R.layout.activity_comm_search)
public class CommSearch2Activity extends BaseAppActivity implements UITableViewDelegate {

    private EditText edtValue;
    private SearchDao2 searchDao;

    @ViewInject(R.id.recyclerView)
    private RecyclerView recyclerView;
    private List<SearchHistroy2> list;
    @Override
    protected void init() {
        searchDao = new SearchDao2(this);
        list = new ArrayList<SearchHistroy2>();
        setCustomView(R.layout.view_search_top2);
        edtValue = (EditText) findViewById(R.id.edtValue);
        edtValue.clearFocus();
        list = searchDao.getAllList();
        recyclerView.setDelegate(this);
        recyclerView.setDataSource(list);
        recyclerView.getRecyclerView().addItemDecoration(new DividerItemDecoration(this, DividerLineDecoration.VERTICAL, true));
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        mToolbarManager.createMenu(R.menu.menu_search);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.tb_add) {
            String strValue = edtValue.getText().toString().trim();
            strValue = strValue.replace("", "");
            if (!StringUtils.isEmpty(strValue)) {
                SearchHistroy2 histroy = new SearchHistroy2();
                histroy.setName(strValue);
                searchDao.add(histroy);
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public android.support.v7.widget.RecyclerView.ViewHolder getItemViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(this).inflate(R.layout.list_item_serch_history, viewGroup, false);
        return new MyViewHolder(view);
    }
    @Override
    public void onBindData(BaseViewHolder baseViewHolder, int i) {
        MyViewHolder holder = (MyViewHolder) baseViewHolder;
        final SearchHistroy2 histroy = list.get(i);
        holder.txtV.setText(histroy.getName());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchDao.add(histroy);
            }
        });

        if (i == list.size() - 1) {
            holder.btnClean.setVisibility(View.VISIBLE);
            holder.btnClean.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    searchDao.deteAll();
                    list.clear();
                    recyclerView.setDataSource(list);
                }
            });
        } else
            holder.btnClean.setVisibility(View.GONE);
    }

    private class MyViewHolder extends BaseViewHolder {
        private TextView txtV;
        private View btnClean;

        public MyViewHolder(View itemView) {
            super(itemView);
            this.txtV = (TextView) itemView.findViewById(R.id.txtValue);
            this.btnClean = itemView.findViewById(R.id.btnClean);
        }

        @Override
        public void onClick(View view) {
        }

        @Override
        public boolean onLongClick(View view) {
            return false;
        }
    }

}

 

界面大概是这样的

希望帮到大家了

 

posted on 2017-01-13 11:27  oooo呼呼  阅读(360)  评论(0编辑  收藏  举报