I have an ArrayList of an object which has properties Object.name and Object.url.
I want to loop through the ArrayList and apply the Object's "name" to an android ListView. I also want to keep the Object's other properties in tact, so that i can call the "url" property in the onClick method.
What i have now is this:
main_list.setAdapter(new ArrayAdapter<RomDataSet>(this, android.R.layout.simple_list_item_1, android.R.id.text1, mRoms));
But clearly that is not what I need...
Any help would be appreciated :)
1.) You have your ArrayList:
main_list
2.) Create a ListView in your XML file (say, main.xml) and grab its id. That is, given:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/liveFeed"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
Do something like this:
ListView livefeed = (ListView)this.findViewById(R.id.liveFeed);
within your activity (if you're in somewhere else such as an OnClickListener, replace the "this" with the View variable that was passed as a variable into the OnClickListener).
3.) Define your ArrayAdapter. Note that one of its parameters (the third one in your case) will be a TextView id. This is because the ArrayAdapter class, by default, returns a TextView in the ListView. If you override the ArrayAdapter class, you can use custom layouts to have items with custom Views within your ListView, but this is not necessary for what you've outlined in your question, and it seems like you've got it already.
4.) Set the adapter to the ListView (given an ArrayAdapter named 'aa'):
livefeed.setAdapter(aa);
Now the way the ArrayAdapter works is it invokes each Object's toString() method and sets each TextView in the ListView to this String. So make a toString() method in your Object's class that returns its name property:
public String toString(){return name;} //assuming name is a String
Also note that, if you add Objects to the ArrayList, notify the ArrayAdapter that you have so it can accordingly update your ListView with the modifications (given an ArrayAdapter named 'aa'):
aa.notifyDataSetChanged();
Let me know if you need any more help. As always, check the answer check mark if this answered your question.
Also note that, at one point you may wish to cross reference your ArrayAdapter and ArrayList between your activity and Object class. It's very helpful to make these fields static in order to do so.
EDIT:
You wanted to also know how to access a specific Object when you click on an item in the ListView. Here it is (given your ListView is named livefeed):
livefeed.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
//in here you may access your Object by using livefeed.getItemAtPosition(position)
//for example:
Object current = livefeed.getItemAtPosition(position);
//do whatever with the Object's data
}
});
Related
I need to change just first row in my ListView. I used such way:
private void updateAdapter(int number) {
String value = Integer.toString(number);
list_.clear();
list_.add(value);
adapter_.notifyDataSetChanged();
}
But, does anybody know another way, like myAdapter.update(newValue)? I use simple adapter
private ArrayAdapter<String> adapter_;
and ListView
<ListView
android:id="#+id/list_view"
android:paddingBottom="150dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
Basically, if your add or remove elements from your data source (which I assume is list_ here) and you call notifyDataSetChanged(), the ListView will get recalculated in the designated way based on your (changed) data source.
Therefore it wouldn't make sense to directly update your adapter (with the proposed function adapter.update()).
If you're worried about performance (which I think is your motivation here when only changing the first row) check Using an ArrayAdapter with ListView to see how the population of a ListView works.
Get the element by using getItem (int position) from the SimpleAdapter class. No you can change the object inside the adapter.
After change value call...
listAdapter.notifyDataSetChanged();
... to refresh your UI.
See doc: SimpleAdapter - getItem(int pos)
I use a CheckBox in my Activity, which is defined in "main.xml" (cbSetAll).
I also have a BaseAdapter, using "item.xml", for setting customized ListItems in a ListView in "main.xml".
Now i want to check all CheckBoxes, depending on cbSetAll. When I fetch the value of cbSetAll, the app crashes. I do this by
boolean bCheckAll = ((CheckBox) view.findViewById(R.id.cbSetAll)).isChecked();
to set the CheckBoxes in BaseAdapter by
((CheckBox)view.findViewById(R.id.cbSetItem)).setChecked(bCheckAll);
If I define
boolean bCheckAll = true;
everything works. I think, the error is, that the CB is in "main.xml" instead of "item.xml" and so the "view" is scoping in the Nirvana. Can someone give a hint?
One way to solve it is to create an additional variable in your custom adapter and set this variable from the parent activity. This way you can control the behaviour in the adapter.
You can add this variable to the constructor of the adapter.
You spotted the problem, you can't access views outside a row from inside. A quick way to do this, would be defining bCheckAll as an instance static variable of your Activity.-
static boolean bCheckAll;
In onCreate method, add a listener to cbSetAll CheckBox so that you can update bCheckAll value, and access it from you adapter's getView method.
I have a ListView where I want each item to have an ID number attached to it (not the same as the position number). I was hoping this could be done by setting a tag to each View item in the ListView using setTag() when these Views are being created.
Right now I'm creating the ListView like this:
final ListView listview = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, names);
listview.setAdapter(adapter);
The names variable in the ArrayAdapter parameters above is an ArrayList, and each string value in this list also has a unique ID that I want to link to this string somehow.
Is there any way I can get access to and modify each of the Views with a tag? One idea was to create my own extended class of ArrayAdapter and override the getView() method, but I don't really understand how it works and how I would go about doing this.
Or is there a better way to link IDs with each string like this than adding tags like I'm trying to do?
Create a ViewBinder and set the tags as the ListView is being populated with whatever you need. You can check all properties of the view to determine what tag goes where, so this should be what you're looking for.
myAdapter.setViewBinder(new MyViewBinder());
public class MyViewBinder implements ViewBinder {
#Override
public boolean setViewValue(View view, Object data, String text){
//Since it iterates through all the views of the item, change accordingly
if(view instanceof TextView){
((TextView)view).setTag("whatever you want");
}
}
}
I just used this exact same answer on another question (albeit slightly different) yesterday.
about getView , it works by using a method of recycling views. i will try to explain it in a simple way.
suppose you have tons of items that can be viewed . you don't want to really create tons of views too , since that would take a lot of memory . google thought of it and provide you the means to update only the views that need to be shown at any specific time.
so , if there is an empty space on the listview , it will be filled with a new view . if the user scrolls , the view that becomes hidden is recycled and given back to you on the getView , to be updated with the data of the one that is shown instead .
for example , if you scroll down , the upper view becomes hidden for the end user , but in fact it becomes the exact same view that is on the bottom .
in order to understand how to make the listview have the best performance and see in practice how and why it works as i've talked about , watch this video:
http://www.youtube.com/watch?v=wDBM6wVEO70
as for tags , i think you want to do something else , since the data itself (usually some sort of collection, like an arrayList) already knows where to update , because you get the position via the getView . if you want a specific view to update , you might be able to do so by using a hashmap that keeps upadting , which its key is the position in the collection , and the value is the associated view . on each time you go to getView , you need to remove the entry that belong to the view (if exists) and assign the new position with the view that you got/created .
Thanks for the answers. thisMayhem's answer would probably have been easier in the end, but on my quest to learn more I ended up making my own adapter according to this tutorial. I pass down the names and the IDs into the adapter and set the names as the text of the TextViews and the IDs as the tags.
I would rather go with the solution discussed in this thread. It is always the easiest to have all related data in same place and in this case you just create a class to hold all the information you will need for every item.
I have seen related answers and I do not know ehich one is the appropriate for me.
I have a listView and each row has a textview. I want given some conditions, each row to get different color.(Imagine that I am getting data from a DB, and given the value I get, i want text set to different color) My code is shown below:
public class TrailsConditionScreen extends ListActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
seeTrails();
}
private void seeTrails() {
String[] help=new String[] {"foo","bar"};
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,R.layout.row,R.id.text1,help);
setListAdapter(adapter);
}
}
This code so far just prints them on the list.
Now I want when retrieving values from the db, given the value i get set a different color on each row. imagine that my codes retrieves data from a table an I want when reading the first line , given the number set the appropriate color on the first line of the listview. Then go to second lone of the db,set color for the second line of the list and so on.. i have successfully implemented the reading from the db but i do not know how to set color on specific row. In pseudo-code it looks like this.
for i=0 to number of lines in db{
read_data();
if key_value=0 then color_of_line(i)=red;
else color_of_line_i)=green;
}
Any help for this?
You must create a custom adapter to handle this instead of using the ArrayAdapter. Extend the ArrayAdapter and override the getView method. And inside the getView method based on the condition you can change the color of the text on your textView.setTextColor.
To write a custom adapter check the tutorial here (6. Tutorial: Implementing your own adapter). This example doesn't use the holder pattern but you should.
Your best bet is to extend ArrayAdapter and create your own class.
In the getView() method, execute your condition and set the color to be drawn. There are a lot of good tutorials on creating your own adapters. Check, for instance, http://www.ezzylearning.com/tutorial.aspx?tid=1763429&q=customizing-android-listview-items-with-custom-arrayadapter.
Hope it helps!
Inorder to achieve this, you will need to use a custom adapter. Since you mentioned, you are getting the data from a database, I am assuming here that you will have information in a cursor adapter. Hence, a good place to start would be to extend cursor adapter.
Within your new custom adapter, you should override getView() method. The view to be used for each item in list view is specified there. Additionally, you can also set the properties of the view there.
Depending on your business logic, you should set the text color in getView.
A tutorial here:
http://www.ezzylearning.com/tutorial.aspx?tid=1763429&q=customizing-android-listview-items-with-custom-arrayadapter
What I would do is create a CustomAdapter for the list view
public class MyCustomAdapter extends BaseAdapter
and in the funcion
public View getView(int position, View convertView, ViewGroup parent)
you have the position and you can change whatever you want.
If you search google by custom adapter listview you will get some examples
Different Color For different list item ,yes this can be achieved only if items are static only , but for dynamic content it's hard to do ...
I want to be able to show an alternative to an empty list, currently the following method call sets up the list, however taskArrayList could be empty if the call to the database has returned an empty list
/**
* Setup list adapter.
*/
private void setupListAdapter() {
setListAdapter(new TaskAdapter(this, R.id.tasks_list_view,
taskArrayList));
taskListView = getListView();
taskListView.setOnItemClickListener(new TaskClickListener());
}
I'm thinking that before I call this method, or at the beginning of the method adding the following check
if(taskArrayList.isEmpty()) {
/*load an alternative view*/
}
however because my Activity is a ListActivity so it requires a ListView to be set against it, so I'm unsure of the best approach to handling the case when the list is empty.
I don't want to create a "dummy item" which says there are no items and add it to the ArrayList but I'm not sure of the alternatives.
If you add something with the idea #android:id/empty
it will be shown instead of the list when it is empty automagically!
<TextView android:id="#android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"
android:text="No data"/>
In the documentation they say it like this:
Optionally, your custom view can contain another view object of any type to display when the list view is empty. This "empty list" notifier must have an id "android:id/empty". Note that when an empty view is present, the list view will be hidden when there is no data to display.
http://developer.android.com/reference/android/app/ListActivity.html