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.
Related
I am running into some difficulty with populating values to a listview, which currently displays no rows.
Firstly I am retrieving values from my database table and storing them in Arrays within onPostExecute.
LikedListAdapter listAdapter = new LikedListAdapter(context, R.layout.liked_list_main, restID, restName, restAddr1, restAddr2, restImgPath);
lvPlaces.setAdapter(listAdapter);
These values are then successfully passed into my ListAdapter.
public LikedListAdapter(Context context, int resource, String[] restID, String[] restName, String[] restAddr1, String[] restAddr2, String[] restImgPath) {
super(context, resource);
this.context = context;
this.resource = resource;
this.restID = restID;
this.restName = restName;
this.restAddr1 = restAddr1;
this.restAddr2 = restAddr2;
this.restImgPath = restImgPath;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LinearLayout likedItemsView;
if(convertView==null) {
likedItemsView = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater vi;
vi = (LayoutInflater)getContext().getSystemService(inflater);
vi.inflate(resource, likedItemsView, true);
}
else {
likedItemsView = (LinearLayout) convertView;
}
ImageView restaurantImg = (ImageView)likedItemsView.findViewById(R.id.listItemThumbImg);
TextView restaurantName =(TextView)likedItemsView.findViewById(R.id.listItemTitle);
TextView restaurantDesc = (TextView)likedItemsView.findViewById(R.id.listItemSubText);
restaurantName.setText(restName[position]);
restaurantDesc.setText(restAddr1[position] + ", " + restAddr2[position]);
Picasso
.with(getContext())
.load(restImgPath[position])
.into(restaurantImg);
return likedItemsView;
}
However, when i run the app the Listview is empty. When debugging i notice that the values are successfully passed to my listAdapter (on debugging it displays the values retrieved being displayed in the constructor) however it never hits the method getView, where values are set to each listview widget.
Is there something i am misunderstanding, or do i need to call the getView method at some point? Thanks in advance.
Did you override
getCount()
method? If not then return the size of your rows. Ex-
#Override
public int getCount() {
return restName.length;
}
Hope your problem will be solved. If already populated list then use
adapter.notifyDataSetChanged()
method.
LikedListAdapter listAdapter = new LikedListAdapter(context, R.layout.liked_list_main, restID, restName, restAddr1, restAddr2, restImgPath);
lvPlaces.setAdapter(listAdapter);
listAdapater.notifyDataSetChanged(); // <-- add this
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.
So I have a List View that when you click on a row it opens up a new activity. In the new activity there's a checkbox. If you check the check box and then go back to the listview activity it should set a checkmark next to the list view item that was initially clicked.
Whats happening right now is when I check the checkbox and return to the listview every row has a checkmark next to it regardless of which row the checkbox was checked from.
heres my mainactivity with the listview and on click listener that starts the second checkbox activity
//fill list view with xml array of routes
final CharSequence[] routeListViewItems = getResources().getTextArray(R.array.routeList);
//custom adapter for list view
ListAdapter routeAdapter = new CustomAdapter(this, routeListViewItems);
final ListView routeListView = (ListView) findViewById(R.id.routeListView);
routeListView.setAdapter(routeAdapter);
routeListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int listViewItemPosition = position;
CharSequence route = routeListViewItems[position];
int imageId = (int) image.getResourceId(position, -1);
if (route.equals(routeListViewItems[position]))
{
Intent intent = new Intent(view.getContext(), RouteDetails.class);
intent.putExtra("route", routeDetail[position]);
intent.putExtra("imageResourceId", imageId);
intent.putExtra("routeName", routeListViewItems[position]);
intent.putExtra("listViewItemPosition", listViewItemPosition);
startActivity(intent);
}
}
}
);
}
then heres what im passing from the second activity back to the listview activity
#Override ///////for back button///////
public void onBackPressed() {
super.onBackPressed();
////////sets checkmark next to listview item//////
if (routeCheckBox.isChecked())
{
Intent check = new Intent(RouteDetails.this,MainActivity.class);
check.putExtra("checkImageResource", R.drawable.checkmark);
check.putExtra("listViewItemPosition", listViewItemPosition);
startActivity(check);
}
}
and heres back in my listview activity where I recieve the info from my checkbox activity and set the checkmark
edited to include full adapter class
edited to include code that I found to solve my issue!
class CustomAdapter extends ArrayAdapter<CharSequence> {
public CustomAdapter(Context context, CharSequence[] routes) {
super(context, R.layout.custom_row ,routes);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater routeInflater = LayoutInflater.from(getContext());
View customView = convertView;
if(customView == null){customView = routeInflater.inflate(R.layout.custom_row, parent, false);}
CharSequence singleRoute = getItem(position);
TextView routeText = (TextView) customView.findViewById(R.id.routeText);
routeText.setText(singleRoute);
/////////////set check mark/////////////
ImageView checkImageView = (ImageView) customView.findViewById(R.id.checkImageView);
int checkImageResourceId = ((Activity) getContext()).getIntent().getIntExtra("checkImageResource",0);
int listViewItemPosition = ((Activity) getContext()).getIntent().getIntExtra("listViewItemPosition",0);
/////my solution was just setting where listviewitemposition == position in my getview method//////
if (listViewItemPosition == position)
{
checkImageView.setImageResource(checkImageResourceId);}
//////////////////////////////////////////////////
return customView;
}
thanks for any help!
The solution was I just needed use an if statement to set listviewItemPosition == position in my getView method
/////my solution was just setting where listviewitemposition == position in my getview method//////
if (listViewItemPosition == position)
{
checkImageView.setImageResource(checkImageResourceId);}
//////////////////////////////////////////////////
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);
}
}
The title pretty much says it all. I have a listview being populated by a simple adapter and an xml layout that changes based on how many rows are present in the listview item. When I add data to one of the items in the activity, calling the notifyondatasetchanged does not update the list, but if I back out of the activity and go back in everything looks the way it should. What do I need to do so when I refresh the adapter the getview gets updated as well?
public AlarmListAdapter(Context context, ArrayList<HashMap<String, String>> list, int textViewResourceId, String[] fields, int[] textViewId) {
super(context, list, textViewResourceId, fields, textViewId);
this.list = list;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.alarm_list_item, null);
}
if(list.get(position).get("alert") == null){
v.findViewById(R.id.ListViewItemSub).setVisibility(View.GONE);
}
return super.getView(position, convertView, parent);
}
public void forceReload(){
notifyDataSetChanged();
}
The notifyondatasetchanged is being called from a popup within my activity. The code for that button is listed below:
addCustomAlertButton = (Button)pView.findViewById(R.id.AddCustomAlertButton);
addCustomAlertButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
arrayList.get((int) customAlertId).setAlertDialog(customAlertInput.getText().toString());
Toast.makeText(EditAlarmsActivity.this, "Custom Alert Added", Toast.LENGTH_SHORT).show();
updateListArray();
pw.dismiss();
}
You could try setListAdapter(yourAdapter);
or listview.requestLayout();
If those didn't work then you could also try refreshing the listview through scrolling, since the getView() function is called once the listview is scrolled.