Monday, April 28, 2014

Android Action Bar search inside activity | Searching into list-view using action bar | Android Action Bar

Hello Friend,

Today I am going to share some of my experience related to Action bar in Android. Have you seen many apps like whats-app and some others top app there are a action-bar search functionality. So let us see how can we do it-





















1)If you want to get search result on same activity-

i-In your manifest,xml just add search action and searchable meta data-

 <activity
            android:name="com.androidhub4you.searchactionbardemo.SearchActivity"
            android:launchMode="singleTop" >
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>

            <meta-data
                android:name="android.app.searchable"
                android:resource="@xml/searchable" />
        </activity>

ii- Create a searchable file inside res/xml-

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:hint="search..."
    android:label="@string/app_name" />

iii- In your menu.xml file add below code-

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <!-- Search Widget -->
    <item
        android:id="@+id/action_search"
        android:actionViewClass="android.widget.SearchView"
        android:icon="@drawable/ic_launcher"
        android:showAsAction="always"
        android:title="Search"/>

</menu>

iv- And finally inside your activity class-


public class SearchActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_results);
// get the action bar
ActionBar actionBar = getActionBar();

// Enabling Back navigation on Action Bar icon
actionBar.setDisplayHomeAsUpEnabled(true);

//txtQuery = (TextView) findViewById(R.id.txtQuery);

handleIntent(getIntent());
}

@Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
handleIntent(intent);
}

*//**
* Handling intent data
*/
 
  
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);

txtQuery.setText("Search Query: " + query);

}
}

2)If you want searching into listview-

package com.androidhub4you.searchactionbardemo;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;

public class SearchActivity extends Activity {

       ArrayAdapter<String> myAdapter;
    ListView listView;
    String[] dataArray = new String[] {"India","Androidhub4you", "Pakistan", "Srilanka", "Nepal", "Japan"};

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_search_results);
             
             
              //==========================
             
              listView = (ListView) findViewById(R.id.listview);
           myAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataArray);
           listView.setAdapter(myAdapter);
           listView.setTextFilterEnabled(true);
          
        listView.setOnItemClickListener(new OnItemClickListener() {

              @Override
              public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                           long arg3) {

              System.out.println(arg2+" --postion");
              }
       });

       }
      
       @Override
       public boolean onCreateOptionsMenu(Menu menu) {
              MenuInflater inflater = getMenuInflater();
              inflater.inflate(R.menu.main, menu);

               SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
               SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();

                   searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
                   searchView.setIconifiedByDefault(false);  

               SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener()
               {
                   @Override
                   public boolean onQueryTextChange(String newText)
                   {
                       // this is your adapter that will be filtered
                       myAdapter.getFilter().filter(newText);
                       System.out.println("on text chnge text: "+newText);
                       return true;
                   }
                   @Override
                   public boolean onQueryTextSubmit(String query)
                   {
                       // this is your adapter that will be filtered
                       myAdapter.getFilter().filter(query);
                       System.out.println("on query submit: "+query);
                       return true;
                   }
               };
               searchView.setOnQueryTextListener(textChangeListener);

               return super.onCreateOptionsMenu(menu);

       }
}

Thank you!

21 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Your information about android application is really interesting. Also I want to know the latest android developments in recent years. Can you update it in your website?
    Android Training in Chennai

    ReplyDelete
  3. can you update it for lower api? I use appcompat v7 library. In order to get the actionbar working I need to extend to ActionBarActivity only which generate errors.

    ReplyDelete
  4. Hi Manish

    How can i search listview which is populated from json data?
    i am new to ANdroid.

    ReplyDelete
  5. Thank you for the article! Can you tell me how to get Object item select when i searched?
    Eg: Result for my searched are two object and listview has tow item. I want get item, which I select?
    Thank you!

    ReplyDelete
  6. thank you so much for that
    iam doing an application ,
    i got my contact on a listview by ContentResolver , i used ResourceCursorAdapter ,
    i want to know how i do the search meanwhile the listview is on a fragment not on the activity directly ...
    thank you very much

    ReplyDelete
  7. Thanks! I was literally applying your codes in despair thinking such a problem doesn't seem to be this easy, and that makes me so surprised as it provided the exact solution precisely, no more, no less! Thanks again and keep up the good work!

    ReplyDelete
  8. Hi, Manish

    i need one help.
    I am using toolbar in place of action bar.
    so can you help me how to use search bar in listview with toolbar

    ReplyDelete
  9. Hey Manish
    Your code was quite helpful.But, how can i display corresponding image for the searched item beside it?
    For Example:If i have searched for an item called Cantaloupe then the corresponding image should also be displayed beside it.

    Thanks in advance!

    ReplyDelete
  10. Its not working for me i am using android studio and it gives me null pointer exception at

    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

    and

    searchView.setIconifiedByDefault(false);

    I need help here.....

    ReplyDelete
    Replies
    1. No idea dear what's wrong. Well i think it is theme issue, please check on stackvoerflow if someone have posted anything.

      Delete
  11. This comment has been removed by the author.

    ReplyDelete
  12. This comment has been removed by the author.

    ReplyDelete
  13. This comment has been removed by the author.

    ReplyDelete
  14. How can I search the activity's children???
    Eg. I have 15 buttons, card views, text views, whatever the children are. How can I search it?

    ReplyDelete
    Replies
    1. Well this code is for search inside listview and I believe you can use it with any type of collection Eg- grid, list, card etc.
      But if you want to search feature on text, button you need to write your own logic.

      Delete