I've looked up a few tutorials online but decided the following was the best approach.
My Activity only consists of a text field (editText) and a list view (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 the other 2 override methods are omitted for convenience here.
The filterList() method returns the filtered array (this, I believe is working fine but I will paste the code if asked for)
And finally the OnClick code 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 2 global variables are assigned specific values to the clicked cells.
PROBLEM
Editing the text field makes no difference whatsoever, and clicking on a cell crashes my program?
I've looked over my code countless times and cannot locate any mistakes.
Thanks for any help in advance.
You need to call:
rla = new RoomListAdapter(RoomsActivity.this, finalcells);
listview2.setAdapter(rla);
before calling:
rla.notifyDataSetChanged();
inside your onTextChanged method as it will have new filtered objects each time you type into your EditText
Related
I have a question:
I have a listview (from custom adapter) with a searchbar on top of it. Everything works ok, the only thing I need is when opening the activity to keep the listview hidden, or invisible, until the search has started in the searchbar (in other words, to keep the listview hidden until I start typing something in the searchbar).
You can find the code here:
How to start new intent after search-filtering listview?
Plus a suggested solution, which unfortunately did not work, you can see here:
Android search list invisible by default? Can it be done?
I am looking forward to your replies guys and I thank you in advance.
Try adding TextWatcher to your search EditText. This will detect when you type something in your search:
EditText search= (EditText) findViewById(R.id.search);
search.addTextChangedListener(filterTextWatcher);
TextWatcher method:
private TextWatcher filterTextWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
//Change the visibility here
list.setVisibility(View.VISIBLE);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
};
I think you may be thinking about an AutoCompleteTextView? It requires that you load the list data into its adapter then set the adapter.
// Get a reference to the AutoCompleteTextView in the layout
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);
// Get the string array
String[] countries = getResources().getStringArray(R.array.countries_array);
// Create the adapter and set it to the AutoCompleteTextView
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countries);
textView.setAdapter(adapter);
Google's Guide: here.
I have a Activity that's creating a Check list, if I close the activity with back Button the list is saved in a Database.
The list from the Database is used as the MainActivity content.
This is how my app will look:
If I press the List Item button, a new element should be added to the list. How can I add and sisplay a new Item (Layout with Checkbox and EditText)?
Do I need an Adapter? I don't want the 'list item' part repeated.
That looks so after i press 4 times
Activity
private ArrayAdapter mAdapter;
onCreate
ListView lv = (ListView) findViewById(R.id.my_list);
List<String> initialList = new ArrayList<String>(); //load these
mAdapter = new ArrayAdapter(this, android.R.id.text1, initialList)
lv.setadapter(mAdapter);
When the event happens
mAdapter.add(newString);
The add method in ArrayAdpater will automatically take care of the notifyDataSetChanged() call for you and update the display.
TextWatcher you might not need this part, it's if you want the text added as soon as the text is changed which your question seems to indicate - that is risky because you might get partial entries, so i recommend a done button instead, in which case you just do the afterTextChanged stuff in the onClick method.
EditText editText = (EditText) findViewById(R.id.my_edit_text);
editText .addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable arg0) {
//TODO: check it isnt emtpy
String text = arg0.getText().toString();
mAdapter.add(text);
//Hide the add item views again
arg0.setText("");
arg0.setVisibility(View.GONE);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) { /*nothing*/ }
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) { /*nothing*/ }
});
You can add plus button in your list as footerview as your image then new item add in your arraylist by the action(onClicklistener) of footer view button then call youradapter.notifyDataSetChanged().
I do have a list of possibly several thousands items (just testing with shorter list with about 200 items). The information is stored in SQLite, the ContentProvider, loader and SimpleCursorAdapter is used. The list is sorted lexicographically, and the android:fastScrollEnabled is used. The list scrolls smoothly -- no problem when one knows the exact name of the item.
Occasionally, I would like to find the items that contain some substring somewhere in the middle of their name. The `... LIKE "%wanted%" is a solution for me. However, I would like to give the user an incremental filtering -- i.e. the list content be updated during typing the substring. The reasoning is that it may not be neccessary to type many characters, and one should find the item as soon as possible. The goal is not to find one or none item. The goal is to filter the list so that manual scrolling be acceptable to overview the candidate items and select one of them by touch.
I have met the SearchView widget that looks nicely at the action bar. Anyway, reading something more about it in the doc, I am not sure if it is the right tool for me. Or if the recommended implementation is the one for me. (I am an android beginner, I am even not sure if I understand it well.)
Is it possible to use the widget for incremental filtering of the list in the same activity that has the SearchView in the Action Bar? Can you point me to some code that possibly shows how to implement the wanted behaviour?
Sample code to try out :
public class AndroidListViewFilterActivity extends Activity {
ArrayAdapter<String> dataAdapter = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Generate list View from ArrayList
displayListView();
}
private void displayListView() {
//Array list of countries
List<String> countryList = new ArrayList<String>();
countryList.add("Aruba");
countryList.add("Anguilla");
countryList.add("Netherlands Antilles");
countryList.add("Antigua and Barbuda");
countryList.add("Bahamas");
countryList.add("Belize");
countryList.add("Bermuda");
countryList.add("Barbados");
countryList.add("Canada");
countryList.add("Costa Rica");
countryList.add("Cuba");
countryList.add("Cayman Islands");
countryList.add("Dominica");
countryList.add("Dominican Republic");
countryList.add("Guadeloupe");
countryList.add("Grenada");
//create an ArrayAdaptar from the String Array
dataAdapter = new ArrayAdapter<String>(this,R.layout.country_list, countryList);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
//enables filtering for the contents of the given ListView
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
}
}
I need to display a list of text items to the screen and make them clickable. So it would be something like a list of links on a web application.
How can I do that in an Android Activity screen?
It would be some random number of items that I have to pull from a db and display all as links.
Any idea how that can be done?
You should read the doc about ListActivity, ListView and follow the Hello ListView tutorial.
Yes you can do it. Create a DataExchange class to fetch it from Db..
Store the Strings in an Array.
Create a ArrayAdapter to display the array of Strings you got from the database.
for Example
public class AndroidListViewActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
String[] numbers = {"one","two","three","four"}
// here you store the array of string you got from the database
// Binding Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, numbers));
// refer the ArrayAdapter Document in developer.android.com
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String num = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
i.putExtra("number", num);
startActivity(i);
}
});
}
}
The secondActivity to display the Particular item you have clicked should be
public class SingleListItem extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_list_item_view);
TextView txtProduct = (TextView) findViewById(R.id.product_label);
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("number");
// displaying selected product name
txtProduct.setText(product);
}
}
you have to create various layout files accordingly..
Hope this helps you :)
You should use a ListView. It's very simple, just create a ListActivity, put your items inside an Adapter and then set it as the Adapter of your ListActivity.
You can read more about ListViews here
There is also a new paradigm called ListFragment.
I have used ListViews before but prefer the fragments approach now - it's just very straight forward and quite flexible esp on tablets since the interation with another area on the screen when selecting an item is quite flexible and only requires very little code.
Just one example:
public class Select_FoodCategories_Fragment extends android.app.ListFragment {
private static final boolean DEBUG = true;
#Override
public void onCreate(Bundle savedInstanceState) {
if (DEBUG)
Log.i(this.getClass().getSimpleName(), " ->"
+ Thread.currentThread().getStackTrace()[2].getMethodName());
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (DEBUG)
Log.i(this.getClass().getSimpleName(), " ->"
+ Thread.currentThread().getStackTrace()[2].getMethodName());
HoldingActivity a = (HoldingActivity) getActivity();
//accessing a variable of the activity is easy
a.visibleListViewInFragment = getListView();
List<XYZ> listTodisplay = a.getListToDisplay();
MyAdapter adapter = new MyAdapter(
getActivity(), 0, listTodisplay);
setListAdapter(adapter);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
if (DEBUG)
Log.i(this.getClass().getSimpleName(), " ->"
+ Thread.currentThread().getStackTrace()[2].getMethodName());
XYZ item = (XYZ) getListAdapter()
.getItem(position);
}
}
More info here: http://developer.android.com/reference/android/app/ListFragment.html
By the way, I find it really worth it to get familiar with the new fragments concept - it just makes live much easier - esp on tablets!
ps I left the debug statements in on purpose - since it helps alto to understand the whole concept much faster in my experience
I've tried to filter my ListView from my EditText box, but currently, it's not working.
I have a ListView that get data properly and they are added to my own ListView using a ArrayAdapter class and my own ArrayList class. When I for example, typing in "table" I want it to sort from the loaded titles in my ListView and than it should show me the items that are left and matching table.
My current code:
private ArrayList<Order> orders; /* ArrayList class with my own Order class to
define title, info etc. */
private OrderAdapter adapter; //Own class that extends ArrayAdapter
orders = new ArrayList<Order>();
adapter = new OrderAdapter(this, R.layout.listrow, orders); /* listrow defining a
single item in my ListView */
setListAdapter(adapter); //Set our adapter to a ListView
search.addTextChangedListener(filterTextWatcher); //search is my EditText
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s); //Filter from my adapter
adapter.notifyDataSetChanged(); //Update my view
}
};
Okay, so how can I achieve this? When I entering some value into the EditText box everything disappear, even if there is a match.
Thanks in advance and tell me if you need more code snippets or if this question i unclear!
The built-in filter implemented by ArrayAdapter converts the contained object to string by calling toString() method. It is this string that will be used to perform the matching. If you are only trying to match one string field in your Order object, you can override the toString() method for your Order class to return that field. If you want to perform more flexible matching, such as matching multiple fields, check out this post which shows how to create a custom filter:
Custom filtering in Android using ArrayAdapter