1

I was using this code to search from my MainActivity Toolbar in a ListView:

    SearchView searchView;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate( R.menu.main, menu);

    MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
    searchView = (SearchView) myActionMenuItem.getActionView();
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }
        @Override
        public boolean onQueryTextChange(String s) {
            adapter.getFilter().filter(s);
            return false;
        }
    });
    return true;

}

But now I moved my Listview to a fragment, how can I pass the adapter from the fragment to the main activity? How can I update the typing? Is there any better way then passing the adapter? Thank you in advance

Johnson
  • 297
  • 2
  • 5
  • 18

3 Answers3

1

Try This code,

activity_main.xml :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="#009688" />

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/fragment"
        android:name="ru.lemmaproj.toolbar_search.MainActivityFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout="@layout/fragment_main" />

</LinearLayout>

fragment_main.xml :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivityFragment">

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

search_layout.xml :

<EditText xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:cursorVisible="true"
    android:imeOptions="actionDone"
    android:inputType="text" />

MainActivity.java :

public class MainActivity extends AppCompatActivity {

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }
}

MainActivityFragment.java :

public class MainActivityFragment extends Fragment {

    private final String[] items = new String[] { "Android", "iOS", "Windows Phone",
            "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2" };

    private ListView listView;
    private ArrayAdapter<String> adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);

        listView = (ListView) view.findViewById(R.id.list);
        adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
        listView.setAdapter(adapter);

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_fragment, menu);

        MenuItem searchItem = menu.findItem(R.id.menu_search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
        if (searchView != null) {
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    return true;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    adapter.getFilter().filter(newText);
                    return true;
                }
            });
        }
    }

}
jeel raja
  • 667
  • 5
  • 11
  • I'm sorry I can't make it work in my application. I copied the last part of the fragment.java (from onActivityCreated), and changed just the layout references, but it crashes when I try to run – Johnson Jan 04 '17 at 11:34
1

A better approach can be using EventBus. It's really helpful in a scenario like this in which we have to pass certain data from an Activity to a Fragment.

For using EventBus, you need to define a POJO class, somewhat like this:

class SearchQueryEvent {
    String query;

    public SearchQueryEvent(String query) {
        this.query=query;
    }

    public String getQuery() {
        return query;
    }
}

Now, your code should be modified like this:

MainActivity.java

SearchView searchView;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate( R.menu.main, menu);

    MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
    searchView = (SearchView) myActionMenuItem.getActionView();
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }
        @Override
        public boolean onQueryTextChange(String s) {
            EventBus.getDefault().post(new SearchQueryEvent(s));
            return false;
        }
    });
    return true;

}

YourFragment.java

@Override
public void onResume() {
    super.onResume();
    EventBus.getDefault().register(this);
}

@Override
public void onPause() {
    EventBus.getDefault().unregister(this);
    super.onPause();
}

@Subscribe(threadMode = ThreadMode.MAIN)
public void onSearchQuery(SearchQueryEvent event) {
    String query=event.getQuery();
    adapter.getFilter().filter(query);
}
Community
  • 1
  • 1
Hitesh Pamnani
  • 177
  • 3
  • 14
  • Cannot resolve symbol 'EventBus', do I have to import something? – Johnson Jan 04 '17 at 12:56
  • Yes, add the following line inside your build.gradle (app) where all the 'compile' statements are written. `compile 'org.greenrobot:eventbus:3.0.0'` – Hitesh Pamnani Jan 05 '17 at 05:42
  • I did it but it doesn't apply the filter to the adapter, and in the fragment.java `.unsubscribe(this);` and `.subscribe(this);` give me the error "Cannot resolve method", how can I do? – Johnson Jan 05 '17 at 14:44
  • The void onSearchQuery in the fragment is never used – Johnson Jan 05 '17 at 14:49
  • After adding the 'compile' statement, you've to build the entire project to get the references. Once the project is rebuilt, you'll be able to see the methods in EventBus class. – Hitesh Pamnani Jan 06 '17 at 06:58
  • I did it all, but look here: https://1drv.ms/f/s!AniEkQ5k9-XDnHli-hT2uu6eTcxL this is what happens and I'm not able to search from the fragment. I don't know what I do wrong – Johnson Jan 06 '17 at 09:41
  • I am really sorry. Please see the updated code. You'll get that running now. Sorry again for silly mistake. – Hitesh Pamnani Jan 06 '17 at 10:33
  • You don't have to be sorry at all, that's perfect! Thank you so much! – Johnson Jan 06 '17 at 11:21
1

1-> Create a static method in fragment

public static void doSearch(String query){
    yourAdapter.filter(query);
}

2-> Call this method from activity on onQueryTextChange method and pass the query you want to search

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.home, menu);

    MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
    searchViewShop = (SearchView) myActionMenuItem.getActionView();
    searchViewShop.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            YourFragment.doSearch(newText);
            return true;
        }
    });
    return true;
}