Dynamically displaying list of object objects on Android

I've searched for several tutorials on the internet, but figured the best one is the best way.

My activity only consists of textbox ( editText

) and list ( roomlv

)

  • CODE

The objects contained in the list are RoomCell

objects

My class has the following variables

public class RoomsActivity extends ActionBarActivity {

    ListView listview2;
    RoomCell[] roomcells = {rc1, rc2, rc3, rc4, rc5, rc6, rc7, rc8, rc9}; 
    //where rc1, rc2, ... are predefined objects
    RoomCell[] finalcells = roomcells;
    RoomListAdapter rla;

      

My onCreate method looks like this:

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

        listview2 = (ListView) findViewById(R.id.roomlv);
        listview2.setClickable(true);
        listview2.setOnItemClickListener(onListClick2);

        EditText filterText = (EditText) findViewById(R.id.editText);
        filterText.addTextChangedListener(filterTextWatcher);

        rla = new RoomListAdapter(this, finalcells);
        listview2.setAdapter(rla);

    }

      

where my TextWatcher works like this:

private TextWatcher filterTextWatcher = new TextWatcher() {

    public void onTextChanged(CharSequence s, int start, int before,
                              int count) {
        if(s.length()==0){

            finalcells = roomcells;
            rla.notifyDataSetChanged();

        }else{

            finalcells = filterList(roomcells, s);
            rla.notifyDataSetChanged();

        }
    }
};

      

where other override 2 methods are omitted for convenience here.

The method filterList()

returns a filtered array (this works fine, I believe, but I will paste in the code if asked)

And finally, the code OnClick

is here:

private AdapterView.OnItemClickListener onListClick2 = new AdapterView.OnItemClickListener(){

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        GlobVar.roomtitle = finalcells[position].name;
        GlobVar.roomsize = finalcells[position].size;

        Intent i = new Intent(RoomsActivity.this, TheRoomActivity.class);
        startActivity(i);
    }
};

      

where two global variables are assigned specific values ​​for the cells you clicked.

  • PROBLEM

Editing a textbox makes no difference and clicking on a cell is crashing my program?

I have looked at my code countless times and cannot find any errors.

Thanks for any help in advance.

+3


source to share


1 answer


You need to call:

rla = new RoomListAdapter(RoomsActivity.this, finalcells);
listview2.setAdapter(rla);

      

before the call:



rla.notifyDataSetChanged();

      

inside your method onTextChanged

as it will have new filtered objects every time you enter yourEditText

+3


source







All Articles