java - SearchView.OnQueryTextListener

标签 java android

我正在尝试使用 SearchView 搜索项目,但我不知道为什么我找不到可能的方法,你能帮助我吗?

FragGridCampos.java

public class FragGridCampos extends Fragment implements SearchView.OnQueryTextListener{

    //Creating a List of jornadas
    private List<Estadisticas> listJornadas;

    //Creating Views
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerView.Adapter adapter;

    private List<Estadisticas> mCountryModel;


    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate( R.layout.campos_list_todos, null);

        setHasOptionsMenu(true);

        recyclerView = (RecyclerView) view.findViewById( R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 1);
        recyclerView.setLayoutManager(layoutManager);

        TextView miTexto = (TextView)view.findViewById( R.id.mi_texto);
        miTexto.setText("CAMPOS");
        //miTexto.setTextColor(color.RED);

        listJornadas = new ArrayList<>();

        getData();

        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new DecoracionLineaDivisoria(getActivity()));

        /*ImageButton fabButton = (ImageButton) view.findViewById(R.id.fab);
        fabButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //startActivity(new Intent(getActivity(), MainActivity2.class));
                Toast.makeText(getActivity(),"Proximamente",Toast.LENGTH_SHORT).show();

            }
        });*/

        return view;
    }


    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_buscar, menu);
        final MenuItem searchItem = menu.findItem(R.id.action_search);
        final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
        searchView.setOnQueryTextListener(this);
    }


    //This method will get data from the web api
    private void getData(){
        //Showing a progress dialog
        final ProgressDialog loading = ProgressDialog.show(getActivity(),"Cargando datos", "Por favor espere...",false,false);

        //Creating a json array request
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigAmaters.CAMPOS,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        //Dismissing progress dialog
                        loading.dismiss();

                        //calling method to parse json array
                        parseData(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

        //Creating request queue
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());

        //Adding request to the queue
        requestQueue.add(jsonArrayRequest);
    }

    //This method will parse json data
    private void parseData(JSONArray array){

        for(int i = 0; i<array.length(); i++) {
            Estadisticas campo = new Estadisticas();
            JSONObject json = null;
            try {
                json = array.getJSONObject(i);

                campo.setNombre_campo(json.getString("nombre_campo"));
                campo.setPoblacion(json.getString("poblacion"));
                campo.setEquipo(json.getString("equipo"));
                campo.setTelefono(json.getString("telefono"));
                campo.setGeo(json.getString("geo"));
                campo.setUrl(json.getString("url"));
                campo.setEmail(json.getString("email"));

                campo.setEscudo(json.getString("escudo"));

            } catch (JSONException e) {
                e.printStackTrace();
            }
            listJornadas.add(campo);
        }

        //Finally initializing our adapter
        adapter = new Campos_Adapter(listJornadas, getActivity());

        //Adding adapter to recyclerview
        recyclerView.setAdapter(adapter);
    }

    private LayoutInflater getMenuInflater() {
        return null;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        final List<Estadisticas> filteredModelList = filter(mCountryModel, newText);

        adapter.setFilter(filteredModelList);
        return true;
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    private List<Estadisticas> filter(List<Estadisticas> models, String query) {
        query = query.toLowerCase();final List<Estadisticas> filteredModelList = new ArrayList<>();
        for (Estadisticas model : models) {
            final String text = model.getPoblacion().toLowerCase();
            if (text.contains(query)) {
                filteredModelList.add(model);
            }
        }
        return filteredModelList;

    }
}

Campos_Adapter.java

 private ImageLoader imageLoader;
    private Context context;


    List<Estadisticas> estadisticas;

    public Campos_Adapter(List<Estadisticas> estadisticas, Context context) {
        super();
        this.estadisticas = estadisticas;
        this.context = context;
    }


    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from( parent.getContext() ).inflate( R.layout.campos_row, parent, false );
        ViewHolder viewHolder = new ViewHolder( v );
        return viewHolder;
    }

    public void onBindViewHolder(ViewHolder holder, final int position) {
        holder.root.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //Toast.makeText(context, "this is my Toast message!!! =)",
                //Toast.LENGTH_LONG).show();

                //Toast.makeText(context, estadisticas.get(position).getNombrePlato(), Toast.LENGTH_SHORT).show();

                Intent intent= new Intent(context, DetailCampos.class);

                intent.putExtra("Poblacion", estadisticas.get(position).getPoblacion());
                intent.putExtra("Nombre_campo", estadisticas.get(position).getNombre_campo());
                intent.putExtra("Nombre", estadisticas.get(position).getEquipo());
                intent.putExtra("Telefono", estadisticas.get(position).getTelefono());
                intent.putExtra("Geo", estadisticas.get(position).getGeo());
                intent.putExtra("Email", estadisticas.get(position).getEmail());
                intent.putExtra("Url", estadisticas.get(position).getUrl());
                intent.putExtra("Imagen", estadisticas.get(position).getEscudo());

                context.startActivity(intent);


                Estadisticas estadisticas1 = estadisticas.get(getAdapterPosition());
            }

            private int getAdapterPosition() {
                return 0;
            }
        } );
        Estadisticas campos = estadisticas.get( position );
        imageLoader = DecoracionLineaDivisoria.CustomVolleyRequest.getInstance(context ).getImageLoader();
        imageLoader.get(campos.getEscudo(), ImageLoader.getImageListener(holder.escudo_local, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert ) );

        holder.textViewEquipo_Local.setText( campos.getEquipo() );
        holder.textViewPoblacion.setText( campos.getPoblacion() );

        //holder.escudo_local.setImageUrl( campos.getImagenPlato(), imageLoader );
    }    

    @Override
    public int getItemCount() {
        return estadisticas.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView escudo_local;
        public TextView textViewEquipo_Local;
        public TextView textViewPoblacion;
        public View root;

        public ViewHolder(View itemView) {
            super( itemView );
            root = itemView;
            escudo_local = (ImageView) itemView.findViewById( R.id.tv_esc_local );
            textViewEquipo_Local = (TextView) itemView.findViewById( R.id.tv_ek_local );
            textViewPoblacion = (TextView) itemView.findViewById( R.id.tv_poblacion );
        }
    }

    public void setFilter(List<Estadisticas> countryModels) {
        estadisticas = new ArrayList<>();
        estadisticas.addAll(countryModels);
        notifyDataSetChanged();
    }
}

行内 *adapter.setFilter(filteredModelList); setFilter 为红色。

我的错误是 *Error:(182, 16) 错误:找不到符号方法 setFilter(List)

最佳答案

1.不要将适配器声明为:

  private RecyclerView.Adapter adapter;

用途:

  private Campos_Adapter adapter;

2. 此外,从 onCreateView() 初始化适配器,并从 parseData() 方法使用 adapter.notifyDataSetChanged()

更新onCreateView()parseData()如下:

 //Creating a List of jornadas
 private List<Estadisticas> listJornadas;

 //Creating Views
 private RecyclerView recyclerView;
 private RecyclerView.LayoutManager layoutManager;
 private Campos_Adapter adapter;

 private List<Estadisticas> mCountryModel;

 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    ...........
    ...................

    listJornadas = new ArrayList<Estadisticas>();

    adapter = new Campos_Adapter(listJornadas, getActivity());
    recyclerView.setAdapter(adapter);
    recyclerView.addItemDecoration(new DecoracionLineaDivisoria(getActivity()));

    getData();

    .........
    .............

    return view;
}

//This method will parse json data
private void parseData(JSONArray array){

    for(int i = 0; i<array.length(); i++) {
        Estadisticas campo = new Estadisticas();
        JSONObject json = null;
        try {
            json = array.getJSONObject(i);

            campo.setNombre_campo(json.getString("nombre_campo"));
            campo.setPoblacion(json.getString("poblacion"));
            campo.setEquipo(json.getString("equipo"));
            campo.setTelefono(json.getString("telefono"));
            campo.setGeo(json.getString("geo"));
            campo.setUrl(json.getString("url"));
            campo.setEmail(json.getString("email"));

            campo.setEscudo(json.getString("escudo"));

        } catch (JSONException e) {
            e.printStackTrace();
        }
        listJornadas.add(campo);

        adapter.notifyDataSetChanged();
    }
}

更新:

java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference at com.ramon.campos.Campos.FragGridCampos.filter(FragGridCampos‌​.java:185)

您的mCountryModel为空。你还没有初始化它。在 onQueryTextChange() 中尝试以下代码:

    @Override
    public boolean onQueryTextChange(String newText) {

        mCountryModel.addAll(listJornadas);

        final List<Estadisticas> filteredModelList = filter(mCountryModel, newText);

        adapter.setFilter(filteredModelList);
        return true;
    }

关于java - SearchView.OnQueryTextListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44342549/

相关文章:

java - 如何在Struts2中使用JSF数据表?

java - 构建基于 Web 的 SQL 客户端

android - Phonegap 无法部署到设备

java - 导入Java项目,找不到src

java - 加载 JNI Dll

java - 如何最有效地在 java 中对字符串中的数字(可以是超大的)进行排序

java - Blowfish 加密问题

java - 尝试通过 Google plus 实现登录的 Android 应用程序显示奇怪的系统错误

Android nestedScrollView - 如何使其水平?

java - 连接错误 : "org.jsoup.UnsupportedMimeTypeException: Unhandled content type"