java - SearchView in Custom List Adapter Using JSON data -


i want implement search in listview made custom listadatper, parsing data json , saving internal storage, here code

 package life.quran.com.quranlife;    public class mainactivity extends actionbaractivity {       list<surah> surahlist;     listview lv;     edittext searchtxt;      arraylist<string> surahnames;       @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_main);          actionbar ab = getsupportactionbar();          ab.hide();         searchtxt = (edittext) findviewbyid(r.id.txtsearch);          surahlist = new arraylist<>();         lv = (listview) findviewbyid(r.id.listview);          file f = getfilesdir();a         string filepath = f.getabsolutepath();         file _file = new file(filepath + "/surah.json");           if (isonline()) {              surahtask task = new surahtask();             task.execute("http://quran.life/surah.php");           } else {              string offline_data = readfromfile();             surahlist = surahjsonparser.parsedata(offline_data);             displaysurah();          }       }       @override     public boolean oncreateoptionsmenu(menu menu) {         // inflate menu; adds items action bar if present.         getmenuinflater().inflate(r.menu.menu_main, menu);         return true;     }       protected void displaysurah() {          final surahadapter adapter = new surahadapter(mainactivity.this,r.layout.item_template,surahlist);         lv.setadapter(adapter);           lv.setonitemclicklistener(new adapterview.onitemclicklistener() {             @override             public void onitemclick(adapterview<?> parent, view view, int position, long id) {                 surah surah = adapter.getitem(position);                 string surahno = surah.getsurah_no().tostring();                 string suranname = surah.getsurah_name().tostring();                   intent intent = new intent(mainactivity.this, surahdetailsactivity.class);                 intent.putextra("_sno", surahno);                 intent.putextra("_sname", suranname);                 startactivity(intent);             }         });          searchtxt.addtextchangedlistener(new textwatcher() {             @override             public void beforetextchanged(charsequence s, int start, int count, int after) {               }              @override             public void ontextchanged(charsequence s, int start, int before, int count) {               /*   surah surahitems = new surah();                 list<surah> newlist = new arraylist<surah>();                 arraylist<string> temp = new arraylist<string>();                 int textlength = searchtxt.gettext().length();                 newlist.clear();                 for(int = 0; < surahnames.size(); i++) {                     if(textlength <= surahnames.get(i).length()) {                         if(searchtxt.gettext().tostring().equalsignorecase((string)surahnames.get(i).subsequence(0,textlength))) {                             newlist.add(surahnames.get(i));                         }                      }                  }                 lv.setadapter(new surahadapter(mainactivity.this,r.layout.item_template,surahlist)); */             }              @override             public void aftertextchanged(editable s) {              }         });      }      private boolean isonline() {         connectivitymanager cm = (connectivitymanager) getsystemservice(context.connectivity_service);         networkinfo netinfo = cm.getactivenetworkinfo();         if (netinfo != null && netinfo.isconnectedorconnecting()) {             return true;         } else {             return false;         }     }      private void writetofile(string data) {         try {             outputstreamwriter outputstreamwriter = new outputstreamwriter(openfileoutput("surah.json", context.mode_private));             outputstreamwriter.write(data);             outputstreamwriter.close();          } catch (ioexception e) {             log.e("exception", "file write failed: " + e.tostring());         }     }      private string readfromfile() {          string ret = "";          try {             inputstream inputstream = openfileinput("surah.json");              if (inputstream != null) {                 inputstreamreader inputstreamreader = new inputstreamreader(inputstream);                 bufferedreader bufferedreader = new bufferedreader(inputstreamreader);                 string receivestring = "";                 stringbuilder stringbuilder = new stringbuilder();                  while ((receivestring = bufferedreader.readline()) != null) {                     stringbuilder.append(receivestring);                 }                  inputstream.close();                 ret = stringbuilder.tostring();             }         } catch (filenotfoundexception e) {             log.e("login activity", "file not found: " + e.tostring());         } catch (ioexception e) {             log.e("login activity", "can not read file: " + e.tostring());         }          return ret;     }      @override     public boolean onoptionsitemselected(menuitem item) {         // handle action bar item clicks here. action bar         // automatically handle clicks on home/up button, long         // specify parent activity in androidmanifest.xml.         int id = item.getitemid();          //noinspection simplifiableifstatement         if (id == r.id.action_settings) {             return true;         }          return super.onoptionsitemselected(item);     }       private class surahtask extends asynctask<string, string, string> {          progressdialog pd;          @override         protected void onpreexecute() {               pd = new progressdialog(mainactivity.this);             pd.setprogressstyle(progressdialog.style_spinner);              pd.settitle("please wait...");             pd.setmessage("preparing list of surah..");             pd.setindeterminate(false);             pd.setcancelable(false);             pd.show();         }          @override         protected string doinbackground(string... params) {              surahnames = new arraylist<>();             string content = httpmanager.getdata(params[0]);             for(surah surah : surahlist) {                 surahnames.add("surah " +surah.getsurah_name());             }             writetofile(content);             return content ;          }          @override         protected void onpostexecute(string s) {              surahlist = surahjsonparser.parsedata(s);             displaysurah();             pd.dismiss();         }     }   } 

edited

to implement search, need use textchanged event of edittext take search word input. can read following links learn action listeners:-

1)how apply textchange event on edittext

2)counting chars in edittext changed listener

after getting search keyword go through list , match objects keywords. store list item in separate list matches search keyword. after search finished set new adapter using newly created list.

best of luck!


Comments