Search code examples
javaandroidandroid-fragmentsrotationsearchview

Maintaining result of search view on rotating phone


I am quite new to this (java,android and stack overflow), so bear with me. I have a bunch of products that I read from my database and I store/add to my ArrayList of type product and output this to a Recycleview. I also have implemented a searchview library called materialsearchview from GitHub and everything works as intended. Meaning initially I have every product in the list and when I search I get a new list with products that have the same or close to the same title. However, upon rotating the phone the list goes back to the default one with every product and the text in the searchview is maintained. Is there a way to keep the new list of products that has derived from the search after rotating the phone in this fragment?

public class GFragment extends Fragment{
     private static final String READ_ALL_PRODUCTS_REQUEST_URL = "****";
     RecyclerView recyclerView;
     ProductsAdapter adapter;
     List<Product> productList;

    TextView product_id;
    ImageView product_image;
    MaterialSearchView searchView;

   @Nullable
   @Override
   public View onCreateView(@NonNull LayoutInflater inflater, @Nullable 
   ViewGroup container, @Nullable final Bundle savedInstanceState) {

      setHasOptionsMenu(true);
      View view = inflater.inflate(R.layout.fragment_products, null);
      productList = new ArrayList<>();
      recyclerView = (RecyclerView) view.findViewById(R.id.list);
      recyclerView.setHasFixedSize(true);
      recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

     StringRequest stringRequest = new StringRequest(Request.Method.GET, 
     READ_ALL_PRODUCTS_REQUEST_URL , new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONArray products = new JSONArray(response);
                    for (int i = 0; i < products .length(); i++) {
                        JSONObject productObject = products.getJSONObject(i);
                        //storing the variables from database
                        String id = productObject.getString("product_id");
                        String title= 
                        productObject.getString("product_title");
                        Product product= new Product(id);
                        productList.add(product);
                    }
                    adapter = new productAdapter(getActivity(), productList);
                    recyclerView.setAdapter(adapter);
                    //Search
                    searchView = (MaterialSearchView) 
                    getActivity().findViewById(R.id.search_view);
                    searchView.setOnSearchViewListener(new 
                    MaterialSearchView.SearchViewListener() {
                        @Override
                        public void onSearchViewShown() {
                        }
                        @Override
                        public void onSearchViewClosed() {
                            searchView = (MaterialSearchView) 
                            getActivity().findViewById(R.id.search_view);
                            adapter = new 
                            productAdapter(getActivity(),productList);
                            recyclerView.setAdapter(adapter);
                        }
                   });
                   searchView.setOnQueryTextListener(new 
                   MaterialSearchView.OnQueryTextListener() {

                       @Override
                       public boolean onQueryTextSubmit(String query) {
                            if (query != null && !query.isEmpty()) {
                                List<Product> currentproductList = new 
                                ArrayList<Product>();
                                for (Productitem : producteList) {
                                    String title = item.getProduct_title();
                                    if (title.contains(query) ||                                                   
                                    title.toLowerCase().contains(query) ||
                                    title.toUpperCase().contains(query)) {
                                        currentproductList.add(item);
                                    }
                                }
                                adapter = new VideoGameAdapter(getActivity(), 
                                currentproductList);
                                recyclerView.setAdapter(adapter);
                            }
                            else {
                               adapter = new productAdapter(getActivity(), 
                               productList);
                               recyclerView.setAdapter(adapter);
                            }
                            //Hide Keyboard
                            View view = 
                            getActivity().findViewById(android.R.id.content);
                            if (view != null) {
                               InputMethodManager imm = (InputMethodManager) 
                               getActivity().getSystemService(
                               Context.INPUT_METHOD_SERVICE);                                          
                               imm.hideSoftInputFromWindow(view.
                               getWindowToken(), 0);
                            }
                            return true;
                        }

                        @Override
                        public boolean onQueryTextChange(String newText) {
                            if (newText != null && !newText.isEmpty()) {
                                List<Product> currentproductList = new 
                                ArrayList<Product>();
                                for (Productitem : productList) {
                                    String title = item.getProduct_title();
                                    if (title.contains(newText) ||                                                    
                                    title.toLowerCase().contains(newText) ||                                                        
                                    title.toUpperCase().contains(newText)) {                                                   
                                         currentproductList.add(item);
                                    }
                                }
                                adapter = new productAdapter(getActivity(), 
                                currentproductList);
                                recyclerView.setAdapter(adapter);
                            }
                            else {
                                adapter = new productAdapter(getActivity(), 
                                productList);
                                recyclerView.setAdapter(adapter);
                           }
                           return true;
                       }
                   });
               } catch (JSONException e) {
                   e.printStackTrace();
               }
            }
        },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getActivity(), "Error", 
                    Toast.LENGTH_SHORT).show();
               }
           });
       Volley.newRequestQueue(getActivity()).add(stringRequest);        
       return view
   }

   @Override
   public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
       super.onCreateOptionsMenu(menu, inflater);
       inflater.inflate(R.menu.main, menu);
       MaterialSearchView searchView = 
       (MaterialSearchView)getActivity().findViewById(R.id.search_view);
       final MenuItem item = menu.findItem(R.id.action_search);
       searchView.setMenuItem(item);
  }
}

Solution

  • I'd use onSaveInstance state, which will save your state between rotations. Make your JSON results into a global string, then retrieve the results. It will go something like this:

    public class GFragment extends Fragment{
      private String json;
      private final String KEY_JSON = "json";
      //..rest of variables
    } 
    
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(KEY_JSON, user);
    
    }
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable 
      ViewGroup container, @Nullable final Bundle savedInstanceState) { 
         if (savedInstanceState != null) {
           json = savedInstanceState.getString(KEY_JSON);
    
        } else {
           json = ""
        }
        //...rest of onCreateView()
    
       if (!TextUtils.isEmpty(json) {
            parseJSON();
       }
    
      }
    
    private void parseJSON() {
       try {
         JSONArray products = new JSONArray(response);
         for (int i = 0; i < products .length(); i++) {
             JSONObject productObject = products.getJSONObject(i);
             //storing the variables from database
             String id = productObject.getString("product_id");
             String title= 
             productObject.getString("product_title");
             Product product= new Product(id);
             productList.add(product);
          }
          adapter = new productAdapter(getActivity(), productList);
          recyclerView.setAdapter(adapter);
              //..any other parsing
          }
          catch (JSONException e) {
             e.printStackTrace();
          }
      }