2

I'm working on an Android application of booking medicine offline. I have used ListView for Cart, but whenever I add a new item in cart, my previous item get replaced.

L1 = imageacidity 
L2 = imagecough

 if(msg.toString().equals("L1")) {

       adapter = new ContactImageAdapter(this, R.layout.list, imageacidity);
       ListView dataList = (ListView) findViewById(R.id.list);
       dataList.setAdapter(adapter);
       adapter.notifyDataSetChanged();

   }
   if(msg.toString().equals("L2"))
   {

       adapter = new ContactImageAdapter(this, R.layout.list, imagecough);
       ListView dataList = (ListView) findViewById(R.id.list);
       dataList.setAdapter(adapter);
       adapter.notifyDataSetChanged();
   }

Here I have 5 elements in imageacidity and Imagecough Array. Whenever I select 1 item, it gets added in cart, but when I try to select another item it get replaced with new one.

7
  • 1
    If you mean you can't select more but only one item in your ListView, this might help: stackoverflow.com/questions/1362602/… Commented Mar 29, 2016 at 20:05
  • @nvi9. Thank you so much for your response . Exactly not more then one item. Commented Mar 29, 2016 at 20:08
  • Every time you make a new Adapter, and do dataList.setAdapter(adapter); you completely remove the old data. Is that the problem you are having? Commented Mar 29, 2016 at 20:13
  • I had the same understanding cricket_007 did. @nvi9, you should post your comment as an answer so we can upvote it and it can be accepted. :) Commented Mar 29, 2016 at 20:14
  • @cricket_007 means I must remove that line. Let me try. Thank you so much and let you know Commented Mar 29, 2016 at 20:15

4 Answers 4

5

You have to Add the element inside your adapter. I will post a custom Adapter and show you how to add elements properly.

Adapter:

public class YourAdapter extends BaseAdapter {
    List<String> itens;
    private Context mContext;
    private static LayoutInflater inflater = null;

    public YourAdapter(Context context, List<String> itens){
        this.itens = itens;
        mContext = context;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
        return itens.size();
    }

    public String getItem(int position) {
        return itens.get(position);
    }

    public long getItemId(int position) {
        return 0;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi = convertView;
        if (convertView == null)
            vi = inflater.inflate(R.layout.list_row, parent, false);

        String msg = itens.get(position);

        TextView tx = vi.findViewById(R.id.your_id);

        tx.setText(msg);

        return vi;
    }

    public void addItem(String item){
        itens.add(item);
    }

    public void addItens(List<String> itens){
        this.itens.addAll(itens);
    }
}

ListView:

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

        adapter = new CustomAdapter(this,yourListOfItens);

        listView = (ListView) findViewById(R.id.list_view);
        listView.setAdapter(adapter);
    }

You can set initial data on constructor of adapter, or use methods addItem and addAll on a click button for example.

Sign up to request clarification or add additional context in comments.

1 Comment

getItem shouldn't return null. Plus, you could just use ArrayAdapter instead.
1

The problem you are describing of the data being removed is happening because making a new ContactImageAdapter and calling setAdapter, which will completely remove the data that was already in the ListView.

If you want to properly implement the code in the question, you need something like this.

String msg = ""; // TODO: get this String value
ListView dataList = (ListView) findViewById(R.id.list);

// TODO: Define a single List to store the data and use that in *one* adapter
List<Contact> contacts = new ArrayList<Contact>();
adapter = new ContactImageAdapter(this, R.layout.list, contacts);
dataList.setAdapter(adapter);

// TODO: Replace this with the object to add to the adapter
Contact contact = null;

if(msg.equals("L1")) {
    // TODO: Use whatever values you want for "L1"
    int img = R.drawable.bati_acidity_1;
    String name = "Amlapitta";
    String price = "price 170";
    contact = new Contact(img, name, price); 
}
else if(msg.equals("L2")) {
    // TODO: Use whatever values you want for "L2"
    int img = R.drawable.bati_acidity_2;
    String name = "Amlapitta2";
    String price = "price 270";
    contact = new Contact(img, name, price); 
}
if (contact != null) {
    contacts.add(contact); 
    adapter.notifyDataSetChanged();
}

Another problem is that you are calling notifyDataSetChanged without actually changing the datasets of imageacidity or imagecough.

13 Comments

Showing Error in m=new Medicine("L1");
@RahulChhuttani Well, yeah. This is only an example, not runnable code.
Sorry Sir. I'm new to android Development. Though I Tried.
That's fine. I will leave my answer because StackOverflow is designed to help everyone, not only the person asking the question.
Agreed. Can you please tell me replacement of L1 with actual code I mean what I have to pass on that.
|
0

You can use an algorithm (logic) on the InputListAdapter checking and verifying if there is a MedicineVO (Value Object Pattern) item on old list before the calling notyChange(..) method. In addition, you can wrapping the logic in other class such as MedicineLogic to improve the adapter readability.

See the sample code below:

    public class MedicineInputListAdapter extends ArrayAdapter<MedicineVo> {
    public static final int[]   COLORS  = new int[] { Color.WHITE, Color.BLUE };

    private Context mContext;
    private List<MedicineVo> medicineVos;
    private MedicineVo medicineVoActual;


    public BasePreOSPreventivaCorretivaInputListAdapter(Context context, int resource, List<MedicineVo> medicineVos) {
        super(context, resource, medicineVos);

        this.medicineVoActual = new MedicineVo();
        this.medicineVos = new ArrayList<MedicineVo>();
        this.medicineVos.addAll(medicineVos);

        this.mContext = context;

    }

    private static class ViewHolder {        
        TextView mMedicineTextView;
        //------------------------------------------------------
        // others Android view components 
        //------------------------------------------------------

    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder viewHolder;

        if (convertView == null) {

            //------------------------------------------------------
            // mapper from xml to view and add itens to holder
            //------------------------------------------------------





            //------------------------------------------------------
            // add event action to the mMedicineTextView
            //------------------------------------------------------
            viewHolder.mMedicineTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    TextView textView = (TextView) view;
                    MedicineVo medicineVo = (MedicineVo) textView.getTag();

                    boolean selected = medicineVo.getSelected();
                    if (selected) {
                        /*do it*/
                    }

                    refreshPreOSMaterialWhenUpdate(preOSMaterialVo);

                }
            });


            convertView.setTag(viewHolder);
        }
        else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        //------------------------------------------------------
        // get item and adjust color
        //------------------------------------------------------
        MedicineVo item = getItem(position);

        /*do it*/

        return convertView;
    }



    public void refreshMedicineListWhenUpdate(MedicineVo medicineVo){
        List<MedicineVo> newMedicineVos = new ArrayList<MedicineVo>();

        for (MedicineVo medicineVoOnList : medicineVos) {
            if( StringUtils.isNull(medicineVoOnList.getId()) )
                continue;

            if( MedicineLogic.existsOnList(medicineVos, medicineVoOnList) )
                continue;

            /* others checks if necessary */    

            newMedicineVos.add(medicineVoOnList);


        }
        medicineVos.addAll(newMedicineVos);
    }
}

1 Comment

Thank you @EAA but I'm new though feeling difficult to implement.
0

If you can't select more but only one item of your ListView, this might help.

As others have commented on the question, changing the adapter of a ListView can clear the selection too, but as I supposed the code you've posted is inside onCreate (or other kind of initialization) so setting the adapter there won't affect the selection (since there can't be selection without items... :) )

1 Comment

Thank you @nvi9. I'm new but Trying my level best to understand the code. I tried listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); but showing error. Though I'm unable to use such method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.