Set Json Array values to AutoCompleteTextView in Android

1.5k Views Asked by At

I am new in Android development, I want to bind a Json array to android AutocompleteTextView in Form (Registration form).

enter image description here the Json array is showed in below

{"Status":true,"errorType":null,"InstituteList":[{"InstituteID":"1","InstituteName":"Demo Institute"},{"InstituteID":"16","InstituteName":"Sheridan College"},{"InstituteID":"17","InstituteName":"iCent Prosp"},{"InstituteID":"18","InstituteName":"Seneca College"}]}

here the Type Institution Name is the auto completeTextView. The main requirement is that, I can bind the values like in the Json response InstituteName on the front end and When click on the Submit Button it needs to take the InstituteID Object.

Currently I can bind the InstituteName Object to AutocompleteTextView and Working fine.

enter image description here But the Submit Action was not performing perfectly.

I cant getting the InstituteID in my codes for performing

Here is my code.

Getting response from web service as json array and binding in asyncTask.

  @Override
    protected void onPostExecute(String res) {

            try
            {
                Log.i("Intitute List",res);
            JSONObject responseObject = new JSONObject(res);
            String status=responseObject.getString("Status");
            ArrayList<String> listInstituteNames = new ArrayList<>();
            JSONArray detailsArray = responseObject.getJSONArray("InstituteList");

            for (int i = 0; i <detailsArray.length() ; i++) {
                JSONObject obj = detailsArray.getJSONObject(i);
                listInstituteNames.add(obj.getString("InstituteName"));
            }

            //Log.i("InstituteName", String.valueOf(listInstituteNames));
            myStringArray = listInstituteNames;

            AutoCompleteAdapter adapter = new AutoCompleteAdapter(SignUpActivity.this, android.R.layout.simple_dropdown_item_1line, android.R.id.text1, listInstituteNames);
            autoTextView.setThreshold(1);
            autoTextView.setAdapter(adapter);




            }
                    catch (JSONException e1) {
            e1.printStackTrace();
        }

AutoCompleteAdapter.java

 package Adapter;
 import java.util.ArrayList;
 import java.util.List;

 import android.content.Context;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ArrayAdapter;
 import android.widget.Filter;
 import android.widget.Filterable;

public class AutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {

private ArrayList<String> fullList;
private ArrayList<String> mOriginalValues;
private ArrayFilter mFilter;

public AutoCompleteAdapter(Context context, int resource, int textViewResourceId, List<String> objects) {

    super(context, resource, textViewResourceId, objects);
    fullList = (ArrayList<String>) objects;
    mOriginalValues = new ArrayList<String>(fullList);

}

@Override
public int getCount() {
    return fullList.size();
}

@Override
public String getItem(int position) {
    return fullList.get(position);
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
    return super.getView(position, convertView, parent);
}

@Override
public Filter getFilter() {
    if (mFilter == null) {
        mFilter = new ArrayFilter();
    }
    return mFilter;
}


 private class ArrayFilter extends Filter {
    private Object lock;

    @Override
    protected FilterResults performFiltering(CharSequence prefix) {
        FilterResults results = new FilterResults();

        if (mOriginalValues == null) {
            synchronized (lock) {
                mOriginalValues = new ArrayList<String>(fullList);
            }
        }

        if (prefix == null || prefix.length() == 0) {
            synchronized (lock) {
                ArrayList<String> list = new ArrayList<String>(mOriginalValues);
                results.values = list;
                results.count = list.size();
            }
        } else {
            final String prefixString = prefix.toString().toLowerCase();

            ArrayList<String> values = mOriginalValues;
            int count = values.size();

            ArrayList<String> newValues = new ArrayList<String>(count);

            for (int i = 0; i < count; i++) {
                String item = values.get(i);
                if (item.toLowerCase().contains(prefixString)) {
                    newValues.add(item);
                }

            }

            results.values = newValues;
            results.count = newValues.size();
        }

        return results;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {

        if(results.values!=null){
            fullList = (ArrayList<String>) results.values;
        }else{
            fullList = new ArrayList<String>();
        }
        if (results.count > 0) {
            notifyDataSetChanged();
        } else {
            notifyDataSetInvalidated();
        }
    }
 }
}

AutoCompleteTextView Section in XML File..

 <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:id="@+id/autoCompt"
    android:orientation="vertical">

    <AutoCompleteTextView
        android:id="@+id/instname_field"
        android:layout_width="match_parent"
        android:hint="Type Institution Name"
        android:paddingLeft="10dp"
        android:textColor="#fff"
        android:background="#b8d1e5"
        android:layout_height="40dp"
        android:textSize="20dp"
        android:ems="10"/>
    </LinearLayout>

How can I solve this Issue. Thanks.

1

There are 1 best solutions below

6
On BEST ANSWER

You can see @blackBelt comment that is the right way to do that.

But here i am explain you another method which is easy to understand using Hashmap instead of Object class .

HashMap<String, String> map_name_value = new HashMap<String, Stirng>();

for (int i = 0; i <detailsArray.length() ; i++) {

          JSONObject obj = detailsArray.getJSONObject(i)

          listInstituteNames.add(obj.getString("InstituteName"))

          map_name_value.put(obj.getString("InstituteName"),obj.getString("InstituteID"));

    }

Then while clicking the item.

Do this:

autoTextView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View arg1, int pos,
                long id) {
             Editable message = autoTextView.getText();

             String  item_name    = message.toString();

              String item_id = map_name_value.get(item_name);
               //your stuff
           }
    });

 //item_name is name of institute
 // item_id is id of institute