Search functionality in Android Custom ListView from database using CursorLoader and CursorAdapter

459 views Asked by At

I have CursorAdapter to show data from database usin CursorLoader. Now, I want add search functionality to custom listview. So, I tried with this. but, this is not working.

public class FindPeopleFragment extends BaseFragment implements LoaderCallbacks<Cursor> {

    public FindPeopleFragment() {
    }

    private TextView advancedSearchOption;
    private TextView saerchButton;
    private EndlessListView listUsers;
    private EditText searchWord;
    private EditText searchFirstName;
    private EditText searchLastName;
    private EditText searchEmail;
    private EditText searchCountry;
    private EditText searchState;
    private int offset = 0;
    private final int limit = 30;
    private boolean mHaveMoreDataToLoad = true;
    private VROAccountManager manager;
    private ArrayList<VROUser> postsList = new ArrayList<>();
    private View advanced;
    private Cursor FriendsCursor;
    private Cursor FriendsCursorTemp;
    // Cursor  c;
    private TextView description;
    long friend_name;
    FriendsListCursorAdapter FRIEND_ADAPTER;
    DatabaseHelper dh;
    FriendinfoService friendinfoService;
String searchValue;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        title = "My Friends";

    }

    private View rootView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        friendinfoService = new FriendinfoService();
        if (rootView != null) {

            ((ViewGroup) rootView.getParent()).removeView(rootView);
            return rootView;
        }

        rootView = inflater.inflate(R.layout.fragment_find_people, null);
        getLoaderManager().initLoader(1, null, this);

        saerchButton = (TextView) rootView.findViewById(R.id.button_search);
        listUsers = (EndlessListView) rootView.findViewById(R.id.user_list);
        searchWord = (EditText) rootView
                .findViewById(R.id.editText_search_word);
        searchFirstName = (EditText) rootView
                .findViewById(R.id.editText_search_first_name);
        searchLastName = (EditText) rootView
                .findViewById(R.id.editText_search_last_name);
        searchEmail = (EditText) rootView
                .findViewById(R.id.editText_search_email);
        searchCountry = (EditText) rootView
                .findViewById(R.id.editText_search_country);
        searchState = (EditText) rootView
                .findViewById(R.id.editText_search_state);
        advancedSearchOption = (TextView) rootView
                .findViewById(R.id.advancedSearch);
        advancedSearchOption.setVisibility(View.GONE);
        manager = new VROAccountManager(getActivity());
        advanced = rootView.findViewById(R.id.layout_advanced_search);
        description = (TextView) rootView.findViewById(R.id.description);
        description
                .setText("You are friends with the following users. To find new friends or to view friends request sent or received use the menu on right");

searchOption.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence cs, int start, int before, int count) {

                AbstractActivity.this.cursorAdapter.getFilter().filter(cs);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }
        });



        listUsers.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Cursor mycursor = (Cursor) listUsers.getItemAtPosition(position);
                VROUser user = VROUser.parse(mycursor);
                Intent intent = new Intent(getActivity(), ProfileViewActivity.class);
                intent.putExtra("userId", user.getUserID());
                getActivity().startActivity(intent);
                //Toast.makeText(getActivity(), " " + FriendsCursor.getColumnIndex("user_profile_pic"), Toast.LENGTH_SHORT).show();

            }
        });
        return rootView;
    }


    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {

        CursorLoader cursorLoader=null;
 if(id==1) {
      cursorLoader = new CursorLoader(getActivity(),
             FriendinfoTable.CONTENT_URI, null, null, null, null);
 }


if (id==2) {




    cursorLoader = new CursorLoader(getActivity(),
            FriendinfoTable.CONTENT_URI, null,
            FriendinfoTable.Cols.FIRST_NAME+" like '%"+searchValue+"%' or "+FriendinfoTable.Cols.LAST_NAME+" like '%"+searchValue+"%'",
            null, null);


                     }

        return cursorLoader;
    }


    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {


      System.out.println("Value returningnnnnnnnnnnnnnnnnnnnnnnnnnnn   " + data.getCount());

            FriendsCursor = data;

            if (FRIEND_ADAPTER == null) {
                FRIEND_ADAPTER = new FriendsListCursorAdapter(getActivity(),
                        FriendsCursor, true);
                listUsers.setAdapter(FRIEND_ADAPTER);
                FRIEND_ADAPTER = null;

            } else {

                FRIEND_ADAPTER.swapCursor(FriendsCursor);



            }


  }





    @Override
    public void onLoaderReset(Loader<Cursor> loader) {



    }
}


and adapter class code



    public class FriendsListCursorAdapter extends CursorAdapter  {
        private Cursor cursor;
        final VROPreferenceManager preferenceManager = new VROPreferenceManager();
        Context con;
        public FriendsListCursorAdapter(Context context, Cursor c, boolean b) {
              super(context,c,true);
            cursor = c;
            con=context;
        }

        public void addItems(Cursor newItems) {
            if (0 == newItems.getCount()) {
                return;
            }


            notifyDataSetChanged();
        }

        public int getCount() {
            // TODO Auto-generated method stub
            return cursor.getCount();
        }






        @Override
        public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
            LayoutInflater inflater = LayoutInflater.from(context);
            View view = inflater.inflate(R.layout.vro_contact_view, null);
            bindView(view, context, cursor);
            return view;
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {

            TextView txtID = (TextView) view.findViewById(R.id.text_fname_lname);
            txtID.setText(cursor.getString(cursor.getColumnIndex("first_name")));

            TextView txtCode = (TextView) view.findViewById(R.id.text_email);
            txtCode.setText(cursor.getString(cursor.getColumnIndex("email")));
            ImageView profilePic = (ImageView) view.findViewById(R.id.user_image);

             VROUser pic = VROUser.parse(cursor);

            ImageLoader.getInstance().displayImage(
                    preferenceManager.getResourceSertver()
                            + pic.getProfilePICURL(), profilePic,
                    Consts.UIL_USER_AVATAR_DISPLAY_OPTIONS);

        }



    }

I will be glad if you guys help to find out what's the problem in my code or how can i add search functionality to a custom listview.

1

There are 1 answers

0
SAM On

Implement the interface Filter in your adapter and override the getfilter() method.

below is the short example.

  @Override
    public Filter getFilter() {
        Filter filter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
             //your logic
                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
               //final updated arraylist
            }
        };
        return filter;

    }