Android parsed json data and add a search functionality

前端 未结 1 1465
感动是毒
感动是毒 2021-01-16 19:46

Sorry for my bad english.I am new to android and i parsed json data into listview,now i want to put on him a search functionality,but i have a problem,when i entered a words

相关标签:
1条回答
  • 2021-01-16 20:08

    The problem is that when you filter the data you add again to mAdapterDTOs list the results you need to clear the list before adding the results. To avoid losing your data you have to keep them in a separate list and when user times nothing show them.

    Step 1: Use a field for keeping a backup of your data (just as mAdapterDTOs):

        ArrayList<AdapterDTOArtist> mAdapterDTOs = null;
        ArrayList<AdapterDTOArtist> mAdapterDTOsBackup= null;
    

    Step 2: initialize that field:

            mAdapterDTOs = new ArrayList<AdapterDTOArtist>();
            mAdapterDTOsBackup = new ArrayList<AdapterDTOArtist>();
    

    Step 3: Fill in all your data to the backup set just after parsing:

     /**
     * getting Albums JSON
     * */
    protected String doInBackground(String... args) {
    
            // HERE all your code as it is!!!
    
        // Just before return add a set keeping the backup of your data...
        // initialize the set just as mAdapterDTOs
        mAdapterDTOsBackup.addAll(mAdapterDTOs);
        return null;
    }
    

    Step 4: When searching filter data from backup set and then add them on the mAdapterDTOs do not forget to clear it before.

    et_artists_searchWord.addTextChangedListener(new TextWatcher() {
    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
        //  ((Filterable) Artists.this.mAdapterDTOs).getFilter().filter(s);
            List<AdapterDTOArtist> list = filter(s.toString(),mAdapterDTOsBackup, true);
            mAdapterDTOs.clear(); // <--- clear the list before add
            mAdapterDTOs.addAll(list); // <--- here is the double add if you do not clear before
            mLazyAdatper.setDataSet(mAdapterDTOs);// update the adapter data (edit 2)
        }
    

    Edit: split answer in steps in order to be more clear the process also added at least one of your line to show where to add each code snippet.

    0 讨论(0)
提交回复
热议问题