Example of custom setDropDownViewResource spinner item - java

I would like to display two values in an drop down view of my spinner.
Currently, it only has a city name, but I would also like to add a small distance field to it.
MyCity<MyCityDistance> dataAdapter;
dataAdapter = new MyCity(this, R.layout.mycityrow, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
I have all the code for custom data adapter, exapanding my view and holder etc.
However, the item which gets show doesn't display both the city and its distance from my current location.
It only shows what is overridden in toString() method of MyCityDistance class.
I even tried setting
dataAdapter.setDropDownViewResource(R.layout.mycityrow);
but, no success. It throws an error.
04-02 11:05:22.600: E/AndroidRuntime(367): java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
04-02 11:05:22.600: E/AndroidRuntime(367): at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:347)
04-02 11:05:22.600: E/AndroidRuntime(367): at android.widget.ArrayAdapter.getDropDownView(ArrayAdapter.java:376)
04-02 11:05:22.600: E/AndroidRuntime(367): at android.widget.Spinner$DropDownAdapter.getDropDownView(Spinner.java:332)
What is a good example of creating your own custom setDropDownViewResource()?
Even if I comment out the setDropDownViewResource() line, I get the same error.
Note: The only effect mycityrow current is that the first element of Spinner is show as per the layout of mycityrow. However, when I click open the drop down, that layout is lost. I want the same layout during drop down selection too.

Note the below example uses the inbuilt android.R.layout.simple_list_item_2, Unfortunately the text color will probably be the same as the background. You can simply solve this by creating your own custom view and use it in the adapter instead.
Let me know if i should explain any part of it.
public class MainActivity extends Activity {
class City {
public City(String city, int d) {
this.city = city;
this.distance = String.valueOf(d);
}
String city;
String distance;
}
class CityAdapter extends ArrayAdapter<City> {
public CityAdapter(Context context, List<City> objects) {
super(context, android.R.layout.simple_list_item_2, objects);
}
#Override //don't override if you don't want the default spinner to be a two line view
public View getView(int position, View convertView, ViewGroup parent) {
return initView(position, convertView);
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
return initView(position, convertView);
}
private View initView(int position, View convertView) {
if(convertView == null)
convertView = View.inflate(getContext(),
android.R.layout.simple_list_item_2,
null);
TextView tvText1 = (TextView)convertView.findViewById(android.R.id.text1);
TextView tvText2 = (TextView)convertView.findViewById(android.R.id.text2);
tvText1.setText(getItem(position).city);
tvText2.setText(getItem(position).distance);
return convertView;
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner)findViewById(R.id.spinner1);
List<City> list = new ArrayList<MainActivity.City>();
for(int i = 0; i < 10; i++)
list.add(new City(String.format("City %d", i + 1), (i + 1) * 1000));
spinner.setAdapter(new CityAdapter(this, list));
}
}

Try commenting the line dataAdapter.setDropDownViewResource() and the adapter will try to use the mycityow layout file for the drop down as well. Works in simple cases.

Related

Search listview but instead of filtering, just inflate and display the valid items

I have a arraylist of buttons (reserveButtons) that I can display in a listview. I have made a search function which searches in my database and outputs a list of integers (resultID). They correspond to the indexes of reserveButtons I want to display.
Simply put, I want to do something like this when the search button is clicked:
ArrayAdapter<ReserveButton> adapter = new MyListAdapter();
ListView list = (ListView) myView.findViewById(R.id.resultslist);
list.setAdapter(adapter);
for (int result : resultID) {
adapter.add(reserveButtons.get(result));
}
So, for each result, I want to add the corresponding button to the listview.
Here is the private class MylistAadapter :
private class MyListAdapter extends ArrayAdapter<ReserveButton> {
public MyListAdapter() {
super(getActivity(), R.layout.list_item, reserveButtons);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if(itemView == null) {
itemView = gettActivity().getLayoutInflater().inflate(R.layout.list_item, parent, false);
}
ReserveButton currentButton = reserveButtons.get(position);
//the resultItem is the id of the buttons
Button butt = (Button) itemView.findViewById(R.id.resultItem);
butt.setBackground(currentButton.getImage());
return itemView;
}
}
I know that getView will just display every reserveButton, but I want the code in getView to be executed when I add each button, but the position doesn't change since position = result in the for loop of the first code block.
//This code is inside MyListAdapter
#Override
public void add(ReserveButton object) {
/* What do I write here to inflate a list_item and give it
the background image reserveButton.get(result).getImage() */
super.add(object);
}
How do I override the add method of MyListAdapter so that I can add a reserveButton and change its background image for each result in the resultID list.
If the same thing can be accomplished without the add method, please do tell.
P.S: I do not want to just list every reserveButton and then filter them with the search; I want to display ONLY the buttons that the user is looking for.
I figured it out myself!
Basically, what I did was create a separate ArrayList of ReserveButtons and do the foreach loop like so:
int index = 0;
for (int result : resultID) {
//result is the single ID of an answer
answerButtons.add(index,reserveButtons.get(result));
index ++;
}
populateListView();
So I end up storing ONLY the buttons I want to display in the answerButtons list. And here is what happens in populateListView()
private void populateListView() {
ArrayAdapter<ReserveButton> adapter = new MyListAdapter();
ListView list = (ListView) myView.findViewById(R.id.resultslist);
list.setAdapter(adapter);
}
and the getView() method:
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if(itemView == null) {
itemView = getActivity().getLayoutInflater().inflate(R.layout.list_item, parent, false);
}
//Just set the image of the corresponding answerButton
ReserveButton currentButton = answerButtons.get(position);
Button butt = (Button) itemView.findViewById(R.id.resultItem);
butt.setBackground(currentButton.getImage());
return itemView;
}
Problem solved. I haven't seen any answers to a problem like this, so this post should make it easily google-able for any newcomer who stumbles upon this problem.

disable item in listview android java

Im trying disable some items in listview , but cant to do it.
I have Array of booleans
private boolean[] array; //10 items all false, and some of them true
in code im trying
for(int i=0;i<array.length();i++){
if(!array[i]){
listview.getChildAt(i).setEnabled(false);
}
}
but im always got nullpointerexception on string "listview.getChildAt()"
if write like
if(listview.getChildAt(i)!=null){ //do code here }
than i see what no entrance to string "getChildAt(i).setEnabled(false)"
im little not understand about getChildAt but i was thinking its way where i can get items by position. Any one can help me how to do it?
adapter for list view
public class LevelAdapter extends ArrayAdapter<String> {
public LevelAdapter(Activity context, ArrayList<String> le, ArrayList<Integer> co, boolean[] bools) {
super(context, R.layout.listviewitem, le);
this.context = context;
this.l = le;
this.s = co;
this.boolStates = bools;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.listviewitem, null, true);
tvL = (TextView) rowView.findViewById(R.id.l);
tvC = (TextView) rowView.findViewById(R.id.s);
tvL.setText(""+l.get(position));
tvCt.setText(""+s.get(position) + "/3");
return rowView;
}
}
regards , Peter.
SOLUTION
in adapter check
if(lvl[position]==false){
rowView= inflater.inflate(R.layout.listviewitemdisabled, null, true);
rowView.setEnabled(false);
}else
{
rowView= inflater.inflate(R.layout.listviewitem, null, true);
}
and when click on
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (view.isEnabled()) {
// do our code here
thanks for this easy solution
You can set enabled state in your adapter.
rowView.setEnabled(false)
Use Adapter approach.
Create an adapter and a viewHolder and in OnBind method just get that item of list and disable it.
send value to the adapter using method and notify the adapter about change.

Custom ListView - Custom Argument

I'm creating an app for a bus station, to give the schedule. For that i'm using a custom listview. Here it is:
class custom_adapter extends ArrayAdapter<String>{
public custom_adapter(Context context, ArrayList<String> horarios) {
super(context, R.layout.costum_listview ,horarios);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater horarioInflater = LayoutInflater.from(getContext());
View costumView = horarioInflater.inflate(R.layout.costum_listview, parent, false);
String singleHorario = getItem(position);
TextView hora = (TextView) costumView.findViewById(R.id.Hora);
TextView nota = (TextView) costumView.findViewById(R.id.Nota);
hora.setText(singleHorario);
nota.setText(" ");
return costumView;
}
}
Now as you can see I have just 2 texViews yet, the "hora" is to show the timers of the bus, the "nota" is for some notes, like someday the bus don't go or something like that. And my problem is exactly on that "nota" textview. I have dozens of arrayList's passing to this custom ListView, and so dozens and dozens of timers, and there are some timers that I need to put a note and other that I don't. So, can I had another argument to this custom ListView, like a boolean or something, so I can do a if / else in that code to put a note on each one. What do I need to change in order to do that ? I've been trying, but didn't quite managed to do that.
Instead of using a String as the argument for your ArrayAdapter, create a custom class and use that instead.
That way you can pass all the information you want into the adapter and show it however you like.
public class custom_adapter extends ArrayAdapter<MyClass>{
public custom_adapter(Context context, ArrayList<MyClass> horarios) {
super(context, R.layout.costum_listview ,horarios);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater horarioInflater = LayoutInflater.from(getContext());
View costumView = horarioInflater.inflate(R.layout.costum_listview, parent, false);
MyClass singleHorario = getItem(position);
TextView hora = (TextView) costumView.findViewById(R.id.Hora);
TextView nota = (TextView) costumView.findViewById(R.id.Nota);
hora.setText(singleHorario.hora);
nota.setText(singleHorario.nota);
return costumView;
}
And the new class
public class MyClass {
public String hora;
public String nota;
}
How about making a class for holding two values 'hora' and 'nota', and with, lets say, boolean isNotaAvailable() method. Then in getView() you just make something like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater horarioInflater = LayoutInflater.from(getContext());
View costumView = horarioInflater.inflate(R.layout.costum_listview, parent, false);
YourClassName singleHorario = getItem(position);
TextView hora = (TextView) costumView.findViewById(R.id.Hora);
TextView nota = (TextView) costumView.findViewById(R.id.Nota);
// set hora text
hora.setText(singleHorario);
// check if nota is available, if true - set nota text
if(singleHorario.isNotaAvailable()) {
nota.setText(singleHorario.getNota())}
else nota.setVisibility(View.GONE);
return costumView;
}
It's just an idea, tell me if it helps :)
Just extend BaseAdapter, so you can define the data structure.
class custom_adapter extends BaseAdapter
change ArrayList<String> horarios to ArrayList<Data> horarios
And the Data can be
public class Data{
private String hora;
private String nota;
private boolean shouldShowNota;
//write getter and setter here
}
at last, read the data in getView
Data data = getItem(position);
if (data.getShouldShowNota) {
nota.setText(data.getNote);
}
hora.setText(data.getHora);

java.lang.NullPointerException when try listview.getChildAt()

There is ListView with correct values:
public class FragmentTab1 extends SherlockFragment {
ListView list;
LazyAdapter adapter;
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
list = (ListView) getActivity().findViewById(android.R.id.list); //also I tried view.findViewById(android.R.id.list)
............
adapter = new LazyAdapter(getActivity(), mSource);
list.setAdapter(adapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragmenttab1, container, false);
return rootView;
}
when I try:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId(); //correct
int itemCount = list.getCount(); // 10 ps as show Logcat
if (R.id.save == id) {
CheckBox cb;
for(int i = itemCount - 1; i >= 0; i--) {
cb = (CheckBox)list.getChildAt(i).findViewById(R.id.checkBox1); //Error here
}
}
return true;
}
xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save to database"
android:id="#+id/checkBox1" /> // same id
and adapter is next:
public class LazyAdapter extends BaseAdapter {
private Activity activity;
ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
private ArrayList<Data> mObjects;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<Data> mObjects1) {
activity = a;
mObjects = mObjects1;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return mObjects.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
Data item = mObjects.get(position);
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item_internet, null);
TextView text=(TextView)vi.findViewById(R.id.title1);
ImageView image=(ImageView)vi.findViewById(android.R.id.icon);
text.setText(item.getmTitle());
bitmapArray.add(imageLoader.getBitmap());
imageLoader.DisplayImage(item.getmImageUrl(), image);
return vi;
}
I receive correct ListView, but receive error when I try click save button from action bar.
Probably, I should init CheckBox in adapter?
Somebody can help me?
list.getChildAt(i) will be null if the child item is not visible. So check for null before use.
So you cannot retrieve all checked items in this way.
Please post complete .xml and the definition of <Data>.
I'd think you'd get an indexoutofbounds but since it's null, this might be why: ListView getChildAt returning null for visible children
Also, put a log statement in your for loop to display the value of all variables concerned, so: i and itemCount etc.
And set a breakpoint just before the loop and run debug mode to step over to check the values as it loops through and you'll see what i value caused the nullpointer in the debugger or if you miss it, it will be in logcat
I know this is very old post. But I'm answering because people are still looking for a work around on ListView getChildAt() null pointer exception.
This is because the ArrayApdater is REMOVING and RECYCLING the views that are not visible yet on the ListView because of height. So that if you have 10 item views, and ListView can display 4 - 5 at a the time :
The Adapter REMOVE the item views at position 5 to 9, so that any attempt to adapter.getChildAt(5... to 9) will cause null pointer exception
The Adapter also RECYCLE the item view, so that any reference you made on position 3 for example will be lost when you scroll down to 5 to 9, and also any Input that you make on position 3 (EditText, Checkbox, etc.) will be recycled when you scroll down to 5 to 9 and will be reused at another position later (ex position 1, 2 or 3, etc.) with the same value
The only way I found to control this is to forget about getting the View and to have :
Attribute HashMap<Integer, Boolean> cbValues or any type you want for handling the values you want to use for each item on the list. The first type must be unique for item like item->getId() or position. Initialize it with new HashMap<>() in the Constructor;
Add InputListener for Input Views, (addTextChangedListener for EditText, setOnCheckedChangeListener for Checkbox, etc.) And on input, update the HashMap key (item.getId() or position) and value (editable.toString() or true or false). Ex. on #Override public void onCheckedChanged, put boolean result cbValues.put(item.getId(), b);
Prevent Adapter from using recycled convertView, remove condition if(convertView == null) so that adapter always inflate a brand new view instance. Because the view instance is new each time, you must set the value from HashMap each time also like if it already contains the key if(cbValues.containsKey(item.getId())){cbItem.setChecked(cbValue.get(cbItem.getId()))};. Probably in this case there is not tons of Items, so that smooth scrolling won't be a must.
And finally create public methods to get the Values outside of Adapter passing item->getId() Integer as parameter. Ex : 'public bool getCheckboxValueForItemId(int itemId) { return cbValues.get(itemId); }` . It will be easy then to select Item from Adapter
Here is the Codes at the end :
public class LazyAdapter extends BaseAdapter {
private Activity activity;
ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
private ArrayList<Data> mObjects;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
HashMap<Integer, Boolean> cbValues;
public LazyAdapter(Activity a, ArrayList<Data> mObjects1) {
activity = a;
mObjects = mObjects1;
cbValues = new HashMap<>();
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return mObjects.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
Data item = mObjects.get(position);
View vi=convertView;
// Remove convertView condition
//if(convertView==null)
vi = inflater.inflate(R.layout.item_internet, null);
TextView text=(TextView)vi.findViewById(R.id.title1);
ImageView image=(ImageView)vi.findViewById(android.R.id.icon);
Checkbox cbItem = (Checkbox) vi.findViewById(android.R.id.checkbox1);
text.setText(item.getmTitle());
bitmapArray.add(imageLoader.getBitmap());
imageLoader.DisplayImage(item.getmImageUrl(), image);
if(cbValues.containsKey(item.getId())) {
cbItem.setChecked(cbValue.get(cbItem.getId()))};
}
cbItem.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
cbValues.put(item.getId(), b);
}
});
return vi;
}
// itemId : unique identifier for an Item, not the position of Item in Adapter
public bool getCheckboxValueForItemId(int itemId) {
return cbValues.get(itemId);
}
}

Help on a simple Android ListView problem

I am new to Android, so this may seem like a basic question. But what I got is a very simple class called SingleItem, which has an integer and a String and a getter and setter for each. In my application, I got an ArrayList which holds a collection of SingleItem objects. I also have a layout with a ListView widget.
What I am trying to do is populate the ListView with my String value in SingleItem, but when a user selects an item from the ListView, I need the integer ID from that SingleItem value. How do I do this in Android development?
If you are using your own adapter to populate the list then in the getView() function when building the view to return you can call setTag() on the view you are returning and store the entire "SingleItem" object. Then in the onClickListener of the views you return you can retrieve your info using the getTag() method of the view that has been clicked.
EDIT:
Specified which onClickListener I am referring to
here is a bunch of pseudo code: create your own adapter. This will give the flexibility to do all kinds of things but important to you here is displaying only the relevant fields from your custom class and make more complicated listviews. a decent tutorial is here: http://developerlife.com/tutorials/?p=327
You will have to handle the other overrides of baseadapter but the key is assigning the value of singleItem.getString()
public class SingleItemAdapter extends BaseAdapter{
private ArrayList<SingleItem> m_items= new ArrayList<SingleItem>();
private Context mContext;
public SingleItemAdapter (Context c,ArrayList<SingleItem> items) {
mContext = c;
m_items= items;
}
.
.
.
#Override
public Object getItem(int arg0) {
return m_items.get(arg0);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.singleitemview, null);
}
SingleItem i=(SingleItem) getITem(position)
if(v!=null){
TextView tv=(TextView) v.findViewById(R.id.yourListItemView);
tv.setText(i.getStringValue());
}
}
}
After defining your custom adapter, you can then assign it to the listview and assign a listener to the OnItemSelectedListener. since this returns the position, you can tie that back to the position in your ArrayList of SingleItems.
.
.
.
SingleItemAdapter sia=new SingleItemAdapter(this,yourArray);
yourArrayList.setAdapter(sia);
yourArrayList.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long row) {
SingleItem si= yourArray.getItem(position);
//do something with si.getValue();
}
.
.
.
});

Categories