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

使用greendao实现搜索历史功能

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

PRE 依赖greendao

greendao.md

WARMING:
[Android]greendao实现搜索历史功能_第2张图片
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
     */
    public static List queryAll() {
        return MyApp.getDaoInstant().getSearchHistoryDao().loadAll();
    }

    /**
     * 清空数据
     */
    public static void clearAll() {
        MyApp.getDaoInstant().getSearchHistoryDao().deleteAll();
    }
}

详细代码方便以后需要copy

xml




    

        

            

            

            
        
    

    

        

            

                

                    

                    
                
            


            

                

                    

                    
                
            
        
    

item




    

        

        

        

        
    

所有ic_的图片为android studio Vector Asset

Adapter

public class SearchAdapter extends RecyclerView.Adapter {
    private Context context;
    private List list;

    public SearchAdapter(Context context, List 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 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实现搜索历史功能)