Search code examples
javaandroidadapter

Android; Get text out of dynamic textfield adapter


I have a dynamic adapter that fills up a listview with textviews with values read from a JSON file, here is an example ( https://i.sstatic.net/5LXCg.jpg ). Now I need to gather the user input from those fields and use it in a later part of my application, but my question is. when i generate textviews like that they all have the same ID right? so how can i specificly gather the user input of lets say the 2nd textview?

Adapter

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

        if (convertView == null) {if (convertView == null) {

            holder = new ViewHolder();

            LayoutInflater inflater = (LayoutInflater)
                    context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.layout_question_textfield, null, true);
--->        holder.editText = (AutoCompleteTextView) convertView.findViewById(R.id.edt);
--->        holder.editTitel = (Button) convertView.findViewById(R.id.btn);

            convertView.setTag(holder);
        }
        else {...}

        holder.editText.setHint(HintArrayList.get(position).getEditTextValue());

Solution

  • ID is an attribute of a view that scope of this attribute is limited by the inflated view group that includes this view.

    for example if we have this xml file (item_view.xml):

    <LinearLayout
          ...>
          <TextView
              ...
              android:id="@+id/textView_itemVew"/>
    </LinearLayout>
    

    and then we inflate this file several times (maybe in an adapter class) as below:

    View item1 = inflater.inflate(R.layout.item_view, null,true);
    View item2 = inflater.inflate(R.layout.item_view, null,true);
    View item3 = inflater.inflate(R.layout.item_view, null,true);
    

    now we can access the TextView view by it's ID but we should use the view group of this TextView to find it.

    //Id's are the same but view groups no!
    TextView editText_of_item1 = item1.findViewById(R.id.editText_itemVew);.
    TextView editText_of_item2 = item2.findViewById(R.id.editText_itemVew);
    TextView editText_of_item3 = item3.findViewById(R.id.editText_itemVew);
    

    .

    .

    .

    in your case you can add each EditText to a list to access it after whole list inflated ... like this:

    List<EditText> editTextList = new ArrayList<>();
    
    public View getView(int position,View view,ViewGroup parent) {  
        LayoutInflater inflater=context.getLayoutInflater();  
        View itemView = inflater.inflate(R.layout.item_view, null,true);  
    
        EditText itemEditText = (EditText) itemView.findViewById(R.id.editText);
    
        editTextList.add(itemEditText);
    
        return itemView;  
    };  
    

    there is useful example in javaTpoint website for you.