如何从sqlite数据库搜索数据并查看到RecyclerView

时间:2018-12-13 06:35:37

标签: android database sqlite android-recyclerview

我正在从API接收数据并能够保存到数据库中,但是无法将这些数据显示到RecyclerView中,我想通过SearchView.onQueryTextListener搜索数据。

  
      
  1. 这是我的活动类ClientView.java
  2.   
public class ClientView extends AppCompatActivity implements SearchView.OnQueryTextListener {
    private static final String TAG = "ClientView";

    ClientDatabase db;
    ClientModel clientModel;
    RequestQueue requestQueue;
    Context context;
    RecyclerView recyclerView;
    CRecyclerAdapter adapter;
    private ArrayList<ClientModel> clientModelsList;

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

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        RequestData();
        initView();
        initObjects();
    }

    public void initView(){
        recyclerView = (RecyclerView)findViewById(R.id.recycler_view_);
    }

    public void initObjects(){
        Log.d(TAG, "InitObjects: initializing");
        clientModelsList = new ArrayList<>();
        adapter = new CRecyclerAdapter(clientModelsList, this);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
        getDataFromSQLite();
    }

    public void RequestData(){
        Log.d(TAG, "RequestData: Requesting Data from API");
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        String url = getResources().getString(R.string.url);
        JSONObject jsonObject = new JSONObject();
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray info = response.getJSONArray("response");
                    ClientDatabase clientDatabase = new ClientDatabase(getApplicationContext());
                    Log.d(TAG, "onResponse: Inserting data into Database");
                    for (int i =0; i<info.length(); i++){
                        JSONObject jsonObject = info.getJSONObject(i);
                        ClientModel clientModel = new ClientModel();
                        clientModel.setClient_name(jsonObject.getString("client_name"));
                        clientModel.setAddress(jsonObject.getString("address"));
                        clientModel.setNote(jsonObject.getString("note"));
                        clientModel.setCp_name(jsonObject.getString("cp_name"));
                        clientModel.setCp_phone(jsonObject.getString("cp_phone"));
                        clientModel.setCp_email(jsonObject.getString("cp_email"));
                        clientModel.setAssign_person_name(jsonObject.getString("assign_person_name"));
                        clientDatabase.AddClient(clientModel);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), "Error in saving",Toast.LENGTH_LONG).show();
            }
        });
        requestQueue.add(jsonObjectRequest);
    }

    public void getDataFromSQLite(){
        Log.d(TAG, "getDataFromSqlite: called");
        new AsyncTask<Void, Void, Void>(){
            @Override
            protected Void doInBackground(Void... voids) {
                try {
                    clientModelsList.clear();
                    clientModelsList.addAll(db. getListedData());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                adapter.notifyDataSetChanged();
            }
        }.execute();
    }

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        MenuItem search = menu.findItem(R.id.search);
        SearchView searchView = (SearchView)search.getActionView();
        searchView.setOnQueryTextListener(this);
        return true;
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        newText = newText.toLowerCase();
        ArrayList<ClientModel> newList = new ArrayList<>();
        for (ClientModel clientModel : clientModelsList){
            String name = clientModel.getClient_name().toLowerCase();
            if (name.contains(newText)){
                newList.add(clientModel);
            }
        }
        adapter.setFilter(newList);
        return true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: is called");
        db.RemoveData();
        db.close();
    }    
}
  
      
  1. 适配器类
  2.   
    public CRecyclerAdapter(ArrayList<ClientModel> clientModelsList, Context context){
        this.clientModelsList = clientModelsList;
        this.context = context;
        this.mFilteredList = clientModelsList;
    }

    @NonNull
    @Override
    public CRecyclerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
        return new CRecyclerAdapter.ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull CRecyclerAdapter.ViewHolder holder, int position) {
        holder.nameTv.setText(clientModelsList.get(position).getClient_name());
        holder.emailTv.setText(clientModelsList.get(position).getCp_email());
        holder.phoneTv.setText(clientModelsList.get(position).getCp_phone());
        holder.assignTv.setText(clientModelsList.get(position).getAssign_person_name());
    }

    @Override
    public int getItemCount() {
       return clientModelsList.size();
    }


    public class ViewHolder extends RecyclerView.ViewHolder{

        public AppCompatTextView nameTv;
        public AppCompatTextView emailTv;
        public AppCompatTextView phoneTv;
        public AppCompatTextView assignTv;

        public ViewHolder(View itemView) {
            super(itemView);
            nameTv = (AppCompatTextView)itemView.findViewById(R.id.nameTv);
            emailTv = (AppCompatTextView)itemView.findViewById(R.id.emailTv);
            phoneTv = (AppCompatTextView)itemView.findViewById(R.id.phoneTv);
            assignTv = (AppCompatTextView)itemView.findViewById(R.id.assignTv);
        }
    }

    public void setFilter(ArrayList<ClientModel> newList) {
        clientModelsList = new ArrayList<>();
        clientModelsList.addAll(newList);
        notifyDataSetChanged();
    }
}
  
      
  1. 这是DatabaseHelper类方法,用于从数据库中获取列出的数据。
  2.   
// ALL LIST FROM CLIENT TABLE
public List<ClientModel> getListedData(){

    String[] COLUMNS = {COLUMN_CLIENT_ID, COLUMN_CLIENT_NAME, COLUMN_CP_PHONE, COLUMN_CP_EMAIL, COLUMN_ASSIGN_PERSON};
    // sorting orders
    String sortOrder = COLUMN_CLIENT_NAME + " ASC";
    List<ClientModel> clientModelList = new ArrayList<ClientModel>();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(CLIENT_TABLE, COLUMNS,
            null, // column to return
            null, // columns for the WHERE Clause
            null, // group the rows
            null, // filter by row groups
            sortOrder); // the sort order

    if (cursor.moveToFirst()){
        do {
            ClientModel clientModel = new ClientModel();
            clientModel.setClient_id(Integer.parseInt(cursor.getString(cursor.getColumnIndex(COLUMN_CLIENT_ID))));
            clientModel.setClient_name(cursor.getString(cursor.getColumnIndex(COLUMN_CLIENT_NAME)));
            clientModel.setCp_email(cursor.getString(cursor.getColumnIndex(COLUMN_CP_EMAIL)));
            clientModel.setCp_phone(cursor.getString(cursor.getColumnIndex(COLUMN_CP_PHONE)));
            clientModel.setAssign_person_name(cursor.getString(cursor.getColumnIndex(COLUMN_ASSIGN_PERSON)));
            // adding clients to the list
            clientModelList.add(clientModel);
        } while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return clientModelList;
}

接口: enter image description here

0 个答案:

没有答案