美文网首页
[Android]greendao实现搜索历史功能

[Android]greendao实现搜索历史功能

作者: jjkopen | 来源:发表于2017-08-31 10:42 被阅读109次

    使用greendao实现搜索历史功能

    ezgif-1-378e749b52.gif device-2017-08-31-103330.png
    之前封装sqlite实现过这功能,不过原生封装使用sql语句,而且greendao功能更强大(对不会sql的我来说更方便写),So...

    PRE 依赖greendao

    greendao.md

    WARMING: methodscount.com.png

    greendao实体

    @Entity
    public class SearchHistory {
        @Id(autoincrement = true) //自增主键
        private Long id;
        @Unique // 搜索记录(唯一)
        private String name;
    }
    
    build gradle | make project(ctrl + F9),自动生成代码

    public class MyApp extends Application {
        private static MyApp instance;
    
        private static DaoSession daoSession;
    
        public static MyApp getInstance() {
            return instance;
        }
    
        public static DaoSession getDaoInstant() {
            return daoSession;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
            instance = this;
            setupDatabase("database.db");
        }
    
        /**
         * 配置数据库
         */
        private void setupDatabase(String name) {
            //创建数据库
            DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, name, null);
            //获取可写数据库
            SQLiteDatabase db = helper.getWritableDatabase();
            //获取数据库对象
            DaoMaster daoMaster = new DaoMaster(db);
            //获取Dao对象管理者
            daoSession = daoMaster.newSession();
        }
    }
    
    public class SearchHistoryDao {
    
        /**
         * 添加数据
         *
         * @param searchHistory
         */
        public static void insertHistory(SearchHistory searchHistory) {
            MyApp.getDaoInstant().getSearchHistoryDao().insertOrReplace(searchHistory);
        }
    
        /**
         * 删除数据
         *
         * @param searchHistory
         */
        public static void deleteHistory(SearchHistory searchHistory) {
            MyApp.getDaoInstant().getSearchHistoryDao().delete(searchHistory);
        }
    
        /**
         * 查询全部数据
         *
         * @return List<SearchHistory>
         */
        public static List<SearchHistory> queryAll() {
            return MyApp.getDaoInstant().getSearchHistoryDao().loadAll();
        }
    
        /**
         * 清空数据
         */
        public static void clearAll() {
            MyApp.getDaoInstant().getSearchHistoryDao().deleteAll();
        }
    }
    

    详细代码方便以后需要copy

    xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#1E8AE8">
    
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="48dp"
                android:layout_margin="8dp"
                android:background="@android:color/white"
                android:gravity="center_vertical">
    
                <ImageView
                    android:id="@+id/btn_back"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="6dp"
                    android:layout_marginRight="6dp"
                    android:padding="6dp"
                    android:src="@drawable/ic_arrow_left"
                    android:tint="@android:color/darker_gray" />
    
                <EditText
                    android:id="@+id/edit_search"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="@android:color/white"
                    android:hint="搜索知乎内容"
                    android:imeOptions="actionSearch"
                    android:inputType="text"
                    android:maxLines="1" />
    
                <ImageView
                    android:id="@+id/btn_searchdelete"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:paddingLeft="6dp"
                    android:paddingRight="6dp"
                    android:src="@drawable/ic_delete"
                    android:tint="@android:color/darker_gray"
                    android:visibility="gone"
                    tools:visibility="visible" />
            </LinearLayout>
        </LinearLayout>
    
        <android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">
    
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">
    
                <android.support.v7.widget.CardView
                    android:id="@+id/recommandsearch"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="8dp">
    
                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:gravity="center_vertical">
    
                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="6dp"
                            android:padding="6dp"
                            android:src="@drawable/ic_search" />
    
                        <TextView
                            android:id="@+id/tv_recommandsearch"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:layout_marginLeft="16dp"
                            android:gravity="center_vertical"
                            tools:text="演技能烂到什么程度"
                            android:textColor="@android:color/black"
                            android:textSize="16dp" />
                    </LinearLayout>
                </android.support.v7.widget.CardView>
    
    
                <android.support.v7.widget.CardView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="8dp">
    
                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical">
    
                        <android.support.v7.widget.RecyclerView
                            android:id="@+id/listview_search_history"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" />
    
                        <TextView
                            android:id="@+id/btn_clearall"
                            android:layout_width="match_parent"
                            android:layout_height="48dp"
                            android:gravity="center"
                            android:text="清除历史记录"
                            android:textColor="@android:color/holo_blue_light" />
                    </LinearLayout>
                </android.support.v7.widget.CardView>
            </LinearLayout>
        </android.support.v4.widget.NestedScrollView>
    </LinearLayout>
    

    item

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:layout_marginLeft="12dp"
            android:layout_marginRight="12dp">
    
            <ImageView
                android:id="@+id/icon"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_centerVertical="true"
                android:paddingRight="6dp"
                android:src="@drawable/ic_history"
                android:tint="@android:color/darker_gray" />
    
            <TextView
                android:id="@+id/tv_recommandsearch"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="16dp"
                android:layout_marginRight="8dp"
                android:layout_toLeftOf="@id/btn_delete"
                android:layout_toRightOf="@id/icon"
                android:ellipsize="end"
                android:gravity="center_vertical"
                android:lines="1"
                android:text="演技能烂到什么程度"
                android:textSize="16dp" />
    
            <ImageView
                android:id="@+id/btn_delete"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:paddingLeft="6dp"
                android:src="@drawable/ic_delete"
                android:tint="@android:color/darker_gray" />
    
            <View
                android:layout_width="match_parent"
                android:layout_height="0.5dp"
                android:layout_alignParentBottom="true"
                android:background="@android:color/black" />
        </RelativeLayout>
    </LinearLayout>
    
    所有ic_的图片为android studio Vector Asset

    Adapter

    public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.ViewHolder> {
        private Context context;
        private List<SearchHistory> list;
    
        public SearchAdapter(Context context, List<SearchHistory> list) {
            this.context = context;
            this.list = list;
        }
    
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_search_history, parent, false));
        }
    
        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            holder.tvRecommandsearch.setText(list.get(position).getName());
            holder.btnDelete.setOnClickListener(view -> deleteListener.OnDelete(position));
            holder.itemView.setOnClickListener(view -> itemClickListener.OnItemClick(position));
        }
    
        @Override
        public int getItemCount() {
            return list.size();
        }
    
        class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.tv_recommandsearch)
            TextView tvRecommandsearch;
            @BindView(R.id.btn_delete)
            ImageView btnDelete;
    
            ViewHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    
        private OnDeleteListener deleteListener;
        private OnItemClickListener itemClickListener;
    
        public interface OnDeleteListener {
            void OnDelete(int position);
        }
    
        public interface OnItemClickListener {
            void OnItemClick(int position);
        }
    
        public void setOnDeleteListener(OnDeleteListener deleteListener) {
            this.deleteListener = deleteListener;
        }
    
        public void setOnItemClickListener(OnItemClickListener itemClickListener) {
            this.itemClickListener = itemClickListener;
        }
    }
    

    Activity

    public class SearchActivity extends BaseActivity {
        @BindView(R.id.btn_back)
        ImageView btnBack;
        @BindView(R.id.edit_search)
        EditText editSearch;
        @BindView(R.id.btn_searchdelete)
        ImageView btnSearchdelete;
        @BindView(R.id.tv_recommandsearch)
        TextView tvRecommandsearch;
        @BindView(R.id.recommandsearch)
        CardView recommandSearch;
        @BindView(R.id.listview_search_history)
        RecyclerView listview;
        @BindView(R.id.btn_clearall)
        TextView btnClearall;
    
        private final int DELETEONE = 0X001;
        private final int DELETEALL = 0X002;
    
        private SearchAdapter adapter;
        private List<SearchHistory> list;
    
        @Override
        protected void bindViews() {
            setContentView(R.layout.activity_search);
        }
    
        @Override
        protected void initView() {
    
        }
    
        @Override
        protected void initData() {
            tvRecommandsearch.setText(getIntent().getStringExtra("recommandsearch"));
            recommandSearch.setOnClickListener(view -> {
                editSearch.setText(tvRecommandsearch.getText());
                insertHistory();
            });
            list = new ArrayList<>();
            adapter = new SearchAdapter(this, list);
            listview.setLayoutManager(new LinearLayoutManager(this));
            listview.setAdapter(adapter);
            adapter.setOnDeleteListener(position -> deleteHistory(DELETEONE, position));
            adapter.setOnItemClickListener(position -> {
                editSearch.setText(list.get(position).getName());
                insertHistory();
            });
            btnClearall.setOnClickListener(view -> showDeleteDialog());
            queryHistory();
        }
    
        @Override
        protected void initActionBar() {
            btnBack.setOnClickListener(view -> finish());
            editSearch.setOnEditorActionListener((textView, i, keyEvent) -> {
                if (i == EditorInfo.IME_ACTION_SEARCH && !TextUtils.isEmpty(editSearch.getText().toString().trim())) {
                    ToastUtils.shortToast(editSearch.getText().toString().trim());
                    insertHistory();
                }
                return true;
            });
            editSearch.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    
                }
    
                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    if (charSequence.toString().length() > 0) {
                        btnSearchdelete.setVisibility(View.VISIBLE);
                    } else {
                        btnSearchdelete.setVisibility(View.GONE);
                    }
                }
    
                @Override
                public void afterTextChanged(Editable editable) {
    
                }
            });
            btnSearchdelete.setOnClickListener(view -> editSearch.setText(""));
        }
    
        private void showDeleteDialog() {
            new AlertDialog.Builder(this)
                    .setMessage("确认清除所有搜索记录吗?")
                    .setPositiveButton("确定", (dialogInterface, i) -> deleteHistory(DELETEALL, 1))
                    .setNegativeButton("取消", null)
                    .setCancelable(true)
                    .create().show();
        }
    
        private void insertHistory() {
            SearchHistory searchHistory = new SearchHistory();
            searchHistory.setName(editSearch.getText().toString().trim());
            SearchHistoryDao.insertHistory(searchHistory);
            queryHistory();
        }
    
        private void deleteHistory(int TAG, int position) {
            if (TAG == DELETEONE)
                SearchHistoryDao.deleteHistory(list.get(position));
            else if (TAG == DELETEALL)
                SearchHistoryDao.clearAll();
            queryHistory();
        }
    
        private void queryHistory() {
            list.clear();
            list.addAll(SearchHistoryDao.queryAll());
            Collections.reverse(list);
            adapter.notifyDataSetChanged();
        }
    }
    

    SearchHistoryDao有命名问题的坑,踩踩更健康

    相关文章

      网友评论

          本文标题:[Android]greendao实现搜索历史功能

          本文链接:https://www.haomeiwen.com/subject/fddxjxtx.html