如何在RecyclerView中添加搜索过滤器以通过解析的JSON数据进行过滤?已编辑 [英] How to add a search filter in RecyclerView to filter through parsed JSON data? edited

查看:83
本文介绍了如何在RecyclerView中添加搜索过滤器以通过解析的JSON数据进行过滤?已编辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Android应用程序,其中显示受冠状病毒感染的国家/地区列表,确诊病例总数和总死亡人数.我正在使用JSON API来获取数据并使用RecyclerView进行显示.该应用程序运行良好,并且我得到了所有国家/地区的清单以及各自的案件数.我想添加一个搜索选项,以便用户可以过滤列表并找到特定的国家.我怎么做?我是编程新手,如果有人可以帮忙,那真是太好了. 这是代码段

I am developing an android app which shows a list of countries affected by Coronavirus , the total number of confirmed cases and total Deaths. I am using a JSON API to get the data and displaying it using a RecyclerView . The app works fine , and i get a list of all the countries with their respective case counts. I want to add a search option so that the users can filter the list and find a specific country. How do i do that? I am new to programming , if someone could help with this that would be awesome. Here is the code snippet

MainActivity.java

MainActivity.java

    private RecyclerView mRecyclerView;
    private Corona_Stats_Adapter mCorona_Stats_Adapter;
    private TextView mErrorDisplay;
    private ProgressBar mProgressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.corona_stats);

        mRecyclerView = (RecyclerView)findViewById(R.id.Corona_stats_recycler);
        mErrorDisplay = (TextView) findViewById(R.id.tv_error_message_display);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setHasFixedSize(true);
        mCorona_Stats_Adapter = new Corona_Stats_Adapter();
        mRecyclerView.setAdapter(mCorona_Stats_Adapter);
        mProgressBar = (ProgressBar)findViewById(R.id.pb_loading_indicator) ;



        loadCoronaData();

    }

        private void loadCoronaData(){
            showCoronaDataView();
            //String Country = String.valueOf(mSearchQuery.getText());
            new Fetch_data().execute();

        }
        private void showCoronaDataView(){
        mErrorDisplay.setVisibility(View.INVISIBLE);
        mRecyclerView.setVisibility(View.VISIBLE);
        }

        private void showErrorMessage(){
        mRecyclerView.setVisibility(View.INVISIBLE);
        mErrorDisplay.setVisibility(View.VISIBLE);
        }

    public class Fetch_data extends AsyncTask<Void,Void,String[]> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressBar.setVisibility(View.VISIBLE);
        }



        @Override
        protected String[] doInBackground(Void... voids) {

            URL covidRequestURL = NetworkUtils.buildUrl();


            try {
                String JSONCovidResponse = NetworkUtils.getResponseFromHttpUrl(covidRequestURL);
                String[] simpleJsonCovidData = CovidJSON_Utils.getSimpleStringFromJson(MainActivity.this, JSONCovidResponse);
                return simpleJsonCovidData;
            } catch (IOException | JSONException e) {
                e.printStackTrace();
                return null;
            }



        }

        @Override
        protected void onPostExecute(String[] coronaData) {
            mProgressBar.setVisibility(View.INVISIBLE);
            if(coronaData !=null){
                showCoronaDataView();
                mCorona_Stats_Adapter.setCoronaData(coronaData);
            } else{
                showErrorMessage();
            }

        }
    }
}

RecyclerView适配器类Corona_stats_Adapter.java

RecyclerView Adapter class Corona_stats_Adapter.java

public class Corona_Stats_Adapter extends RecyclerView.Adapter<Corona_Stats_Adapter.Corona_Stats_AdapterViewHolder>
  {

    private Context context;
   // private List<Country> countryList;
   // private List<Country> countryListFiltered;
    private String[] mCoronaData;
    public Corona_Stats_Adapter(){
    }

    @NonNull
    @Override
    public Corona_Stats_AdapterViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        Context context = viewGroup.getContext();
        int LayoutIdForListItem =R.layout.corona_stats_list_item;
        LayoutInflater inflater =LayoutInflater.from(context);
        boolean ShouldAttachToParentImmediately = false;

        View view = inflater.inflate(LayoutIdForListItem,viewGroup,ShouldAttachToParentImmediately);
        return new Corona_Stats_AdapterViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull Corona_Stats_AdapterViewHolder corona_stats_adapterViewHolder, int position) {

        String coronaStats = mCoronaData[position];
        corona_stats_adapterViewHolder.mCoronaTextView.setText(coronaStats);
    }

    @Override
    public int getItemCount() {
        if(null == mCoronaData) return 0;
        return mCoronaData.length;
       // return countryListFiltered.size();
    }

    public class Corona_Stats_AdapterViewHolder extends RecyclerView.ViewHolder {

        public final TextView mCoronaTextView;

        public Corona_Stats_AdapterViewHolder(@NonNull View view) {
            super(view);
            mCoronaTextView = (TextView) view.findViewById(R.id.tv_corona_data);
        }
    }

        public void setCoronaData(String[] coronaData){
            mCoronaData = coronaData;
            notifyDataSetChanged();
        }

}

在CovidJSON_Utils.java中解析JSON数据

Parsing the JSON data in CovidJSON_Utils.java

public final class CovidJSON_Utils {

    public static String[] getSimpleStringFromJson(Context context, String codivJsonString)
    throws JSONException {
    final String COV_COUNTRY = "Countries";
    final String COV_CONFIRMED = "confirmed";
    final String COV_DEATHS = "deaths";
    final String COV_MESSAGE_CODE = "code";

        String[] parsedCovidData = null;
        JSONObject covidJsonObject = new JSONObject(codivJsonString);

        if (covidJsonObject.has(COV_MESSAGE_CODE)) {
                int errorCode = covidJsonObject.getInt(COV_MESSAGE_CODE);
                switch (errorCode) {
                    case HttpURLConnection.HTTP_OK:
                        break;
                    case HttpURLConnection.HTTP_NOT_FOUND:
                        return null;
                    default:
                        return null;
                }

            }

            JSONArray countryCovidArray = covidJsonObject.getJSONArray(COV_COUNTRY);


            parsedCovidData = new String[countryCovidArray.length()];
            for (int i = 0; i < countryCovidArray.length(); i++) {

                JSONObject countryJSONObject = countryCovidArray.getJSONObject(i);
                String Country = countryJSONObject.getString("Country");
                String Confirmed = String.valueOf(countryJSONObject.getInt("TotalConfirmed"));
                String Deaths = String.valueOf(countryJSONObject.getInt("TotalDeaths"));

                parsedCovidData[i] = Country + "- Cases " + Confirmed + "- Deaths " + Deaths;

            }
            return parsedCovidData;


        }


    }

推荐答案

从服务器获取数据后,必须设置arraylist以更新适配器中的国家/地区数据.

You have to set arraylist to update country data in adapter after getting data from the server.

Public void setCoronaData (Arraylist coronaData) {
  countryList = coronaData;
  notifyDataSetChanged ();
}

这篇关于如何在RecyclerView中添加搜索过滤器以通过解析的JSON数据进行过滤?已编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆