7

I am retrieving values from server for autocompletetextview, I am getting the list of user names along with their user ids, now what I want is when i select any username from list I want to get user id of that username.

Please have look at my code:

SearchFriendsAdapter.java

public class SearchFriendsAdapter extends ArrayAdapter<String> {

private ArrayList<SearchFriends> items;
public static SearchFriends searchFriends;
public static ArrayList<String> friends_id;

boolean iNetAvailable;
Context context = getContext();

public SearchFriendsAdapter(Activity context, String nameFilter) {
    super(context, R.layout.row_search_friend);
    items = new ArrayList<SearchFriends>();
}

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

@Override
public String getItem(int index) {

    return items.get(index).getFriend_name();

}

public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;
    if (v == null) {
        LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(R.layout.row_search_friend, null);
    }

    searchFriends = items.get(position);
    if (searchFriends != null) {

        TextView tv_friend_name = (TextView) v.findViewById(R.id.search_friend_txt_friend_name);
        TextView tv_friend_email = (TextView) v.findViewById(R.id.search_friend_txt_friend_email);
        SimpleDraweeView iv_friend_pic = (SimpleDraweeView)v.findViewById(R.id.search_friend_img_friend_pic);
        tv_friend_name.setText(searchFriends.getFriend_name());
        tv_friend_email.setText(searchFriends.getFriend_email_id());
        iv_friend_pic.setImageURI(Uri.parse(searchFriends.getFriend_profile_pic()));

    }
    return v;
}


@Override
public Filter getFilter() {
    Filter myFilter = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults filterResults = new FilterResults();

            iNetAvailable = Utility.isNetworkAvaliable(context);
                    SearchFriendsAsyncTask sf = new SearchFriendsAsyncTask();
                    if (constraint != null) {
                        List<SearchFriends> new_suggestions = sf.getParseJsonWCF(context, constraint.toString());
                        items.clear();

                        items.addAll(new_suggestions);

                        filterResults.values = items;
                        filterResults.count = items.size();
                    }
                    return filterResults;
        }

        @Override
        protected void publishResults(CharSequence contraint,
                FilterResults results) {
            if (results != null && results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    };
    return myFilter;
}

}

SearchFriendsAsyncTask.java

 public class SearchFriendsAsyncTask {


public SearchFriendsAsyncTask() {
    super();
}

public List<SearchFriends> getParseJsonWCF(Context mContext, String sName){
    List<SearchFriends> ListData = new ArrayList<SearchFriends>();

    SearchFriendsModel searchFriendsModel = null;

    String webUrl = Constant.URL_SEARCH_FRIEND;

    try{
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair(Constant.USER_ID, 
                Utility.getAppPrefString(mContext ,Constant.USER_ID)));
        nameValuePairs
                .add(new BasicNameValuePair("name", sName));

        String response = Utility.postRequest(webUrl, nameValuePairs);

        JSONObject jObject = new JSONObject(response);
        Log.v("SEARCH FRIENDS RESPONSE : ", jObject.toString());


        searchFriendsModel = (SearchFriendsModel) new Gson().fromJson(
                jObject.toString(), SearchFriendsModel.class);

    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    return searchFriendsModel.getFriends(); 


    }

}

SearchModel.java

public class SearchFriends {

String friend_user_id;
String friend_name;
String friend_email_id;
String friend_profile_pic;


public SearchFriends(String friend_user_id, String friend_name,
        String friend_email_id, String friend_profile_pic) {
    super();
    this.friend_user_id = friend_user_id;
    this.friend_name = friend_name;
    this.friend_email_id = friend_email_id;
    this.friend_profile_pic = friend_profile_pic;
}


public String getFriend_user_id() {
    return friend_user_id;
}
public void setFriend_user_id(String friend_user_id) {
    this.friend_user_id = friend_user_id;
}
public String getFriend_name() {
    return friend_name;
}
public void setFriend_name(String friend_name) {
    this.friend_name = friend_name;
}
public String getFriend_email_id() {
    return friend_email_id;
}
public void setFriend_email_id(String friend_email_id) {
    this.friend_email_id = friend_email_id;
}
public String getFriend_profile_pic() {
    return friend_profile_pic;
}
public void setFriend_profile_pic(String friend_profile_pic) {
    this.friend_profile_pic = friend_profile_pic;
}

}

SearchFriendsModel.java

public class SearchFriendsModel {

private String response;
private String message;
private List<SearchFriends> friends;


public String getResponse() {
    return response;
}
public void setResponse(String response) {
    this.response = response;
}
public String getMessage() {
    return message;
}
public void setMessage(String message) {
    this.message = message;
}
public List<SearchFriends> getFriends() {
    return friends;
}
public void setFriends(List<SearchFriends> friends) {
    this.friends = friends;
}

}

Here i am setting the adapter

et_search.setAdapter(new SearchFriendsAdapter(this, et_search.getText().toString()));
    et_search.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View arg1, int position,
                long arg3) {
            // TODO Auto-generated method stub
            SearchFriendsAdapter adapter = ((SearchFriendsAdapter)
                    et_search.getAdapter());
            String friend_id = ((SearchFriends)adapter
                    .getItem(position)).getFriend_user_id();

        }
    });

while I am trying to get user_id as above it gives me error "Cannot cast from String to SearchFriends"

Please help me to achieve what I want. Thanks in advance.

Aditi Parikh
  • 1,528
  • 3
  • 12
  • 33
Rajesh Panchal
  • 1,042
  • 3
  • 18
  • 38
  • 2
    may i know, why question has been down voted ? at least leave comment what's wrong with the question so that one can learn it and will not repeat it in future. – Rajesh Panchal Oct 13 '15 at 05:04
  • what I understand from these too many downvotes is, share only relevant code, this is too much code to dive in – Syed Nazar Muhammad Oct 13 '15 at 05:09
  • the error you mentioned can you give the line where it getting this error – Syed Nazar Muhammad Oct 13 '15 at 05:10
  • @SyedNazarMuhammad : i just wanted to make sure that if any one is helping then he may want to check full code that's why i posted full code. and these people are not helping instead down voting the question, so that others will not help also. – Rajesh Panchal Oct 13 '15 at 05:12
  • @SyedNazarMuhammad : the error is inside et_search.setOnItemClickListener – Rajesh Panchal Oct 13 '15 at 05:13
  • no if any one want to see your full code he will ask you to update for example please show the code of Adapter class too, but initially only share the relevant & small code as much as possible – Syed Nazar Muhammad Oct 13 '15 at 05:13
  • @SyedNazarMuhammad: Ok from next time i'll not repeat this and thank you for explainig me this. :) Others should also do the same but unfortunately they are not doing. – Rajesh Panchal Oct 13 '15 at 05:15
  • @SyedNazarMuhammad : actually i need to display image and name so that custom adapter is required, BTW i got the solution. thank you for your help :) and if you think this question can be useful for other then please up vote it. – Rajesh Panchal Oct 13 '15 at 05:59
  • see [here](http://stackoverflow.com/a/19860624/2252830) how easy you can do that without any custom Adapters – pskink Oct 13 '15 at 06:05
  • Good to see you got the solution. Next time don't make the Helpers to hesitate to dive in your code :) – Syed Nazar Muhammad Oct 13 '15 at 06:16
  • Possible duplicate of [How to get correct ID of AutoCompleteTextView adapter](http://stackoverflow.com/questions/11522592/how-to-get-correct-id-of-autocompletetextview-adapter) – Shabbir Dhangot Oct 13 '15 at 07:18
  • Thanks for complete example :v – Tineo Sep 26 '16 at 04:46

4 Answers4

6

Change this in adapter

@Override
public SearchFriends getItem(int index) {

    return items.get(index);

}


et_search.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View arg1, int position,
                long arg3) {
            // TODO Auto-generated method stub
            SearchFriends freindPOJO= adapter
                    .getItem(position);
String friends_id = freindPOJO.getFriend_user_id()

        }
    });
Narendra Kumar
  • 531
  • 5
  • 16
  • i got it working, thank you for your help :) and if you think this question can be useful for other then please up vote it. – Rajesh Panchal Oct 13 '15 at 06:00
  • its giving position of the list shown, so position did not match with original data. The real solution here: spapas.github.io/2019/04/05/android-custom-filter-adapter. You need to expose the FilterResult values. – Susanta Feb 12 '20 at 09:31
5

Adapter you are using for et_search using ArrayList<SearchFriends>

and you are trying to get friend_id which is string or int and you are casting it to SearchFriends which is not possible.

if you want SearchFriends object then use like this

SearchFriends object = (SearchFriends)adapter.getItem(position);

Sorry i have not check you adapter

here is the mistake you are returning string here so you cannot get SearchFriends

@Override
public String getItem(int index) {

    return items.get(index).getFriend_name();

}

So i will say do this and you are good to go.

@Override
public SearchFriends getItem(int index) {
        return items.get(index);    
}
shreyash mashru
  • 301
  • 2
  • 9
  • it gives the same error "Cannot cast from String to SearchFriends" – Rajesh Panchal Oct 13 '15 at 05:30
  • i tried it, it gives the error "The return type is incompatible with ArrayAdapter.getItem(int)" – Rajesh Panchal Oct 13 '15 at 05:38
  • Please use below link and learn how to use ArrayAdapter or make custom adapter. [link](http://stackoverflow.com/questions/2265661/how-to-use-arrayadaptermyclass) – shreyash mashru Oct 13 '15 at 05:42
  • hey i got id but one new problem is there, while i am selecting any name it sets the value as "com.example.imp.models.SearchFriends@41fffa58" – Rajesh Panchal Oct 13 '15 at 05:47
  • got it working, thank you for your help :) and if you think this question can be useful for other then please up vote it. – Rajesh Panchal Oct 13 '15 at 06:00
  • its giving position of list shown, so position did not match with original data. The real solution here: spapas.github.io/2019/04/05/android-custom-filter-adapter. You need to expose the FilterResult values. – Susanta Feb 12 '20 at 09:31
  • https://stackoverflow.com/questions/61790242/spinner-data-from-server can any one help me out with my problem @shreyashmashru – Sunny May 14 '20 at 06:28
2

Narendra Kumar's answer works fine.

This is a Kotlin version example, for an AutoCompleteTextView with id atvUser and an ArrayAdapter based on an ArrayList of User objects:

atvUser.onItemClickListener = AdapterView.OnItemClickListener {
    parent, _, position, _ ->
    userId = (parent.getItemAtPosition(position) as User).id
}

I assigned the adapter doing this:

atvUser.setAdapter(arrayAdapter(myData.users))

It works because I have an extension function declared in a separated file:

fun <T> Context.arrayAdapter(objects: List<T>): ArrayAdapter<T> {
    return ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, objects)
}

Hope it helps.

JCarlosR
  • 1,299
  • 3
  • 14
  • 26
0

Just call your adapter.getItem(position) and you will get the output you want. For example skillLevelAdapter.getItem(position).getName() saved my entire day.