Search filter for filtering custom listview elements

2.3k views Asked by At

What i have done ::

  • I am able to implement displaying data through JSON from webservice and populating it into listview
  • I have implemented search-filter to search the elements based on text view

What i have problem:: Ill post a series of snapshots explaining my problem


  1. Snapshot1 :: i have the listview showing series of elements in list

enter image description here

  1. Snapshot2:: Now when i type carl, my names are filtered and only matching result is shown

enter image description here

  1. Snapshot3:: Now remove all the things in search bar ..... I should get the display as shown in snapshot1 which is not happening

enter image description here

Overall:: what happening is once its filtered i can't use it for another try ... i have to recompile whole project again


ListOfContacts.java

public class ListOfContacts extends Activity {
    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String NAME = "rank";
    static String FLAG = "flag";
    EditText mEditText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from listview_main.xml
        setContentView(R.layout.listview_main);


        // Locate the listview in listview_main.xml
        listview = (ListView) findViewById(R.id.listview);
        mEditText = (EditText) findViewById(R.id.inputSearch);
        // Execute DownloadJSON AsyncTask
        new DownloadJSON().execute();


    }

    // DownloadJSON AsyncTask
    class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(ListOfContacts.this);
            // Set progressdialog title
            //mProgressDialog.setTitle("Fetching the information");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            jsonobject = JSONfunctions.getJSONfromURL("http://URL");

            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("restaurants");

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put(ListOfContacts.NAME, jsonobject.getString("Person_Name"));
                    map.put(ListOfContacts.FLAG, "http://54.218.73.244:7004/"+jsonobject.getString("Image_Name"));



                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(ListOfContacts.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog

            mEditText = (EditText) findViewById(R.id.inputSearch);
            mEditText.addTextChangedListener(new TextWatcher()
            {

                public void afterTextChanged(Editable s)
                {

                }

                public void beforeTextChanged(CharSequence s, int start,int count, int after)
                {

                }

                public void onTextChanged(CharSequence s, int start,int before, int count)
                {

                    ArrayList<HashMap<String, String>> arrayTemplist= new ArrayList<HashMap<String,String>>();
                    String searchString =mEditText.getText().toString();
                    for (int i = 0; i < arraylist.size(); i++)
                    {
                        String currentString =arraylist.get(i).get(ListOfContacts.NAME);
                        if (searchString.equalsIgnoreCase(currentString))
                        {
                            arrayTemplist.add(arraylist.get(i));
                        }
                    }
                    adapter = new ListViewAdapter(ListOfContacts.this, arrayTemplist);
                    listview.setAdapter(adapter);
                 }
                });
            mProgressDialog.dismiss();
        }
    }
}

DataAcceptActivity.java

public class DataAcceptActivity extends Activity {

    Button submit;
    Button display;
    ProgressDialog pDialog;
    InputStream is;
    EditText name;
    ImageView imageView;
    EditText search;

    private static final int SELECT_PICTURE = 1;
    private String selectedImagePath;

    int[] image_array={R.drawable.index,R.drawable.image1,R.drawable.image5,R.drawable.image6,R.drawable.image7,R.drawable.image8,R.drawable.image9,R.drawable.image10};

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

        submit = (Button) findViewById(R.id.SUBMIT_BUTTON_ID);
        name = (EditText) findViewById(R.id.editText1);
        imageView = (ImageView) findViewById(R.id.imageView1);
        display=(Button) findViewById(R.id.DISPLAY_BUTTON_ID);

        search=(EditText) findViewById(R.id.inputSearch);

        display.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent searchIntent=new Intent(DataAcceptActivity.this,ListOfContacts.class);
                startActivity(searchIntent);

            }
        });


        submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new MainTest().execute();


            }
        });


        imageView.setOnClickListener(new  OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
            }
        });




    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {
                Uri selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
                System.out.println("Image Path : " + selectedImagePath);
                imageView.setImageURI(selectedImageUri);
            }
        }
    }

    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }



    /**
     * Method to post the image to the server.
     * U will have to change the url which will accept the image data.
     * @throws IOException 
     */
    public void postImageData() {


        try
        {

            Bitmap bitmapOrg = ((BitmapDrawable)imageView.getDrawable()).getBitmap();

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost("http://URL");
            MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            try{
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmapOrg.compress(CompressFormat.JPEG, 75, bos);
                byte[] data = bos.toByteArray();
                ByteArrayBody bab = new ByteArrayBody(data, "image.jpg");
                reqEntity.addPart("key", bab);
                reqEntity.addPart("key1", new StringBody(name.getText().toString()));
            }
            catch(Exception e){
                //Log.v("Exception in Image", ""+e);
                reqEntity.addPart("picture", new StringBody(""));
            }
            postRequest.setEntity(reqEntity);       
            HttpResponse response = httpClient.execute(postRequest);
            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
            String sResponse;
            StringBuilder s = new StringBuilder();
            while ((sResponse = reader.readLine()) != null) {
                s = s.append(sResponse);
            }
        }catch(Exception e){
            e.getStackTrace();
        }


    }
    public class MainTest extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            pDialog = new ProgressDialog(DataAcceptActivity.this);
            pDialog.setMessage("Loading..");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {

            postImageData();

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub

            super.onPostExecute(result);
            // data=jobj.toString();
            pDialog.dismiss();
            Toast.makeText(getApplicationContext(), "File Uploaded", Toast.LENGTH_SHORT).show();
        }

    }


    class ImageAdapter extends BaseAdapter{

        Context cxt;
        public ImageAdapter(DataAcceptActivity dataAcceptActivity) {
            // TODO Auto-generated constructor stub
            this.cxt=dataAcceptActivity;
        }

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

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

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

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

            ImageView imageView ;
            if(convertView==null){
                imageView=new ImageView(cxt);
                imageView.setLayoutParams(new GridView.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(15, 15, 15, 15);
            }else{
                imageView=(ImageView) convertView;
            }

            imageView.setImageResource(image_array[position]);
            return imageView;
        }

    }

}

MainActivity.java

public class MainActivity extends Activity {
    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;

    static String NAME = "rank";
    static String FLAG = "flag";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from listview_main.xml
        setContentView(R.layout.listview_main);


        // Locate the listview in listview_main.xml
        listview = (ListView) findViewById(R.id.listview);

        // Execute DownloadJSON AsyncTask
        new DownloadJSON().execute();
    }

    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(MainActivity.this);
            // Set progressdialog title
            //mProgressDialog.setTitle("Fetching the information");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            jsonobject = JSONfunctions.getJSONfromURL("http://URL");

            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("restaurants");

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put(MainActivity.NAME, jsonobject.getString("restaurantNAME"));;
                    map.put(MainActivity.FLAG, "http://url"+jsonobject.getString("restaurantIMAGE"));


                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(MainActivity.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog
            mProgressDialog.dismiss();
        }
    }
}

Any ideas on resolving this, Thanks

4

There are 4 answers

0
Niranj Patel On BEST ANSWER

Just put condition for search string length.

mEditText.addTextChangedListener(new TextWatcher()
    {

        public void afterTextChanged(Editable s)
        {

        }

        public void beforeTextChanged(CharSequence s, int start,int count, int after)
        {

        }

        public void onTextChanged(CharSequence s, int start,int before, int count)
        {

            ArrayList<HashMap<String, String>> arrayTemplist= new ArrayList<HashMap<String,String>>();
            String searchString =mEditText.getText().toString().trim();
            if(searchString.length()>0)
            {
                for (int i = 0; i < arraylist.size(); i++)
                {
                    String currentString =arraylist.get(i).get(ListOfContacts.NAME);
                    if (searchString.equalsIgnoreCase(currentString))
                    {
                        arrayTemplist.add(arraylist.get(i));
                    }
                }
                adapter = new ListViewAdapter(ListOfContacts.this, arrayTemplist);
                listview.setAdapter(adapter);
            }
            else
            {
                adapter = new ListViewAdapter(ListOfContacts.this, arraylist);
                listview.setAdapter(adapter);
            }
         }
        });
0
Ketan Ahir On

try following code

 if(arraryTemplist.size()>0){
      adapter = new ListViewAdapter(ListOfContacts.this, arrayTemplist);
                    listview.setAdapter(adapter);
  }else{

     adapter = new ListViewAdapter(ListOfContacts.this, arraylist);
                    listview.setAdapter(adapter);
}
0
Suau On

it happens because you filter for an empty String e.g. searchString.equalsIgnoreCase(""). you can easily fix it in your code. However i'd recommend you'd rather implement the filterable interface in your custom arrayadapter. http://developer.android.com/reference/android/widget/Filterable.html check out the ArrayAdapter source code for an example on how to do that: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/widget/ArrayAdapter.java

1
Salman Khan On

On Text Change Listener set the adapter with local values :-

@Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        // TODO Auto-generated method stub

                        ArrayList<String> STOREID_SUB = new ArrayList<String>();
                        ArrayList<String> STORE_NAME_SUB = new ArrayList<String>();
                        ArrayList<String> PHOTO_SUB = new ArrayList<String>();
                        final ArrayList<String> STORE_DESC_SUB = new ArrayList<String>();

                        textlength = searchText.getText().length();

                        for (int i = 0; i < STORE_NAME.size(); i++)
                        {
                            if (textlength <= STORE_NAME.get(i).length())
                            {
                                if (searchText.getText().toString().
                                        equalsIgnoreCase((String) STORE_NAME.get(i).subSequence(0, textlength)))
                                {
                                    STORE_NAME_SUB.add(STORE_NAME.get(i));
                                    STOREID_SUB.add(STOREID.get(i));
                                    PHOTO_SUB.add(PHOTO.get(i));
                                    STORE_DESC_SUB.add(STORE_DESC.get(i));  


                                }
                            }
                        }

                        adapter=new StoreSearchListAdapter(context, R.drawable.ic_launcher, R.drawable.ic_launcher, STORE_NAME_SUB, PHOTO_SUB,STORE_DESC_SUB);
                        singlePlaceChooserList.setAdapter(adapter);             

                    }