0

So far I can get to sort the listview thing by its String ArrayAdapter. But now as I want to progress, I want to be able to sort the listview by its CustomAdapter.

Here's what I've tried so far:

MainActivity

    String[] text, price;
ArrayList<String> priceList;

private DBHelper dbHelper;
SimpleCursorAdapter dataAdapter;
Cursor cursor;

MyCustomAdapter adapter;

Button back, filter;
TextView highest, lowest, location;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.viewhouseandland);

    initControls();

    displayRecords();
}

private void displayRecords() {
    // TODO displayRecords
    // TODO CheckDBConnection
    checkDatabaseConnection();

    text = dbHelper.getAll();
    price = dbHelper.getAllPrices();

    adapter = new MyCustomAdapter(imgs, text, price);

    lv.setAdapter(adapter);

}

    @SuppressLint("InlinedApi")
private void displayDialog() {
    // TODO displayDialog
    final ArrayAdapter<String> adp = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, sortBy);

    LayoutInflater li = LayoutInflater.from(this);
    View promptsView = li.inflate(R.layout.dialog_layout, null);

    promptsView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));

    final Spinner mSpinner= (Spinner) promptsView
            .findViewById(R.id.spDialog);

    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setTitle("Sort By...");
    builder.setIcon(R.drawable.launcher);

    mSpinner.setAdapter(adp);
    mSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

    public void onItemSelected(AdapterView<?> parent, View v,
            int pos, long id) {
        strSpinner = mSpinner.getSelectedItem().toString();

        if(strSpinner.equals("Highest Price")){
            highest.setTypeface(Typeface.DEFAULT_BOLD);
            lowest.setTypeface(Typeface.DEFAULT);
            location.setTypeface(Typeface.DEFAULT);
            price = dbHelper.sortHighestPrice();

            adapter = new MyCustomAdapter(imgs, text, price);
            lv.setAdapter(adapter);
            adapter.notifyDataSetChanged();

        } else if (strSpinner.equals("Lowest Price")){
            highest.setTypeface(Typeface.DEFAULT);
            lowest.setTypeface(Typeface.DEFAULT_BOLD);
            location.setTypeface(Typeface.DEFAULT); 
            price = dbHelper.sortLowestPrice();

            adapter = new MyCustomAdapter(imgs, text, price);
            lv.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        } else if (strSpinner.equals("Location")) {
            highest.setTypeface(Typeface.DEFAULT);
            lowest.setTypeface(Typeface.DEFAULT);
            location.setTypeface(Typeface.DEFAULT_BOLD);
        } else {
            Log.d("Default", "Default");
        }
    }

    public void onNothingSelected(AdapterView<?> arg0) {

    }
    });

    builder.setPositiveButton("Okay",
            new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
        }
    });
    builder.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
        }
    });

    builder.setView(promptsView);
    AlertDialog alert = builder.create();
    alert.show();

    //((Button)alert.findViewById(android.R.id.button1)).setBackgroundResource(R.drawable.custom_button);
    //((Button)alert.findViewById(android.R.id.button2)).setBackgroundResource(R.drawable.custom_button);
} 

     class MyCustomAdapter extends BaseAdapter
{
    String[] data_text1;
    String[] data_text2;
    int[] data_image;

MyCustomAdapter() {
    data_text1 = null;
    data_text2 = null;
    data_image = null;
}

MyCustomAdapter(int[] image, String[] house, String[] price) {
    data_text1 = house;
    data_text2 = price;
    data_image = image;
}

public int getCount() {
    return data_text1.length;
}

public String getItem(int position) {
    return null;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {

    LayoutInflater inflater = getLayoutInflater();
    View row;

    row = inflater.inflate(R.layout.listrow, null);

    TextView textview1 = (TextView) row.findViewById(R.id.text1);
    TextView textview2 = (TextView) row.findViewById(R.id.text2);
    ImageView imageview = (ImageView) row.findViewById(R.id.image);

    imageview.setScaleType(ImageView.ScaleType.FIT_XY);
    textview1.setText(data_text1[position]);
    textview2.setText(data_text2[position]);
    imageview.setImageResource(data_image[position]);

    return (row);

    }
} 

DBHelper

    public String[] getAll(){
            Cursor localCursor =  
                   this.myDataBase.query(DB_TABLE, new String[] { 
                       KEY_ID, KEY_HOUSE, KEY_PRICE }, null, null, null, null, null);
            String[] array = new String[localCursor.getCount()];
            int i = 0;
            while(localCursor.moveToNext()){
                String uname = localCursor.getString(localCursor.getColumnIndex(DBHelper.KEY_HOUSE));
                array[i] = uname;
                i++;
            }
            return array;
        }

        public String[] getAllPrices(){
            Cursor localCursor =  
                   this.myDataBase.query(DB_TABLE, new String[] { 
                       KEY_ID, KEY_HOUSE, KEY_PRICE }, null, null, null, null, null);
            String[] array = new String[localCursor.getCount()];
            int i = 0;
            while(localCursor.moveToNext()){
                String uname = localCursor.getString(localCursor.getColumnIndex(DBHelper.KEY_PRICE));
                array[i] = uname;
                i++;
            }
            return array;
        }

        public String[] sortHighestPrice(){
            Cursor localCursor =  
                   this.myDataBase.query(DB_TABLE, new String[] { 
                       KEY_ID, KEY_HOUSE, KEY_PRICE }, 
                       null, null, null, null, 
                      KEY_PRICE + " DESC");
            String[] array = new String[localCursor.getCount()];
            int i = 0;
            while(localCursor.moveToNext()){
                String uname = localCursor.getString(localCursor.getColumnIndex(DBHelper.KEY_PRICE));
                array[i] = uname;
                i++;
            }
            return array;
        }

        public String[] sortLowestPrice(){
            Cursor localCursor =  
                   this.myDataBase.query(DB_TABLE, new String[] { 
                       KEY_ID, KEY_HOUSE, KEY_PRICE }, 
                       null, null, null, null, 
                      KEY_PRICE + " ASC");
            String[] array = new String[localCursor.getCount()];
            int i = 0;
            while(localCursor.moveToNext()){
                String uname = localCursor.getString(localCursor.getColumnIndex(DBHelper.KEY_PRICE));
                array[i] = uname;
                i++;
            }
            return array;
        }

Basically, what my app does :

  • it displays list of data (Image, Title and caption)
  • when the user clicks the filter button to choose from highest price to lowest price and location, the app should respond by sorting according to user choice (sort by highest, lowest or by location)...

So these data come from a local db(sqlite)

I don't have error so far, but it's just that the list is not updating/sorting. What am I missing here in my code? Any ideas? I really need help. Thanks.

UPDATE: I get it to work, but the problem now is the price is a string, when I sorted by highest, it's giving the 900, instead of 1000. How can I handle this?

Jeffrey Klardie
  • 3,020
  • 1
  • 18
  • 23
Dunkey
  • 1,900
  • 11
  • 42
  • 72
  • Is the data that you get from `sortHighestPrice()` and `sortLowestPrice()` sorted correctly? **Edit**: seems the query is correct, so the problem is probably that the list does not update. – Jeffrey Klardie Oct 30 '13 at 10:24
  • @JeffreyKlardie I've updated my code, please have a look at my update note. – Dunkey Oct 30 '13 at 10:32
  • I'd advice to make price a numeric field, e.g. an Integer and store cents. Then retrieve that, which makes sorting easier. Another solution is to sort the string as an integer: `CAST(value AS INTEGER) DESK`, where value is the name of the column. – Jeffrey Klardie Oct 30 '13 at 10:45
  • Yes I changed it to Numeric – Dunkey Oct 30 '13 at 10:48
  • please let us know how you fixed the initial problem, and if the answer fixed it, accept it please. It's a bit unclear now how you solved it. If you fixed it in another way, add your own answer and accept that one. – Jeffrey Klardie Oct 30 '13 at 11:01
  • 1
    @JeffreyKlardie thanks I accepted the answer below. – Dunkey Oct 30 '13 at 11:04

1 Answers1

1

This answer gives a great overview:

Two options: either hold onto the reference for the ArrayList that you passed into the constructor so you can modify the actual list data later (since the list isn't copied, modifying the data outside the Adapter still updates the pointer the Adapter is referencing), or rewrite the Adapter to allow the list to be reset to another object.

In either case, after the ArrayList has changed, you must call notifyDataSetChanged() to update your ListView with the changes. This can be done inside or outside the adapter.

Cleanest way in my opinion is to create a method like updateData() inside MyCustonAdapter:

public void updateData(int[] image, String[] house, String[] price) {
    data_text1 = house;
    data_text2 = price;
    data_image = image;
    notifyDataSetChangeD();
}
Community
  • 1
  • 1
Jeffrey Klardie
  • 3,020
  • 1
  • 18
  • 23