Skip to content Skip to sidebar Skip to footer

Search Bar In Application

I am developing an application. In which a list view is displayed in which the data is coming from SQLite data base. I am getting data in String[]. Now the need of application is t

Solution 1:

Have a editext at the top of your listview. I suggest you to have a custom list adapter.

Have a list of original values for database.

Have another list to set temporary data to match the search criteria.

If your search criteria matches one in the list add those to founditmes and display the data in the list. If it does not match display original data in the list.

I have given a general idea. The below code can be modified according to your needs. I have implemented the search myself and it works.

I asked a question in SO and i got the answer from How to implement search in CustomListView based on class item of POJO class in Android?.

Try the below and if you are not able to get it working you can always post a question in SO.

     search= (EditText) findViewById(R.id.search);
     //look for text changing in edittext.
     search.addTextChangedListener(new TextWatcher() {

         publicvoidonTextChanged(CharSequence s, int start, int before, int count) {
                         youradapter.getFilter().filter(s);
                         youradapter.notifyDataSetChanged();

         }

         publicvoidbeforeTextChanged(CharSequence s, int start, int count,
             int after) {


           }

           publicvoidafterTextChanged(Editable s) {
           }
          });

Implement a filter on your list

publicvoidsetData(ArrayList mPpst) {   
         set data either searched data or original values from database
        mPostingData = mPpst;//contains class items data.
    }

 @OverridepublicFiltergetFilter() {
     returnnewFilter() {
         @OverrideprotectedvoidpublishResults(CharSequence constraint, FilterResults results) {
             if (results != null && results.count >= 0) {
                 setData( results.values);//if results match set data
             } else {
                 setData(mOri);// set data for listview original values.
             }

             notifyDataSetInvalidated();
         }



        @OverrideprotectedFilterResultsperformFiltering(CharSequence constraint) {
             FilterResults result = newFilterResults();
             if (!TextUtils.isEmpty(constraint)) {
                   ArrayList foundItems = newArrayList();
                 constraint = constraint.toString().toLowerCase();
                 if(listitems!=null)
                 {
                         if(listitems.equals(constarint))//matching
                         foundItems.add(listitems);

                     }
                     else
                     {

                     }
                 }
                 }
                 result.count = foundItems.size();//search results found return count
                 result.values = foundItems;// return values
             } 
             else
             {
                 result.count=-1;// no search results found
             }


             return result;
         }
     };
 }

Edit 1

how to set json parsed data in a listview and then adding search functionality in it. The answer in the link works. I have used temporary data and did a search function on it. You can display data form database and modify the same.

Edit 2:

publicclassMainActivityextendsActivity {

// List viewprivateListView lv;

// Listview AdapterArrayAdapter<String> adapter;

// Search EditTextEditText inputSearch;


// ArrayList for ListviewArrayList<HashMap<String, String>> productList;

@OverridepublicvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Listview DataString products[] = {"aaa","bbbb","cccc","dddd"};

    lv = (ListView) findViewById(R.id.list_view);
    inputSearch = (EditText) findViewById(R.id.inputSearch);

    // Adding items to listview
    adapter = newArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
    lv.setAdapter(adapter);

    /**
     * Enabling Search Filter
     * */
    inputSearch.addTextChangedListener(newTextWatcher() {

        @OverridepublicvoidonTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
            // When user changed the TextMainActivity.this.adapter.getFilter().filter(cs);   
        }

        @OverridepublicvoidbeforeTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
            // TODO Auto-generated method stub

        }

        @OverridepublicvoidafterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub                          
        }
    });
  }

}

Edit 3 Search with data from Database

publicclassSearchActivityextendsListActivity {
 ArrayAdapter<String> dataAdapter = null;

  private ArrayList<String> results = newArrayList<String>();
  privateStringtableName= DatabaseHandler.TABLE_SEARCH;
  private SQLiteDatabase newDB;
  ArrayAdapter<String> adapter = null;

  @OverridepublicvoidonCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.page_search);

   DatabaseHandlerdbHelper=newDatabaseHandler(this.getApplicationContext());
   newDB = dbHelper.getWritableDatabase();
   Cursorc= newDB.rawQuery("SELECT skeys FROM " +
        tableName, null);
   if (c != null ) {
    if  (c.moveToFirst()) {
        do {
            Stringskeys= c.getString(c.getColumnIndex("skeys"));
            results.add(skeys);
        }while (c.moveToNext());
    } 
 }           

dataAdapter = newArrayAdapter<String>(this,
        R.layout.listviews_search, results);

setListAdapter(newArrayAdapter<String>(this,
        R.layout.listviews_search, results));

  ListViewlistView= (ListView) findViewById(android.R.id.list);
  listView.setAdapter(dataAdapter);
  listView.setTextFilterEnabled(true);

  listView.setOnItemClickListener(newOnItemClickListener() {
      publicvoidonItemClick(AdapterView<?> parent, View view,
              int position, long id) {
          Toast.makeText(getApplicationContext(),
                  ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
      }
  });

  EditTextmyFilter= (EditText) findViewById(R.id.search);
  myFilter.addTextChangedListener(newTextWatcher(){
      publicvoidafterTextChanged(Editable s) {
  }

      publicvoidbeforeTextChanged(CharSequence s, int start, int count, int after) {
  }

      publicvoidonTextChanged(CharSequence s, int start, int before, int count) {
   dataAdapter.getFilter().filter(s.toString());
      }
  });
 }
}

Solution 2:

For your requirement you have to use Sectioned List view in android. Please see this link. http://samir-mangroliya.blogspot.in/2012/05/android-sectioned-listview-with-search_6865.html. It will help you alot.Let me know you have any doubts.

Post a Comment for "Search Bar In Application"