title: How to sort item by price in listview?
body: <p>I would like to sort my item based on price if the user selects it in a spinner. How do I implement it? The code below is what I had done. Is my usage for onitemselected correct? Must i implements OnItemSelectedListener?</p>
  
  <pre><code>public class SearchResults extends ListActivity {
  
  // Progress Dialog
  private ProgressDialog pDialog;
  
  // Creating JSON Parser object
  JSONParser jParser = new JSONParser();
  JSONObject json;
  
  ArrayList&lt;Products&gt; productsList = new ArrayList&lt;Products&gt;();
  
  // url to get all products list
  // private static String url_all_products =
  // "http://10.0.2.2:8000/project/display_items.php";
  // private static String url_all_products =
  // "http://inticlassifields.comze.com/phpscripts/display_items.php";
  
  // JSON Node names
  private static final String TAG_SUCCESS = "success";
  private static final String TAG_PRODUCTS = "product";
  private static final String TAG_PID = "pid";
  private static final String TAG_NAME = "name";
  private static final String TAG_BUDGET = "price";
  private static final String TAG_DES = "description";
  private static final String TAG_DATE_POSTED = "created_at";
  private static final String TAG_CATEGORY = "category";
  private static final String TAG_EMAIL = "email";
  private static final String TAG_CONTACT = "contact";
  
  // products JSONArray
  JSONArray products = null;
  
  Spinner spinTop;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_search_results);
      String[] spinnerText = { "Sort by date posted (newest first)",
              "Sort by price (lowest to highest)" };
      LayoutInflater inflater = LayoutInflater.from(this);
      spinTop = (Spinner) inflater.inflate(R.layout.spin, null);
      getListView().addHeaderView(spinTop);
      ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;String&gt;(this,
              android.R.layout.simple_spinner_item, spinnerText);
      adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
      spinTop.setAdapter(adapter);
  
      // Hashmap for ListView
      productsList = new ArrayList&lt;Products&gt;();
  
      // Loading products in Background Thread
      new LoadAllProducts().execute();
  
      // Get listview
      ListView lv = getListView();
  
      // on seleting single product
      // launching Edit Product Screen
      lv.setOnItemClickListener(new OnItemClickListener() {
  
          @Override
          public void onItemClick(AdapterView&lt;?&gt; parent, View view,
                  int position, long id) {
              // getting values from selected ListItem
              String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                      .toString();
              String name = ((TextView) view.findViewById(R.id.name))
                      .getText().toString();
              String description = ((TextView) view.findViewById(R.id.des))
                      .getText().toString();
              String price = ((TextView) view.findViewById(R.id.budget))
                      .getText().toString();
              String date = ((TextView) view.findViewById(R.id.date_posted))
                      .getText().toString();
              String category = ((TextView) view.findViewById(R.id.category))
                      .getText().toString();
              String email = ((TextView) view
                      .findViewById(R.id.email_request)).getText().toString();
              String contact = ((TextView) view
                      .findViewById(R.id.contact_request)).getText()
                      .toString();
  
              // Starting new intent
              Intent in = new Intent(getApplicationContext(),
                      DisplayItemInfo.class);
              // sending information to next activity
              in.putExtra(TAG_PID, pid);
              in.putExtra(TAG_NAME, name);
              in.putExtra(TAG_DES, description);
              in.putExtra(TAG_BUDGET, price);
              in.putExtra(TAG_DATE_POSTED, date);
              in.putExtra(TAG_CATEGORY, category);
              in.putExtra(TAG_EMAIL, email);
              in.putExtra(TAG_CONTACT, contact);
              startActivity(in);
          }
      });
  
      spinTop.setOnItemSelectedListener(new OnItemSelectedListener() {
          public void onItemSelected(AdapterView&lt;?&gt; parent, View view,
                  int pos, long id) {
              String strSpinner = spinTop.getSelectedItem().toString();
              if (strSpinner.equals("Sort by price (lowest to highest)")) {
                  Collections.sort(productsList, new PriceSort());
              }
              adapter.notifyDataSetChanged();
          }
  
          @Override
          public void onNothingSelected(AdapterView&lt;?&gt; arg0) {
              // TODO Auto-generated method stub
  
          }
      });
  }
  
  /**
   * Background Async Task to Load all product by making HTTP Request
   * */
  class LoadAllProducts extends AsyncTask&lt;String, String, String&gt; {
  
      /**
       * Before starting background thread Show Progress Dialog
       * */
      @Override
      protected void onPreExecute() {
          super.onPreExecute();
          pDialog = new ProgressDialog(SearchResults.this);
          pDialog.setMessage("Loading products. Please wait...");
          pDialog.setIndeterminate(false);
          pDialog.setCancelable(false);
          pDialog.show();
      }
  
      /**
       * getting All products from url
       * */
      protected String doInBackground(String... args) {
          // List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;();
          Intent intent = getIntent();
          // getting attached intent data
          String jsonS = intent.getStringExtra("JSon");
  
          if (jsonS == null) {
              // getting JSON string from URL
              /*
               * json = jParser.makeHttpRequest(url_all_products, "GET",
               * params);
               */
          } else {
              try {
                  JSONObject Jsonobj = new JSONObject(jsonS);
                  json = Jsonobj;
              } catch (JSONException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
          }
  
          // Check your log cat for JSON reponse
          Log.d("All Products: ", json.toString());
  
          try {
              // Checking for SUCCESS TAG
              int success = json.getInt(TAG_SUCCESS);
  
              if (success == 1) {
                  // products found
                  // Getting Array of Products
                  products = json.getJSONArray(TAG_PRODUCTS);
  
                  // looping through All Products
                  for (int i = products.length() - 1; i != -1; i--) {
                      JSONObject c = products.getJSONObject(i);
  
                      // Storing each json item in variable
                      String id = c.getString(TAG_PID);
                      String name = c.getString(TAG_NAME);
                      String budget = c.getString(TAG_BUDGET);
                      String description = c.getString(TAG_DES);
                      String category = c.getString(TAG_CATEGORY);
                      String contact = c.getString(TAG_CONTACT);
                      String email = c.getString(TAG_EMAIL);
                      String dateS = c.getString(TAG_DATE_POSTED);
                      SimpleDateFormat formatter = new SimpleDateFormat(
                              "yyyy-mm-dd", java.util.Locale.getDefault());
                      Date dateD = null;
                      try {
                          dateD = formatter.parse(dateS);
                      } catch (ParseException e) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                      } catch (java.text.ParseException e) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                      }
                      SimpleDateFormat formatter2 = new SimpleDateFormat(
                              "dd-mm-yyyy", java.util.Locale.getDefault());
                      String date = formatter2.format(dateD);
  
                      // Create a new Product Object, set its Values
                      Products mProduct = new Products();
                      mProduct.pid = id;
                      mProduct.name = name;
                      mProduct.price = budget;
                      mProduct.description = description;
                      mProduct.date = date;
                      mProduct.category = category;
                      mProduct.email = email;
                      mProduct.contact = contact;
  
                      // adding Product to ArrayList
                      productsList.add(mProduct);
                  }
              } else {
                  // no products found
                  Intent i = new Intent(getApplicationContext(),
                          MainMenu.class);
                  // Closing all previous activities
                  i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                  startActivity(i);
              }
          } catch (JSONException e) {
              e.printStackTrace();
          }
  
          return null;
      }
  
      /**
       * After completing background task Dismiss the progress dialog
       * **/
  
      protected void onPostExecute(String file_url) {
          // dismiss the dialog after getting all products
          pDialog.dismiss();
  
          if (productsList.size() &gt; 0) {
              /**
               * Updating parsed JSON data into ListView
               * */
              CustomAdapter adapter = new CustomAdapter(getBaseContext(),
                      productsList);// ,
  
              if (getListView() != null) {
  
                  // updating listview
                  setListAdapter(adapter);
              } else {
                  Log.d("ListView-Reference", "ListView is null");
              }
          } else {
              Log.d("Product List", "Products list is empty");
          }
      }
  }
  }
  </code></pre>
  
  <p>PriceSort:</p>
  
  <pre><code>public class PriceSort implements Comparator&lt;Products&gt; {
  public int compare(Products a, Products b) {
      return a.getPrice().compareTo(b.getPrice());
  }
  
  }
  </code></pre>