2014-03-19 37 views
0

如果用戶在微調器中選擇它,我想根據價格對商品進行排序。我如何實現它?下面的代碼就是我所做的。我的用法是否正確?我必須實現OnItemSelectedListener嗎?如何在listview中按價格排序項目?

public class SearchResults extends ListActivity { 

// Progress Dialog 
private ProgressDialog pDialog; 

// Creating JSON Parser object 
JSONParser jParser = new JSONParser(); 
JSONObject json; 

ArrayList<Products> productsList = new ArrayList<Products>(); 

// 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<String> adapter = new ArrayAdapter<String>(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<Products>(); 

    // 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<?> 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<?> 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<?> arg0) { 
      // TODO Auto-generated method stub 

     } 
    }); 
} 

/** 
* Background Async Task to Load all product by making HTTP Request 
* */ 
class LoadAllProducts extends AsyncTask<String, String, String> { 

    /** 
    * 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<NameValuePair> params = new ArrayList<NameValuePair>(); 
     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() > 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"); 
     } 
    } 
} 
} 

PriceSort:

public class PriceSort implements Comparator<Products> { 
public int compare(Products a, Products b) { 
    return a.getPrice().compareTo(b.getPrice()); 
} 

} 

回答

0

創建Comparator和呼叫Collections.sort(productsList, yourComparator)一旦用戶選擇排序類型。並撥打notifyDataSetChanged()作爲適配器。

這裏可能比較

public class MyComparator implements Comparator<Product> 
{ 
    public int compare(Product p1, Product p2) 
    { 
     return c1.price.compareTo(c2.price); 
    } 
} 
+0

有任何教程? – Benz

+0

究竟是爲了什麼? http://stackoverflow.com/questions/19676781/android-sort-listview-alphabetically - 在這裏我發現類似的問題給你。 – Heisenberg

+0

我編輯了上面的問題以包含產品,並在我的onItemSelected中實現了Collections.sort,但是我有錯誤.sort說類型集合中的方法排序(列表,Comparator )不適用於參數ArrayList ,Products) – Benz