-2

I want to implement search in my listview which is made by custom listadatper, I am parsing data from JSON and saving it into internal storage, here is my 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 the menu; this adds items to the action bar if it is 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 i = 0; i < 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. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a 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

Viraj Nalawade
  • 3,137
  • 3
  • 28
  • 44

1 Answers1

1

To implement search, you need to use the textchanged event of the editText which will take the search word as an input. You can read the following links to learn about the action listeners:-

1)How to Apply the Textchange event on EditText

2)Counting Chars in EditText Changed Listener

After getting the search keyword go through the list and match the objects with the keywords. Then store the list item in a separate list which matches with the search keyword. After search is finished set the new adapter by using the newly created list.

Best of Luck!

Community
  • 1
  • 1
Pranav Agrawal
  • 466
  • 6
  • 17