0

I have a listview which display names from webservice and in the json web response there is also user_id. I used a pojo for getter and setter of names and user_id's. I want to filter the selected listview's names and their user_id's and save the user_id's in an arraylist.

Activity:

public class InvitedMembers extends AppCompatActivity{


    Button invite;
    private ListView mListView;
    private GridItem newItem;
    private ListAdapter mListAdapter;
    private ArrayList<GridItem> mGridData;
    private static final String FETCH_FOLLOWING = "http://www.example.com/api/member/get-followings/", KEY_USERID = "user_id";


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


        invite  = (Button)findViewById(R.id.btn_invite);

        mListView = (ListView)findViewById(R.id.list_view);
        mGridData = new ArrayList<>();
        mListAdapter = new ListAdapter(InvitedMembers.this, R.layout.listrow, mGridData);
        mListView.setAdapter(mListAdapter);
        mListView.setEmptyView(findViewById(R.id.empty));
        mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);


        loadfollowinglist();

        invite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

               /* SparseBooleanArray checked = mListView.getCheckedItemPositions();

                for (int i = 0; i < mListView.getAdapter().getCount(); i++) {
                    if (checked.get(i)) {
                        ArrayList<String> newList = new ArrayList<String>();
                    }
                } */


                  // Here I want to fetch the user_id's of the selected names.


            }
        });
    }



    private void loadfollowinglist(){
        StringRequest stringRequest = new StringRequest(Request.Method.POST, FETCH_FOLLOWING,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            JSONObject jObj = new JSONObject(response);

                            System.out.println(jObj);

                            String status = jObj.getString("status");

                            // Now check status value
                            if (status.equals("0")) {
                                Toast.makeText(getApplicationContext(), "There was some error! Please try again.", Toast.LENGTH_LONG).show();
                            } else if (status.equals("1")) {

                                JSONArray result = jObj.getJSONArray("result");
                                for (int i = 0; i < result.length(); i++) {
                                    JSONObject json_data = result.getJSONObject(i);
                                    String name = json_data.getString("name");
                                    String regtdemail = json_data.getString("username");
                                    String user_id = json_data.getString("user_id");

                                    newItem = new GridItem();

                                    newItem.setName(name);
                                    newItem.setRegtdEmail(regtdemail);
                                    newItem.setUserId(user_id);
                                    if(json_data.has("profile_picture")){

                                        newItem.setImage(json_data.getString("profile_picture"));

                                    }else{

                                        Uri path = Uri.parse("android.resource://com.example.sam.fitlincevent/" + R.drawable.default_profile);
                                        String image_def = path.toString();
                                        newItem.setImage(image_def);

                                    }


                                    mGridData.add(newItem);
                                }


                                mListAdapter.notifyDataSetChanged();


                            } else {
                                // Error in login. Get the error message
                                String errorMsg = jObj.getString("error_msg");
                                Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
                            }
                        } catch (JSONException e) {
                            // JSON error
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(KEY_USERID, "1"); //get user_id from SQLite database.
                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);
    }
}

Listadapter:

public class ListAdapter extends ArrayAdapter<GridItem> {



    private Context mContext;
    int resource;
    private ArrayList<GridItem> mListData = new ArrayList<GridItem>();

    public ListAdapter(Context mContext, int resource, ArrayList<GridItem> mListData) {
        super(mContext, resource, mListData);
        this.resource = resource;
        this.mContext = mContext;
        this.mListData = mListData;
    }

    public void setListData(ArrayList<GridItem> mListData) {
        this.mListData = mListData;
        notifyDataSetChanged();
    }




    @Override
    public GridItem getItem(int position) {
        return super.getItem(position);
    }



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

        ViewHolder holder;
        if (v == null) {
            holder = new ViewHolder();
            LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();

            v = inflater.inflate(resource, parent, false);
            holder.image = (ImageView) v.findViewById(R.id.item_image);
            holder.name = (TextView) v.findViewById(R.id.item_name);
            holder.regtdemail = (TextView) v.findViewById(R.id.item_regtdemail);
            holder.checkBox = (CheckBox)v.findViewById(R.id.checkBox);


            v.setTag(holder);

        } else {
            holder = (ViewHolder) v.getTag();
        }

        GridItem item = mListData.get(position);
        Picasso.with(mContext)
                .load(item.getImage())
                .placeholder(R.drawable.placeholder)
                .fit()
                .into(holder.image);
        holder.name.setText(item.getName());
        holder.regtdemail.setText(item.getRegtdEmail());




        return v;
    }

    class ViewHolder {
        ImageView image;
        TextView name, regtdemail;
        CheckBox checkBox;
    }

}

Pojo:

public class GridItem {
    private String nameUrls, imageUrls, userIdUrls, regtdEmailUrls, sportsIdUrls;
    private boolean selected;

    public GridItem() {
        super();
    }

    public String getImage() {
        return imageUrls;
    }

    public void setImage(String imageUrls) {
        this.imageUrls = imageUrls;
    }

    public String getName() {
        return nameUrls;
    }

    public void setName(String nameUrls) {
        this.nameUrls = nameUrls;
    }


    public String getRegtdEmail(){
        return regtdEmailUrls;
    }

    public void setRegtdEmail(String regtdEmailUrls){
        this.regtdEmailUrls = regtdEmailUrls;
    }


    public String getUserId(){
        return userIdUrls;
    }

    public void setUserId(String userIdUrls){
        this.userIdUrls = userIdUrls;
    }

    public String getSportsId() { return sportsIdUrls; }

    public void setSportsId(String sportsIdUrls) { this.sportsIdUrls = sportsIdUrls; }


}
Tom Sabel
  • 3,935
  • 33
  • 45
Ritu
  • 1
  • 1
  • create getter setter for selected value that you have defined in your pojo class and set it's value when you select checkbox – Vivek Mishra Apr 19 '16 at 12:15
  • Thanks for the quick reply. Can you please give me some code to explain how? @Vivek – Ritu Apr 19 '16 at 12:19
  • There are many things missing from your code right now so I can tell you what to do but you have to code yourself – Vivek Mishra Apr 19 '16 at 12:21
  • First thing create getter setter for your boolean variable and then provide a listener for your checkbox with which you will get which item is checked and then setSelected value for that position to true. – Vivek Mishra Apr 19 '16 at 12:23
  • Okay. Let's suppose I use this below link to check for the selected checkbox. But how to get the user_id in respect to selected checkbox? link: http://lalit3686.blogspot.in/2012/06/today-i-am-going-to-show-how-to-deal.html – Ritu Apr 19 '16 at 12:32
  • from the link you posted implement checkchangedlistener too – Vivek Mishra Apr 19 '16 at 12:33
  • Yes, I added the checkedchangelistener in adapter. But I don't want to implement listview.onItemClick. I want to get the selected item's user_id on button click. – Ritu Apr 19 '16 at 12:42
  • that's not required , if you don't want then don't use it – Vivek Mishra Apr 19 '16 at 12:45
  • Ok. So, after I implemented the checkBox.setCheckedChangeListener, how to get the selected item's user_id on button click in activity? – Ritu Apr 19 '16 at 12:56
  • first do this `mListData.get(position).isChecked()` and if it is checked then `mListData.get(position).getUserId()` – Vivek Mishra Apr 19 '16 at 12:58
  • What's mListData here? – Ritu Apr 19 '16 at 13:03
  • 1
    You don't know about your own code?? `mListData` is your ArrayList – Vivek Mishra Apr 19 '16 at 13:05
  • Actually its mGridData. And `if(mGridData.get(position).isChecked())` in this code 'position cannot be resolved'. Since its button click there is no position here like listview.onItemClick – Ritu Apr 19 '16 at 13:11

1 Answers1

0

Use SparseBooleanArray.get returns a boolean

you need to check it for each position in your list

int length = listView.getCount();
SparseBooleanArray checked = listView.getCheckedItemPositions();
for (int i = 0; i < length; i++)
if (checked.get(i)) {
String item = list.get(i);

/* do your code with the checked item */
}
Ramkumar.M
  • 681
  • 6
  • 21