在arraylist中保存选定的列表视图项

时间:2016-04-19 12:13:43

标签: android listview arraylist pojo

我有一个listview,显示来自webservice的名称,在json web响应中也有user_id。我使用pojo作为getter和setter of name以及user_id' s。我想过滤所选列表视图的名称及其user_id,并将user_id保存在arraylist中。

的活动:

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; }


}

1 个答案:

答案 0 :(得分:0)

使用SparseBooleanArray.get返回一个布尔值

您需要检查列表中的每个位置

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 */
}