SearchView.OnQueryTextListener

时间:2017-06-03 09:40:47

标签: java android

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

FragGridCampos.java

class CronTest {

function __construct() {
    add_action( 'init', array ( $this, 'g_order_sync' ) );
    add_action( 'ga_order_syn', array ( $this, 'sync_order' ) );
}

// init

public function g_order_sync() {
    try{
        if ( ! wp_next_scheduled( 'ga_order_syn' ) ) {
            wp_schedule_event(  time() + 10, null, 'ga_order_syn' );
        }
    }
    catch(Exception $ex)
    {
        echo "<p>The error: " . $e->getMessage() . "</p>"; //display error
    }
}

// cron job

public function sync_order() {
    $content = time() . ": some text here";
    $this->_write_content ($content);
}

// write content

private function _write_content( $content = '') {
    $path =  $_SERVER[ 'DOCUMENT_ROOT' ] . "/myText.txt";
    if( is_writable($path)) {
        $original = file_get_contents($path);
        $original .= PHP_EOL . $content;
        $fp = fopen( $path, "wb" );
        fwrite( $fp, $original );
        fclose( $fp );
    } else {
        // log error here
    }
}
}

// must initialize the cron class
$cron_test = new CronTest();

Campos_Adapter.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;

    }
}

排队* 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(); } } setFilter为红色。

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

2 个答案:

答案 0 :(得分:0)

1。而不是将Adapter声明为:

  private RecyclerView.Adapter adapter;

使用:

  private Campos_Adapter adapter;

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

更新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:尝试调用接口方法   &#39; java.util.Iterator java.util.List.iterator()&#39;在null对象上   参考   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;
    }

答案 1 :(得分:0)

解决方案:

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 Campos_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<Estadisticas>();

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

        getData();

        /*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);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        final List<Estadisticas> filteredModelList = filter(listJornadas, 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 poblacion = model.getPoblacion().toLowerCase();
            final String equipo = model.getEquipo().toLowerCase();

            if (poblacion.contains(query)) {
                filteredModelList.add(model);
            }
            else if (equipo.contains(query)) {
                filteredModelList.add(model);
            }
        }
        return filteredModelList;

    }
}

Campos_Adapter.java

public class Campos_Adapter extends RecyclerView.Adapter<Campos_Adapter.ViewHolder> {

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

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