【问题标题】:SearchView in Custom List Adapter Using JSON data [closed]使用 JSON 数据的自定义列表适配器中的 SearchView [关闭]
【发布时间】:2015-05-08 05:06:37
【问题描述】:

我想在由自定义 listadatper 制作的列表视图中实现搜索,我正在解析来自 JSON 的数据并将其保存到内部存储中,这是我的代码

 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();
        }
    }


}

编辑

【问题讨论】:

  • 所以...你的问题是什么@Yasir
  • 使用你的适配器的Filter,最简单的是使用FilterQueryProvider:只需实现runQuery方法并使用FilterQueryProvider设置你的适配器
  • 当然FilterQueryProvider需要使用CursorAdapter

标签: java android json parsing search


【解决方案1】:

要实现搜索,您需要使用editText 的textchanged 事件,它将搜索词作为输入。您可以阅读以下链接以了解动作侦听器:-

1)How to Apply the Textchange event on EditText

2)Counting Chars in EditText Changed Listener

获得搜索关键字后,通过列表将对象与关键字匹配。然后将列表项存储在与搜索关键字匹配的单独列表中。搜索完成后,使用新创建的列表设置新适配器。

祝你好运!

【讨论】:

  • 点击事件?什么点击事件?
  • 更新了答案,是editText的textChanged事件
猜你喜欢
  • 2014-12-06
  • 2020-12-16
  • 1970-01-01
  • 2014-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多