Update the Value of the ListView Item In Android

10,845

Solution 1

Never update ListView items directly. Update data in your storage and call notifyDataSetChanged on your adapter.

Solution 2

You will need an ArrayAdapter with the data for your list. Then when you manipulate the data in that array you can call .notifyDataSetChanged(); on the adabter to refresh your view. Be aware that it have to be the same arraylist! so you cant call arraylist = new ArrayList(); that will destroy the reference. Instead use arraylist.clear(); and then arraylist.addAll(data);

Here is an example:

    public class GroupsListAdapter extends ArrayAdapter<Object> {

    /**
     * Constructor
     * 
     * @param context
     *            Context
     * @param objects
     *            Array of objects to show in the list.
     */
    public GroupsListAdapter(Context context, ArrayList<Object> objects) {
        super(context, R.layout.row, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        Object = getItem(position);

        /* Initialize strings */
        String nameText = group.getName();
        boolean upToDate = group.isUpToDate();

        /* Get the layout for the list rows */
        View rowView = convertView;
        if (rowView == null) {
            LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            rowView = inflater.inflate(R.layout.row, parent, false);
        }
            rowView.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                         //do stuff here
                    }
            });


        return rowView;
    }
}
Share:
10,845
Developer
Author by

Developer

Now working as Android developer in Travel Domain start up company SOreadytohelp

Updated on June 06, 2022

Comments

  • Developer
    Developer almost 2 years

    I have a Listview that is showing a list .So on the click of the listview i have a customDialog.In that i am taking some values from the user.So want once the user enters the details and click on the ok button ,then i have to update the value of that item from the listview and when all the item of the listview has been updated then compare it with the previous value to check whether all the item are updated or not .Help me on this how could i do this

    Activity Code

    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            setContentView(R.layout.activity_iween_booking_page);
            intent = getIntent();
            isReturn  = (Boolean) intent.getExtras().get("isReturn");
            searchParam = (HashMap<String,String>) intent.getExtras().get("searchParam");
            listView = (ListView) findViewById(R.id.passengerList);
            emailId = (TextView)findViewById(R.id.emailid);
            continuebooking = (ImageView)findViewById(R.id.continuebooking);
            firstName= (EditText)findViewById(R.id.firstName);
            lastName =(EditText)findViewById(R.id.LastName);
            mobileNumber =(EditText)findViewById(R.id.mobileNumber);
    
    
            setTittle();
            if(searchParam.get("NoOfChild").equals("0") && searchParam.get("NoOfInfant").equals("0")&& searchParam.get("NoOfAdult").equals("1")){
    
            } else {
    
    
                passengerList = getPassengerList(passengerInfo);
                showPassengerListView(passengerList);
    
            }
    
            continuebooking.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    if(searchParam.get("NoOfChild").equals("0") && searchParam.get("NoOfInfant").equals("0") && searchParam.get("NoOfAdult").equals("1")){
                        if(firstName.getText().toString().trim().equalsIgnoreCase("")){
                            firstName.setError("Enter FirstName");
                        }
                        if(lastName.getText().toString().trim().equalsIgnoreCase("")){
                            lastName.setError("Enter LastName");
                        }
                        if(mobileNumber.getText().toString().trim().equalsIgnoreCase("")){
                            mobileNumber.setError("Enter Mobile No.");
                        }
                    }else{
                         int count = listView.getAdapter().getCount();
                         listData = new String[count];
                         for (int i = 0; i < count; i++) {
                                listData[i] = listView.getAdapter().getItem(i).toString();
    
                         }
                         for(int i=0;i<listView.getAdapter().getCount();i++){
                             for(int j=0;j<count;j++){
                                 if(listData[j]==listView.getAdapter().getItem(i).toString()){
                                     Log.d("listData data", listView.getAdapter().getItem(i).toString());
    //                              View v=listView.getChildAt(i);
    //                              TextView tv=(TextView) v.findViewById(android.R.id.text1);
    //                              tv.setError("Please change the data");
                                  }
                            }
                         }
                        } 
    
    
                }
            });
    
    
    
        }
    
    
    
        private void showPassengerListView(final String[] passengerList) {
            adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, passengerList);
            listView.setAdapter(adapter);
            listView.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
    //              int itemPosition     = position;
    //              String  itemValue    = (String) listView.getItemAtPosition(position);
                    View v=listView.getChildAt(position);
                    TextView tv=(TextView) v.findViewById(android.R.id.text1);
                    tv.setError(null);
                    passengerInformationPopup(passengerList,position);
                }
            });
        }
    
    
    
    
    
    
        public void passengerInformationPopup(final String[] passengerList, final int position) {
            final Dialog dialog= new Dialog(Test.this,R.style.Dialog_Fullscreen);
            dialog.setContentView(R.layout.passenger_details_dialog); 
    
    
            final EditText firstNameDialog;
            final EditText lastNameDialog;
            ImageView continueBooking;
            dateofBirth = (TextView)dialog.findViewById(R.id.dateofBirth);
            firstNameDialog = (EditText)dialog.findViewById(R.id.firstName);
            lastNameDialog =(EditText)dialog.findViewById(R.id.LastName);
            continueBooking =(ImageView)dialog.findViewById(R.id.continuebooking);
            if((passengerList[position].contains("Child"))|| (passengerList[position].contains("Infant"))){
                dateofBirth.setVisibility(View.VISIBLE);
             }else{
                    dateofBirth.setVisibility(View.GONE);
            }
            dateofBirth.setClickable(true);
            dialog.show();
    
            continueBooking.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    isSuccess= true;
                    if(firstNameDialog.getText().toString().trim().equalsIgnoreCase("")){
                        firstNameDialog.setError("Enter FirstName");
                        isSuccess= false;
                    }
                    if(lastNameDialog.getText().toString().trim().equalsIgnoreCase("")){
                        lastNameDialog.setError("Enter LastName");
                        isSuccess= false;
                    }
                    if((passengerList[position].contains("Child"))|| (passengerList[position].contains("Infant"))){
                        if(dateofBirth.getText().toString().trim().equalsIgnoreCase("")){
                            dateofBirth.setError("Date of Birth Can't be blank");
                            isSuccess= false;
                        }
                     }
                    if(isSuccess){
                        dialog.cancel();
                        View v=listView.getChildAt(position);
                        TextView tv= (TextView) v.findViewById(android.R.id.text1);
                        tv.setText(firstNameDialog.getText().toString().trim().toString()+" "+lastNameDialog.getText().toString().trim().toString());
    
    
                    }
                }
            });
    
        }
    

    passengerInformationPopup function i have to update the items values of the ListView .In on create continueBooking i have to check whether all the items are updated or not

    Before Updation After Updation

  • Developer
    Developer over 10 years
    So how could i identify which array position i have update in the array.so that the position of the items won't change see my code what i have done
  • JWqvist
    JWqvist over 10 years
    Create you own class that extends ArrayAdapter then you create the onClicklistener in the getView method, that method is called with the int position parm
  • Developer
    Developer over 10 years
    will u post some sample code for my problem how to update and validate the listview item
  • JWqvist
    JWqvist over 10 years
    This code is insted of all the code in your onCreate method. Create an adabter and set it on the listview.
  • Developer
    Developer over 10 years
    what is happening now it is updating the value of the item but i when i am trying to get the value of the item then i am getting the previous value
  • JWqvist
    JWqvist over 10 years
    Try getting and setting the value in the same arraylist (The one you called the adapter with)
  • David Christopher Reynolds
    David Christopher Reynolds over 9 years
    Thanks very much kriomant - this problem has been annoying me for ages.