Gokhan Arik
Gokhan Arik

Reputation: 2766

SearchView back to search results implementation

I have a SearchView in my ActionBar that filters results and shows in a ListView. Once the user clicks on an item, I start a new activity to show the details of the item. When they hit the back button, I want to show filtered search results. The search phrase they typed stays in SearchView.

What would be the best way to achieve this?

Upvotes: 0

Views: 90

Answers (1)

NoChinDeluxe
NoChinDeluxe

Reputation: 3444

In my app, I had a few ways to get the search results into the search results activity. If the search activity was sending in the results, I would check for the results in the Intent extras. If an orientation change occurred, I would repopulate the search results using savedInstanceState, and if I navigate to the details activity, then come back again, I repopulate the search results from a saved file. So my onCreate() code has a structure like this:

if(savedInstanceState != null) {
    terms = savedInstanceState.getStringArrayList(TERM_RESULTS_KEY);
} else {
    Bundle args = getIntent().getExtras();
    if(args != null) {
        resultsData = args.getParcelableArrayList(SearchActivity.SEARCH_RESULT_ARGS);
        //...
    } else {
        terms = getSavedResults();
    }
}

When I navigate away from the activity (like going to a details page, as you mentioned), I save the search results like this:

private void saveResults(ArrayList<String> results) {
    try {
        FileOutputStream fileOutputStream = openFileOutput(SAVED_RESULTS_FILENAME, Context.MODE_PRIVATE);
        ObjectOutputStream out = new ObjectOutputStream(fileOutputStream);
        out.writeObject(results);
        out.close();
        fileOutputStream.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

Since ArrayList is serializable, it's pretty easy to just write to disk using an ObjectOutputStream. Then when the user hits the back button on your details activity, you would retrieve the previous search results like this:

@SuppressWarnings("unchecked")
private ArrayList<String> getSavedResults() {
    ArrayList<String> savedResults = null;

    try {
        FileInputStream inputStream = openFileInput(SAVED_RESULTS_FILENAME);
        ObjectInputStream in = new ObjectInputStream(inputStream);
        savedResults = (ArrayList<String>) in.readObject();
        in.close();
        inputStream.close();

    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    }

    return savedResults;
}

Upvotes: 1

Related Questions