title: How do I filter options using a spinner that saves selection and applies to an API? - ANDROID
body: <p>I'm having a hard time finding an answer to this, since there are many elements involved. I made a simple search engine app that uses spinners to select filtering options for the search, e.g. you can select what color or size of the image you are searching for. I am using the Google search API and the search parameters in their API (JSON format). Here is the developer link (shows parameter names I had to use): <a href="https://developers.google.com/image-search/v1/jsondevguide#request_format" rel="nofollow">https://developers.google.com/imagesearch/v1/jsondevguide#request_format</a></p>
  
  <p><strong>The problem:</strong> The app runs fine, except when you select a filter option, e.g. red... it actually returns the wrong filter, it returns blue. I looked in my switch statements where I order the API parameters by case number, and they match my XML layout in my strings.xml (not sure the strings order matters), as well as matching the actual dropdown list spinner order when I run the app. I also use the <code>getSelectedItemPosition()</code> method, which I assume would get the actual filter selected, but I must be missing something.</p>
  
  <p>Even though this project is very involved, I got help with a lot of the code, so I'm not sure really what it all means (or does)... I am still learning and a beginner.</p>
  
  <p>I will post my 2 main activities, but if you need more (like my XMLs) let me know. The 2 activities are very long, so didn't want to post too much if I don't need to. Thank you very much in advance!</p>
  
  <p><strong>My main activity that has an EditText field, a Search button, and an Advanced search button (which leads to activity #2 below this one).</strong></p>
  
  <pre><code>package com.noni.gridimagesearch;
  
  import java.util.ArrayList;
  
  import org.json.JSONArray;
  import org.json.JSONException;
  import org.json.JSONObject;
  
  import android.app.Activity;
  import android.content.Intent;
  import android.content.SharedPreferences;
  import android.net.Uri;
  import android.os.Bundle;
  import android.util.Log;
  import android.view.Menu;
  import android.view.MenuItem;
  import android.view.View;
  import android.view.View.OnClickListener;
  import android.widget.AdapterView;
  import android.widget.AdapterView.OnItemClickListener;
  import android.widget.Button;
  import android.widget.EditText;
  import android.widget.GridView;
  import android.widget.Toast;
  
  import com.loopj.android.http.AsyncHttpClient;
  import com.loopj.android.http.JsonHttpResponseHandler;
  
  public class SearchActivity extends Activity {
      EditText etQuery;
      GridView gvResults; 
      Button btnSearch;
      Button advancedSearch;
      String filterPreferences;
      private String FilterPreferences;
  
      ArrayList&lt;ImageResult&gt; imageResults = new ArrayList&lt;ImageResult&gt;();
      ImageResultArrayAdapter imageAdapter;
  
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_search);
  
          setupViews();
  
          //This enables you to click on an image, and see it in its own activity
          imageAdapter = new ImageResultArrayAdapter(this, imageResults);
          gvResults.setAdapter(imageAdapter);
          gvResults.setOnItemClickListener(new OnItemClickListener() {
              @Override
              public void onItemClick(AdapterView&lt;?&gt; adapter, View parent, 
                      int position, long rowId) {
                  Intent i = new Intent(getApplicationContext(), 
                          ImageDisplayActivity.class);
                  ImageResult imageResult = imageResults.get(position);
                  i.putExtra("result", imageResult);
                  startActivity(i);
              }
          });
  
  //      //Attempt at the endless scroll feature
  //      GridView gvResults = (GridView) findViewById(R.id.gvResults);
  //      gvResults.setOnScrollListener(new EndlessScrollListener() {
  //          @Override
  //          public void onLoadMore(int page, int totalItemsCount) {
  //              loadMoreImages(totalItemsCount); 
  //          }
  //      });
  //      
  //      public void loadMoreImages(int totalItemsCount) {
  //          String query = etQuery.getText().toString();
  //          AsyncHttpClient client = new AsyncHttpClient();
  //          makeAsyncHttpGetRequest(client, totalItemsCount, query);
  //      }
  
          //Create intent to go from Advanced Search button to Advanced Search Activity
          Button advancedSearch = (Button) findViewById(R.id.advancedSearch);
          advancedSearch.setOnClickListener(new OnClickListener() {
              public void onClick(View v){
                  Intent i = new Intent (SearchActivity.this, AdvancedOptionsActivity.class);
                  startActivity(i);
              }   
          });
  
      }//end onCreate method
  
      public void setupViews() {
          etQuery = (EditText) findViewById(R.id.etQuery);
          gvResults = (GridView) findViewById(R.id.gvResults);
          btnSearch = (Button) findViewById(R.id.btnSearch);  
      }
  
      //Using onClick method from btnSearch in layout, called onImageSearch
      public void onImageSearch(View v) {
          String query = etQuery.getText().toString();
          Toast.makeText(this, "Searching for " + query, Toast.LENGTH_SHORT).show();
          //Then makes the HTTP request from the Google API
          AsyncHttpClient client = new AsyncHttpClient();
          imageResults.clear(); 
          int offset = 0;
          FilterPreferences = getFilterPreferences();
          client.get("https://ajax.googleapis.com/ajax/services/search/images?rsz=8&amp;" + 
          FilterPreferences + "start=" + offset + "&amp;v=1.0&amp;q=" + Uri.encode(query),
                  new JsonHttpResponseHandler() { //A handler is set in case the search doesn't work
                  @Override
                  public void onSuccess(JSONObject response) {
                      JSONArray imageJsonResults = null;
                      try {
                          imageJsonResults = response.getJSONObject("responseData")
                              .getJSONArray("results");
                          imageAdapter.addAll(ImageResult
                              .fromJSONArray(imageJsonResults));
                          Log.d("DEBUG", imageResults.toString());
                      } catch (JSONException e) {
                      e.printStackTrace();
                      }
                  } //End onSuccess
          }); //End client.get()  
  
      } //End onImageSearch 
  
      //Spells out all my filter preferences by using the API "language" put into variables
      //and ultimately becomes a part of the getFilterPreferences method
      public String getFilterPreferences() {
  
          String filterPreferences, imageType, imageSize, colorFilter = null;
  
          SharedPreferences filters = getSharedPreferences(AdvancedOptionsActivity.FILTERS, 0);
  
          switch(filters.getInt("image_type", 0)) {
              case 0:  imageType = "";                 break;
              case 1:  imageType = "&amp;imgtype=face";    break;
              case 2:  imageType = "&amp;imgtype=photo";   break;
              case 3:  imageType = "&amp;imgtype=lineart"; break;
              case 4:  imageType = "&amp;imgtype=clipart"; break;
              default: imageType = "";
          }
          switch(filters.getInt("color_filter", 0)) {
              case 0: colorFilter = "";                 break;
              case 1: colorFilter = "&amp;imgcolor=blue";   break;
              case 2: colorFilter = "&amp;imgcolor=red";    break;
              case 3: colorFilter = "&amp;imgcolor=green";  break;
              case 4: colorFilter = "&amp;imgcolor=orange"; break;
              case 5: colorFilter = "&amp;imgcolor=gray";   break;
              default: colorFilter = "";
          }
          switch(filters.getInt("image_size", 0)) {
              case 0:  imageSize = "";              break;
              case 1:  imageSize = "&amp;imgsz=small";  break;
              case 2:  imageSize = "&amp;imgsz=medium"; break;
              case 3:  imageSize = "&amp;imgsz=large";  break;
              case 4:  imageSize = "&amp;imgsz=xlarge"; break;
              default: imageSize = "";
          }
  
          filterPreferences = imageType + colorFilter + imageSize;
          //If selects nothing, it will still run the filterPreferences variable 
          //to include the default selections (filters shown in top row of spinner)
          if (filterPreferences.equals("")) return filterPreferences;
          else return filterPreferences + "&amp;";
  
      }// End getFilterPreferences
  
      @Override
      public boolean onCreateOptionsMenu(Menu menu) {
  
          // Inflate the menu; this adds items to the action bar if it is present.
          getMenuInflater().inflate(R.menu.search, menu);
          return true;
      } 
  
      @Override
      public boolean onOptionsItemSelected(MenuItem item) {
          // Handle action bar item clicks here. The action bar will
          // automatically handle clicks on the Home/Up button, so long
          // as you specify a parent activity in AndroidManifest.xml.
          int id = item.getItemId();
          if (id == R.id.action_settings) {
              return true;
          }
          return super.onOptionsItemSelected(item);
      }
  }
  </code></pre>
  
  <p><strong>My 2nd activity which has all the spinners and filter options:</strong></p>
  
  <pre><code>package com.noni.gridimagesearch;
  
  import android.app.Activity;
  import android.content.Intent;
  import android.content.SharedPreferences;
  import android.os.Bundle;
  import android.view.Menu;
  import android.view.MenuItem;
  import android.view.View;
  import android.widget.ArrayAdapter;
  import android.widget.Button;
  import android.widget.Spinner;
  
  public class AdvancedOptionsActivity extends Activity {
  
      private Spinner colorFilter, imageSize, imageType;
      protected static final String FILTERS = "FilterPreferences";
      private Button btnSubmit;
      private ArrayAdapter&lt;CharSequence&gt; imageSizeAdapter, colorFilterAdapter, imageTypeAdapter;
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_advanced_options);
  
          setupViews();
          restoreFilterPreferences();
      }
  
      private void setupViews() {
  
          imageType = (Spinner) findViewById(R.id.image_type);
          imageTypeAdapter = ArrayAdapter.createFromResource(this, 
                  R.array.image_type, android.R.layout.simple_spinner_item);
          imageTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
          imageType.setAdapter(imageTypeAdapter);
  
          colorFilter = (Spinner) findViewById(R.id.color_filter);
          colorFilterAdapter = ArrayAdapter.createFromResource(this, 
                  R.array.color_filter, android.R.layout.simple_spinner_item);
          colorFilterAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
          colorFilter.setAdapter(colorFilterAdapter);
  
          imageSize = (Spinner) findViewById(R.id.image_size);
          imageSizeAdapter = ArrayAdapter.createFromResource(this, 
                  R.array.image_size, android.R.layout.simple_spinner_item);
          imageSizeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
          imageSize.setAdapter(imageSizeAdapter);
  
          btnSubmit = (Button) findViewById(R.id.btnSubmit);
          btnSubmit.setOnClickListener(new View.OnClickListener() {
  
              @Override
              public void onClick(View v) {
                  Intent i = new Intent();
                  setResult(RESULT_OK, i);
                  finish();
              }
          }); 
      }   
  
      private void restoreFilterPreferences() {
          SharedPreferences filters = getSharedPreferences(FILTERS, 0);
  
          int imageSizeSelection = filters.getInt("image_size", 0);
          imageSize.setSelection(imageSizeSelection);
  
          int colorFilterSelection = filters.getInt("color_filter", 0); 
          colorFilter.setSelection(colorFilterSelection);
  
          int imageTypeSelection = filters.getInt("image_type", 0);
          imageType.setSelection(imageTypeSelection);
      }
  
      @Override
      protected void onPause() {
          super.onPause();
          saveFilterPreferences();
      }
  
      private void saveFilterPreferences() {
          SharedPreferences filters = getSharedPreferences(FILTERS, 0);
          SharedPreferences.Editor editor = filters.edit();
          editor.putInt("image_size", imageSize.getSelectedItemPosition()); 
          editor.putInt("color_filter", colorFilter.getSelectedItemPosition());
          editor.putInt("image_type", imageType.getSelectedItemPosition()); 
          editor.commit(); 
      }
  
      @Override
      public boolean onCreateOptionsMenu(Menu menu) {
  
          // Inflate the menu; this adds items to the action bar if it is present.
          getMenuInflater().inflate(R.menu.advanced_options, menu);
          return true;
      }
  
      @Override
      public boolean onOptionsItemSelected(MenuItem item) {
          // Handle action bar item clicks here. The action bar will
          // automatically handle clicks on the Home/Up button, so long
          // as you specify a parent activity in AndroidManifest.xml.
          int id = item.getItemId();
          if (id == R.id.action_settings) {
              return true;
          }
          return super.onOptionsItemSelected(item);
      }
  }
  </code></pre>