-1

I am getting data from JSON in below format

{
    "success": 1,
    "message": "done",
    "data": [
    {
        "name": "Central Construction",
        "id": 11
    },
    {
        "name": "IT",
        "id": 12
    },
    {
        "name": "Marketing",
        "id": 13
    },
    {
        "name": "Sales",
        "id": 14
    }
  ]
}

In my Response i am getting the object from data and storing it in my Model

JSONObject parentObject = new JSONObject(response);
JSONArray parentArray = parentObject.getJSONArray("data");
staffData = gson.fromJson(parentArray.toString(),StaffResponseModel.StaffData[].class);
staffName = new ArrayList<String>();
for(StaffResponseModel.StaffData staff : staffData) {
         staffName.add(staff.getName());
         staffName.add(String.valueOf(staff.getId()));
 }
 setUpAutoComplete();

And finally in my SetupAutoComplete

final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item,staffName);
        visitingStaffTextView.setAdapter(adapter);
        visitingStaffTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int index, long l) {

                String staff = adapter.getItem(index).toString();

                Toast.makeText(visitorSignInActivity.this,staff,Toast.LENGTH_LONG).show();

            }
        });

In the Toast i can see the name which selected and also sets it in the EditText, however i am currently unable to save the id of selected name, as i need to use/post that to server. I have seen quite a few question on stackoverflow and also tried to implement them but had no luck.

I am showing the name on AutoCompeleteEditText.. I need to store the id value in a variable to post to server.

Any Suggestion how i can get the id when name is selected?

chirag90
  • 2,211
  • 1
  • 22
  • 37
  • Is that logical for you to show the ID on the AutoCompleteEditText?It's weird。 – xiaoyuan Mar 16 '17 at 01:08
  • @xiaoyuan i am not showing the ID on AutoComplete i am showing the name, however the name which is selected, i need to store the ID in int value and post that value to server – chirag90 Mar 16 '17 at 01:10
  • But you stored all the names and ids in `staffName `, right?the result is all the data will be shown on the AutoCompleteEditText. – xiaoyuan Mar 16 '17 at 01:27
  • @xiaoyuan nope it is just showing the name on the AutocompleteEditText. If it was showing both. I could have slipt the value. – chirag90 Mar 16 '17 at 01:31
  • Then you have to check out whether the id is in the staffName or not.Maybe there is something wrong happens when you parse the json String. – xiaoyuan Mar 16 '17 at 01:45
  • @xiaoyuan that is what i am asking how do i check that. if i knew i would have been able to store that in the variable. but unfortunately i am not sure and i am not able to find much answers on internet. – chirag90 Mar 16 '17 at 07:56
  • Before downvoting please give a reason why you are downvoting. is there something wrong with my question? if so tell me and i will modify the question – chirag90 Mar 16 '17 at 07:57
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/138188/discussion-between-xiaoyuan-and-chirag90). – xiaoyuan Mar 16 '17 at 08:13

2 Answers2

0

Thanks everyone for your helpful answers and comments, I have now solved my issue by creating custom adapter.

Parsing JSON Value

try {
       JSONObject parentObject = new JSONObject(response);
       JSONArray parentArray = parentObject.getJSONArray("data");
       staffData = gson.fromJson(parentArray.toString(), StaffResponseModel.StaffData[].class);
       visitList = new ArrayList<VisitorSignInModel>();
       visitorSignInModel visit;
       for(StaffResponseModel.StaffData staff : staffData) {
           visit = new VisitorSignInModel();
           visit.setName(staff.getName());
           visit.setId(String.valueOf(staff.getId()));
           visitList.add(visit);
       }
       setUpAutoComplete();
    } catch (JSONException e) {
           e.printStackTrace();
      }

My setUpAutoComplete function

private void setUpAutoComplete() {
        final ArrayAdapter<VisitorSignInModel> adapter = new VisitorAdapter(this, R.id.lbl_name, visitList);
        visitingStaffTextView.setAdapter(adapter);

        visitingStaffTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int index, long l) {
                String staff = adapter.getItem(index).getName().toString();
                staffSelectedId = (adapter.getItem(index).getId());
                Toast.makeText(visitorSignInActivity.this, staffSelectedId ,Toast.LENGTH_LONG).show();
            }
        });
    }

And finally i created a custom adapter called VisitorAdapter

public class VisitorAdapter extends ArrayAdapter<VisitorSignInModel> {
        Context context;
        List<VisitorSignInModel> items, tempItems, suggestions;

        public VisitorAdapter(Context context, int textViewResourceId, List<VisitorSignInModel> items) {
            super(context, textViewResourceId, items);
            this.context = context;
            this.items = items;
            tempItems = new ArrayList<VisitorSignInModel>(items); // this makes the difference.
            suggestions = new ArrayList<VisitorSignInModel>();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.row_visitor, parent, false);
            }
            VisitorSignInModel people = items.get(position);
            if (people != null) {
                TextView lblName = (TextView) view.findViewById(R.id.lbl_name);
                if (lblName != null)
                    lblName.setText(people.getName());
            }
            return view;
        }

        @Override
        public Filter getFilter() {
            return nameFilter;
        }

        /**
         * Custom Filter implementation for custom suggestions we provide.
         */
        Filter nameFilter = new Filter() {
            @Override
            public CharSequence convertResultToString(Object resultValue) {
                String str = ((VisitorSignInModel) resultValue).getName();
                return str;
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                if (constraint != null) {
                    suggestions.clear();
                    for (VisitorSignInModel people : tempItems) {
                        if (people.getName().toLowerCase().contains(constraint.toString().toLowerCase())) {
                            suggestions.add(people);
                        }
                    }
                    FilterResults filterResults = new FilterResults();
                    filterResults.values = suggestions;
                    filterResults.count = suggestions.size();
                    return filterResults;
                } else {
                    return new FilterResults();
                }
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                List<VisitorSignInModel> filterList = (ArrayList<VisitorSignInModel>) results.values;
                if (results != null && results.count > 0) {
                    visitList.clear();
                    for (VisitorSignInModel people : filterList) {
                        visitList.add(people);
                        notifyDataSetChanged();
                    }
                }
            }
        };
chirag90
  • 2,211
  • 1
  • 22
  • 37
-1

Modify your model as below:

public class StaffResponseModel { 
    public int success; 
    public String message; 
    public List<StaffData> data; 

    public static class StaffData { 
        public String name; 
        public int id; 
    } 

}

then getting data from json as below:

StaffResponseModel staffResponseModel = gson.fromJson(response, new TypeToken<StaffResponseModel>(){}.getType());

At last:

staffName = new ArrayList<String>();
for(StaffResponseModel.StaffData staff : staffResponseModel.data) {
     staffName.add(staff.name);
     staffName.add(String.valueOf(staff.id));
}
setUpAutoComplete();
  • Hi, sorry i think i didn't explain myself properly, i need to store the id value in int, and post it to server again. However i tried to do a Toast with adapter.getItem(index+1).toString(), but that shows the next name, not id. – chirag90 Mar 16 '17 at 01:03
  • Modify your model as below `public class StaffResponseModel { public int success; public String message; public List data; public static class StaffData { public String name; public int id; } }` then getting data from json as below: `staffResponseModel = gson.fromJson(response, new TypeToken(){}.getType());` – Gavin Zhuang Mar 17 '17 at 09:16
  • i have managed to solve the issue now i had to create a new custom adapter. – chirag90 Mar 17 '17 at 09:38