如何在列表视图中按价格对项目进行排序?

时间:2014-03-19 08:07:58

标签: android sorting android-listview

如果用户在微调器中选择它,我想根据价格对我的项目进行排序。我该如何实现它?下面的代码就是我所做的。我对onitem选择的用法是否正确?我必须实现OnItemSelectedListener吗?

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());
}

}

1 个答案:

答案 0 :(得分: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);
    }
}