logo
down
shadow

Android ListView Adapter Crash issue/Duplicates


Android ListView Adapter Crash issue/Duplicates

By : Riyaz Abdul
Date : November 28 2020, 09:01 AM
Does that help Yes you will get duplicate Item, Because Convertview is reusing. Once convertview is created that view using if you scroll.
So better use single layout and with both Image and text. Based type hide any one.
code :


Share : facebook icon twitter icon
Android ListView Adapter OnClickListener issue

Android ListView Adapter OnClickListener issue


By : Andrew
Date : March 29 2020, 07:55 AM
wish help you to fix your issue why you dont attach an onItemClickListener to your ListView in your activity, instead of perform ItemClick from each inner view in the ListView
code :
        dataListView = (ListView)findViewById(R.id.dataListView);     
        dataItems = new ArrayList<DataItem>();
        int resID = R.layout.dataitem;
        aa = new DataItemAdapter(this, resID, dataItems);
        dataListView.setAdapter(aa);
        //attach a listener to the list view
        dataListView.setOnItemClickListener (listener);

        dataListView.setItemsCanFocus(true);
OnItemClickListener listener = new OnItemClickListener (){

  @Override
  onItemClick(AdapterView<?> parent, View view, int position, long id){
      ((TextView)view.findViewById(R.id.yourTextViewId)).getText();
      //or do your stuff
  }

}
public class Main extends Activity {
    private ArrayList<DataItem> dataItems;
    private DataItemAdapter aa;
    private ListView dataListView;  

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        dataListView = (ListView)findViewById(R.id.dataListView);     
        dataItems = new ArrayList<DataItem>();
        int resID = R.layout.dataitem;
        aa = new DataItemAdapter(this, resID, dataItems);
        dataListView.setAdapter(aa);
        dataListView.setItemsCanFocus(true);

    populateArray();
}

public void populateArray() {
    DataItem newItem = new DataItem(
            "2008","Ferrari","F430","Red","ASX772"
        );
    dataItems.add(0, newItem);
    newItem = new DataItem(
            "2008","Ferrari","F430","Black","TZB123"
        );
    dataItems.add(0, newItem);
    newItem = new DataItem(
            "2009","Ferrari","F430","Red","MIDAS"
        );
    dataItems.add(0, newItem);      

    aa.notifyDataSetChanged();
}

public void modelInfo(int pos) {
    Log.i("modelInfo", "=" + pos);
}

public void makeInfo(int pos) {
    Log.i("makeInfo", "=" + pos);
}

public void assetInfo(int pos) {
    Log.i("assetInfo", "=" + pos);
}
}
public class DataItemAdapter extends ArrayAdapter<DataItem> {
    private Activity activity;
    private int resource;
    private LayoutInflater inflater=null;

    public DataItemAdapter(Activity _activity,int _resource,List<DataItem> _items) {
        super(_activity, _resource, _items);
        inflater = (LayoutInflater)_activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //i always do this way, but i dont think this is the error
        //inflater = LayoutInflater.from(_activity.getBaseContext());
        resource = _resource;
        activity = _activity;
    }

public static class ViewHolder {
    TextView carYear;
    TextView carMake;
    TextView carModel;
    TextView carColor;
    TextView assetTag;
   }

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    ViewHolder holder;
    if (convertView == null) {
        vi = inflater.inflate(resource, null);
        holder=new ViewHolder();
        holder.carYear = (TextView)vi.findViewById(R.id.carYear);
        holder.carMake = (TextView)vi.findViewById(R.id.carMake);
        holder.carModel = (TextView)vi.findViewById(R.id.carModel);
        holder.carColor = (TextView)vi.findViewById(R.id.carColor);
        holder.assetTag = (TextView)vi.findViewById(R.id.assetTag);
        vi.setTag(holder);
    } else {
        holder=(ViewHolder)vi.getTag();
    }

    DataItem item = getItem(position);  

    holder.carYear.setText(item.getCarYear());
    holder.carMake.setText(item.getCarMake());
    holder.carModel.setText(item.getCarModel());
    holder.carColor.setText(item.getCarColor());
    holder.assetTag.setText(item.getAssetTag());

    holder.carYear.setTag(position);
    holder.assetTag.setTag(position);

    final OnClickListener makeListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            LinearLayout ll = (LinearLayout)v.getParent();
            TextView tv = (TextView)ll.getChildAt(0);
            Integer pos = (Integer) tv.getTag();
            //main.makeInfo(pos);
            ((Main)activity).makeInfo(pos);
        }
    };
    holder.carMake.setOnClickListener(makeListener);

    final OnClickListener modelListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            LinearLayout ll = (LinearLayout)v.getParent();
            TextView tv = (TextView)ll.getChildAt(0);
            Integer pos = (Integer) tv.getTag();
            //main.modelInfo(pos);
            ((Main)activity).modelInfo(pos);
        }
   };        

    holder.carModel.setOnClickListener(modelListener);

    final OnClickListener assetListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            LinearLayout ll = (LinearLayout)v.getParent();
            TextView tv = (TextView)ll.getChildAt(0);
            Integer pos = (Integer) tv.getTag();
            //main.assetInfo(pos);
            ((Main)activity).assetInfo(pos);
        }
    };
    holder.assetTag.setOnClickListener(assetListener);        

    return vi;
}
ListView Adapter issue in android

ListView Adapter issue in android


By : Peter
Date : March 29 2020, 07:55 AM
I wish did fix the issue. I believe that the problem is that in the onClick handler, you always clear() the list, but then only notify the adapter if the selected directory is not empty.
So, when an empty directory is clicked, the list is changed (cleared), but the adapter is not notified.
android listview with custom adapter multiselection issue

android listview with custom adapter multiselection issue


By : Naveen Ram
Date : March 29 2020, 07:55 AM
this will help You need to maintain the selected item in adapter and use it to change the text :
Adapter Code
code :
 private int selectedIndex;
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        final ViewHolder holder;
                    LayoutInflater inflater = ((Activity) activity).getLayoutInflater();
                    if (convertView == null) {
                        convertView = inflater.inflate(resource,parent, false);
                        holder = new ViewHolder();
                        holder.group_name = (TextView) convertView.findViewById(R.id.group_name);
                        holder.select = (TextView) convertView.findViewById(R.id.select);
                        convertView.setTag(holder);
                    } else {
                        holder = (ViewHolder) convertView.getTag();
                    }
        if(selectedIndex!= -1 && position == selectedIndex)
        {
            convert_view.setBackgroundColor(Color.CYAN);
           holder.select.setText("selected");

        }
        else
        {
            convert_vie.wsetBackgroundColor(default_color);
           holder.select.setText("Select");
        }
                //Your other code      .....

        return convertView ;
    }

   public void setSelectedIndex(position)
   {
       selectedIndex = position;
   }
public class MainActivity extends Activity implements OnItemClickListener
{
    // Implemented onItemClickListener

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {
        adapter.setSelectedIndex(position);
    }
}
Adapter for ListView on android scrolling issue

Adapter for ListView on android scrolling issue


By : Dave Miles
Date : March 29 2020, 07:55 AM
Hope this helps I have created an adapter for my listview. for each listitem there's a checkbox on it. Whenever I scroll my listview it randomly set the checkbox to check on items. , try this..
code :
public View getView(int position, View convertView, final ViewGroup parent) {
    View vi = convertView;
    if (convertView == null)
        vi = inflater.inflate(R.layout.list_equipment_search, null);
    enter code here
    TextView serialno = (TextView) vi.findViewById(R.id.txtSerialNo); // Serial No
    TextView unitno = (TextView) vi.findViewById(R.id.txtUnitNo);

 CheckBox checkbox = (CheckBox) row.findViewById(R.id.chkEquipment);
        checkbox.setTag(new Integer(position));
        checkbox.setOnCheckedChangeListener(null);

            if (checkBoxState[position])
                checkbox.setChecked(true);
            else
                checkbox.setChecked(false);



        checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Integer pos = (Integer) buttonView.getTag();
                if (isChecked) {

                    checkBoxState[pos.intValue()] = true;
                } else {
                    checkBoxState[pos.intValue()] = false;


                }
            }
        });
Android: Adapter Changed outside ListView Issue

Android: Adapter Changed outside ListView Issue


By : sasanka
Date : March 29 2020, 07:55 AM
To fix this issue Don't initialize adapter everytime in onTextChanged() method. use notifyDataSetChanged(). here is example with your code.
Just Replace your code with this. That's it.
code :
SimpleStringAdapter adapter;
ArrayList<String> items = new ArrayList<>();
ListView addressList;

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

    addressList = (ListView) findViewById(R.id.addressList);
    addressBox = (EditText) findViewById(R.id.addressBox);

    adapter = new SimpleStringAdapter(this, items);
    addressList.setAdapter(adapter);

    //Search for locations when the user types in
    addressBox.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(final CharSequence s, int start, int before, int count) {
                //Search the typed location
                SearchAddresses(searchText);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
    });
}

private void SearchAddresses(String searchText) {
    Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
    try {
        List<Address> addresses =     geoCoder.getFromLocationName(searchText, 5);
        addressList.setAdapter(null);

        if (addresses.size() != 0) {
            //Add the Address line to the list
            items.add(addresses.get(0).getAddressLine(0));
            //Populate the listview
            adapter.notifyDataSetChanged();

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Related Posts Related Posts :
  • My shape moved but will pause for a while
  • How to solve syntax error in eclipse Mars.1
  • Shibboleth idp configuration for ldap authentication
  • Do something when app starts?
  • Android Runtime Exception font asset not found
  • How to query using objectify in Google App Engine app
  • List value is printing address instead of value
  • StringUtils.isBlank return false for null Strings
  • Sent parameter through PATCH android
  • i am not able to clear the code below given using throwable concept in java
  • How to get System time instead of Server time in java?
  • How to push json data into an arrya object in MONGO DB by java
  • Saving RelationshipEntity not working
  • Error on "instanceOf" when checking a subClass
  • Java - Splitting a image into 4 images
  • "Pinging" a server in Java
  • RoboGuice Proguard CreationException
  • Android Array list returns Null after adding values
  • Jar Executable what am I doing wrong?
  • How do I mitigate Connection leak triggered for connection com.mysql.jdbc.JDBC4Connection@11d08960,
  • How do i iterate values from a 2d array using conditions
  • Hide Button in CustomPagerAdapter
  • Java GC: does it ever make sense to call super.finalize() in a class that only extends Object?
  • 64bit HashMap in Java
  • Hibernate wildcard query on two columns
  • Want to Generate Auto Login Program Using Java
  • Spring security Oauth 2 with ajax login and form login
  • Parse findInBackground doesn't add to global arraylist?
  • Remove random item from ArrayList
  • in SpringMVC getMessage from i18n properties in a function outside the controller
  • How do I add JCheckBox next to each name that has been entered into an arraylist from a JTextField?
  • Return node ID along with complete node
  • InvocationTargetException. Cannot cast class X to class X. When invoked in Scala Imain through spark-submit
  • how to print elements of a 1D array into a N x N box
  • How to map csv file to pojo class in java
  • How, in Java, to encode default vhost %2F in URL/URI so it doesn't get changed to slash and fail to work
  • Tomcat 5.5 https configuration in Windows Server 2008 64bit
  • Enabling FIPS 140-2 compliance mode in MULE ESB
  • How to pass String PackageName to PkgName under parseXML() and run XMLParser class as a new activity when click on list
  • Error while creating spring -hibernate configuration file
  • Hand off control between java threads
  • NoClassDefFoundError: scala/collection/Seq
  • Getting stack overflow error on one machine but not the other on the same code
  • How can I loop AsyncAjaxRequest in GWT?
  • Failed to find provider info for urbanairship.provider
  • Displaying Splash screen only once on user preference
  • Loop List<WebElement> doesn't stop despite no more WebElements
  • Check if pattern exists in a String
  • Swing - Key Problems (Arrow Keys, Tab, etc.) in GUIs with TextComponents
  • Why the solution for binary search tree validity is not working?
  • Double encrypting 2048 RSA?
  • create junit test for runnable class
  • Unable to read and sort information from a text file in Java
  • My device isn't getting detected in android studio (driver issue)
  • Representing a Graph in Java
  • How to XML mapping using jxls
  • Quick Sort stackoverflow error for large arrays
  • Parsing Apache Tika XML Output returns Unknown Tag
  • java simple UI loop, can't find bug
  • how to use greater than and less than in a single if statement in java
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co