how to implement search functionality in Gridview

2019-08-11 15:25发布

问题:

In my application I have search tab which display images with their name in grid view and now I want to implement search functionality. I have been searching in google for past two days but I didn't get any solution. Any idea or tutorial 0r how can I achieve this?

Anyone help me with this.

Thanks in advance.

mainactivity

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;

import com.example.diceapp.R;

public class SearchActivity extends Activity 
{


     JSONArray results;

     JSONObject jobj;

     SearchCustomAdapter adapter1;

     ImageButton ib;

     ArrayList<String> a1,a2,a3,a4;

     ArrayList<String> name=new ArrayList<String>();

     ArrayList<String> description=new ArrayList<String>();

     ArrayList<String> image=new ArrayList<String>();

     ArrayList<String> price=new ArrayList<String>();

     Button add;

     String pid;

     GridView gView;

     EditText src;

     int textlength = 0;

     ArrayList<String> p_name = new ArrayList<String>();
     ArrayList<String> p_image = new ArrayList<String>();


    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {

        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.search_activity);

        a1=new ArrayList<String>();

        a2=new ArrayList<String>();

        a3=new ArrayList<String>();

        a4=new ArrayList<String>();

        src=(EditText)findViewById(R.id.srcetxt);

        /*src.addTextChangedListener(new TextWatcher()
        {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                // When user changed the Text
                SearchActivity.this.adapter1.getFilter().filter(cs);  
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub                         
            }
        });*/

        new Searchtask().execute();

        gView = (GridView)findViewById(R.id.gridView1);

        gView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                    long arg3) {
                // TODO Auto-generated method stub
                System.out.println("outside on click"+position);

            }
        });

       ib=(ImageButton)findViewById(R.id.imageButton1);

    }

    private class Searchtask extends AsyncTask<String, String, JSONObject> 
    {
        private ProgressDialog pDialog;

        @Override
        protected void onPreExecute() 
        {
            super.onPreExecute();

            pDialog = new ProgressDialog(SearchActivity.this);

            pDialog.setMessage("Loading Data ...");

            pDialog.setIndeterminate(false);

            pDialog.setCancelable(true);

            pDialog.show();
        }

        @Override
        protected JSONObject doInBackground(String... args) 
        {
            JSONParser jParser = new JSONParser();

            JSONObject json = jParser.getJSONFromUrl("http:link.php");

            return json;

        }

        @Override
        protected void onPostExecute(JSONObject json)
        {

            System.out.println("---------------return name list json------------"+json);

            pDialog.dismiss();

            try 
            {
                jobj=json.getJSONObject("response");
                // Getting Array of Contacts
                results = jobj.getJSONArray("obejects");

                System.out.println("In product Activity after JSON");
                // looping through All Contacts
                for(int i = 0; i < results.length(); i++)
                {
                    JSONObject c = results.getJSONObject(i);

                    name.add(c.getString("name"));

                    image.add(c.getString("image"));

                     price.add(c.getString("price"));

                    description.add(c.getString("Description"));

                }
            } 
            catch (JSONException e) 
            {
                e.printStackTrace();
            }
            adapter1  = new SearchCustomAdapter(getApplicationContext(), R.layout.gridlistimg, name, image,description,price);

            gView.setAdapter(adapter1);

        }
    }

}

baseadapter class

package com.example.diceapp.search;
import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.sax.StartElementListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.example.diceapp.AAAMainActivity;
import com.example.diceapp.R;
import com.example.diceapp.category.ImageLoader;

public class SearchCustomAdapter extends BaseAdapter
{
    Context context;

    LayoutInflater inflater;

    ArrayList<String> aaaa1,bbbb1,cccc1;


    ArrayList<String> c_pname;

    ArrayList<String> c_pimage;

    ArrayList<String> c_pprice;

    ArrayList<String> c_pdescription;

    String[] data_text;
    String[] data_image;

    ImageLoader iloader;

    public SearchCustomAdapter(Context c, int productDescribe,ArrayList<String> pname, ArrayList<String> pimage,
            ArrayList<String> productdescription, ArrayList<String> pprice)
    {
        // TODO Auto-generated constructor stub



        this.context=c;

        this.c_pname=pname;

        this.c_pprice=pprice;

        this.c_pdescription=productdescription;

        this.c_pimage=pimage;

         inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

         iloader= new ImageLoader(context.getApplicationContext());


    }


    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return c_pname.size();
        //return data_text.length;
    }

@Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return null;

    }

    @Override
    public long getItemId(int pos) {
        // TODO Auto-generated method stub
        //return  c_pname.indexOf(getItem(pos));//arg0;
        return pos;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent)
    {
        // TODO Auto-generated method stub
        View row=convertView; 

        ViewHolder vh;

        if(row==null)
        {
            row=inflater.inflate(R.layout.custom_search_activity, parent, false);

            vh=new ViewHolder();

            vh.pname=(TextView)row.findViewById(R.id.product_name);

            vh.pprice=(TextView)row.findViewById(R.id.textView2);

            vh.image1=(ImageView) row.findViewById(R.id.imageView1);

            vh.btn=(Button)row.findViewById(R.id.p_custom_tv);


            /*row.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {

                     System.out.println("outside on click"+position);


                     ArrayList<String> sendingary=new ArrayList<String>();

                     sendingary.add(c_pname.get(position));

                     sendingary.add(c_pprice.get(position));

                     sendingary.add(c_pimage.get(position));

                     sendingary.add(c_pdescription.get(position));

                     Intent cp=new Intent(context.getApplicationContext(),product_details.class);

                     cp.putStringArrayListExtra("aryvalue", sendingary);

                     cp.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                     context.startActivity(cp);

                }
            });*/

            row.setTag(vh);
        }
        else 
        {
            vh = (ViewHolder) row.getTag();
            row=convertView;
        }

        vh.pname.setText(c_pname.get(position));
        vh.pprice.setText("KD "+c_pprice.get(position));        
        iloader.DisplayImage(c_pimage.get(position),  vh.image1);

        return row;
    }



    public static class ViewHolder
    {
         TextView pname,pprice;

         ImageView image1;

         Button btn;
    }

    public SearchCustomAdapter getFilter() {
        // TODO Auto-generated method stub
        return null;
    }
}

回答1:

Hi I just edit your code please replace and check it

SearchActivity.java

import java.util.ArrayList;
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;

public class SearchActivity extends Activity {

    JSONArray results;

    JSONObject jobj;

    SearchCustomAdapter adapter1;

    ImageButton ib;

    ArrayList<String> a1, a2, a3, a4;

    ArrayList<String> name = new ArrayList<String>();

    ArrayList<String> description = new ArrayList<String>();

    ArrayList<String> image = new ArrayList<String>();

    ArrayList<String> price = new ArrayList<String>();

    Button add;

    String pid;

    GridView gView;

    EditText src;

    int textlength = 0;

    ArrayList<String> p_name = new ArrayList<String>();
    ArrayList<String> p_image = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.search_activity);

        a1 = new ArrayList<String>();

        a2 = new ArrayList<String>();

        a3 = new ArrayList<String>();

        a4 = new ArrayList<String>();

        src = (EditText) findViewById(R.id.srcetxt);

        src.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                if (src.getText().toString().trim().length() > 0) {
                    applySearch(src.getText().toString().trim());
                } else {
                    adapter1.setC_pname(name);
                    adapter1.setC_pdescription(description);
                    adapter1.setC_pimage(image);
                    adapter1.setC_pprice(price);
                    adapter1.notifyDataSetChanged();
                }
            }
        });

        new Searchtask().execute();

        gView = (GridView) findViewById(R.id.gridView1);

        gView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                // TODO Auto-generated method stub
                System.out.println("outside on click" + position);

            }
        });

        ib = (ImageButton) findViewById(R.id.imageButton1);

    }

    private class Searchtask extends AsyncTask<String, String, JSONObject> {
        private ProgressDialog pDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = new ProgressDialog(SearchActivity.this);

            pDialog.setMessage("Loading Data ...");

            pDialog.setIndeterminate(false);

            pDialog.setCancelable(true);

            pDialog.show();
        }

        @Override
        protected JSONObject doInBackground(String... args) {
            JSONParser jParser = new JSONParser();

            JSONObject json = jParser.getJSONFromUrl("http:link.php");

            return json;

        }

        @Override
        protected void onPostExecute(JSONObject json) {

            System.out.println("---------------return name list json------------" + json);

            pDialog.dismiss();

            try {
                jobj = json.getJSONObject("response");
                // Getting Array of Contacts
                results = jobj.getJSONArray("obejects");

                System.out.println("In product Activity after JSON");
                // looping through All Contacts
                for (int i = 0; i < results.length(); i++) {
                    JSONObject c = results.getJSONObject(i);

                    name.add(c.getString("name"));

                    image.add(c.getString("image"));

                    price.add(c.getString("price"));

                    description.add(c.getString("Description"));

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            adapter1 = new SearchCustomAdapter(getApplicationContext(), R.layout.gridlistimg, name, image, description, price);

            gView.setAdapter(adapter1);

        }
    }

    private void applySearch(String searchStr) {
        ArrayList<String> searchname = new ArrayList<String>();
        ArrayList<String> searchdescription = new ArrayList<String>();
        ArrayList<String> searchimage = new ArrayList<String>();
        ArrayList<String> searchprice = new ArrayList<String>();

        for (int i = 0; i < name.size(); i++) {
            if (name.get(i).contains(searchStr)) {
                searchname.add(name.get(i));
                searchdescription.add(description.get(i));
                searchimage.add(image.get(i));
                searchprice.add(price.get(i));
            }
        }

        adapter1.setC_pname(searchname);
        adapter1.setC_pdescription(searchdescription);
        adapter1.setC_pimage(searchimage);
        adapter1.setC_pprice(searchprice);
        adapter1.notifyDataSetChanged();
    }

}

SearchCustomAdapter.java

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class SearchCustomAdapter extends BaseAdapter {
    Context context;

    LayoutInflater inflater;

    ArrayList<String> aaaa1, bbbb1, cccc1;

    ArrayList<String> c_pname;
    ArrayList<String> c_pprice;
    ArrayList<String> c_pdescription;
    ArrayList<String> c_pimage;

    public void setC_pname(ArrayList<String> c_pname) {
        this.c_pname = c_pname;
    }

    public void setC_pimage(ArrayList<String> c_pimage) {
        this.c_pimage = c_pimage;
    }

    public void setC_pprice(ArrayList<String> c_pprice) {
        this.c_pprice = c_pprice;
    }

    public void setC_pdescription(ArrayList<String> c_pdescription) {
        this.c_pdescription = c_pdescription;
    }

    String[] data_text;
    String[] data_image;

    ImageLoader iloader;

    public SearchCustomAdapter(Context c, int productDescribe, ArrayList<String> pname, ArrayList<String> pimage, ArrayList<String> productdescription, ArrayList<String> pprice) {
        // TODO Auto-generated constructor stub

        this.context = c;

        this.c_pname = pname;

        this.c_pprice = pprice;

        this.c_pdescription = productdescription;

        this.c_pimage = pimage;

        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        iloader = new ImageLoader(context.getApplicationContext());

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return c_pname.size();
        // return data_text.length;
    }

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return null;

    }

    @Override
    public long getItemId(int pos) {
        // TODO Auto-generated method stub
        // return c_pname.indexOf(getItem(pos));//arg0;
        return pos;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View row = convertView;

        ViewHolder vh;

        if (row == null) {
            row = inflater.inflate(R.layout.custom_search_activity, parent, false);

            vh = new ViewHolder();

            vh.pname = (TextView) row.findViewById(R.id.product_name);

            vh.pprice = (TextView) row.findViewById(R.id.textView2);

            vh.image1 = (ImageView) row.findViewById(R.id.imageView1);

            vh.btn = (Button) row.findViewById(R.id.p_custom_tv);

            /*
             * row.setOnClickListener(new OnClickListener() {
             * 
             * @Override public void onClick(View arg0) {
             * 
             * System.out.println("outside on click"+position);
             * 
             * 
             * ArrayList<String> sendingary=new ArrayList<String>();
             * 
             * sendingary.add(c_pname.get(position));
             * 
             * sendingary.add(c_pprice.get(position));
             * 
             * sendingary.add(c_pimage.get(position));
             * 
             * sendingary.add(c_pdescription.get(position));
             * 
             * Intent cp=new
             * Intent(context.getApplicationContext(),product_details.class);
             * 
             * cp.putStringArrayListExtra("aryvalue", sendingary);
             * 
             * cp.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
             * 
             * context.startActivity(cp);
             * 
             * } });
             */

            row.setTag(vh);
        } else {
            vh = (ViewHolder) row.getTag();
            row = convertView;
        }

        vh.pname.setText(c_pname.get(position));
        vh.pprice.setText("KD " + c_pprice.get(position));
        iloader.DisplayImage(c_pimage.get(position), vh.image1);

        return row;
    }

    public static class ViewHolder {
        TextView pname, pprice;

        ImageView image1;

        Button btn;
    }

}


回答2:

If you use ArrayAdapter as your gridview's adapter, you can override getFilter() method and return your own Filter, which is able to filter items according to entered text. See e.g. this link to learn how to work with Filter. Good luck. :-)