Samah Dawoud Samah Dawoud - 3 months ago 19
Android Question

Get checked items id from custom listview and pass them to new activity android

I'm developing an android app which has a custom listview with a checkbox. I want to pass all the checked items from one activity to another. how should I pass them? and where should I manage the checkbox (to get all the checked items) in the custom adapter or the activity?

Note: I retrieve all the data from my server using json response.

Here's my Model :

public class Groups {
public String name;
public boolean selected= false;

public String getName() {
return name;
}

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

public boolean isSelected() {
return selected;
}

public void setSelected(boolean selected) {
this.selected = selected;
}

public Groups() {
}
}


My Adapter:

public class AdapterMainActivity extends BaseAdapter{

Activity activity;
private LayoutInflater inflater;
List<Groups> groupsList;

public AdapterMainActivity(Activity activity, List<Groups> groupses) {
this.activity = activity;
this.groupsList = groupses;
}

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

@Override
public Object getItem(int position) {
return groupsList.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

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

if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_list, null);
TextView name = (TextView) convertView.findViewById(R.id.textViewName);
final CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);

final Groups groups = groupsList.get(position);
name.setText(groupsList.get(position).getName());

checkBox.setChecked(groups.selected);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
groups.selected = isChecked;
MainActivity.getInstance().updateArrayList(groupsList);
}
});


}

return convertView;
}


}

MainActivity:

public class MainActivity extends AppCompatActivity {

ListView listViewGroups;
Button buttonSentToActivity;

List<Groups> groupsList;
List<Groups> resultGroupList;
ArrayList<Boolean> areChecked;
List<String> finalArray;

private AdapterMainActivity adapterMainActivity;

static MainActivity yourActivity;

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

yourActivity = this;

groupsList= new ArrayList<Groups>();
resultGroupList= new ArrayList<Groups>();

ReadGroup(37);

adapterMainActivity = new AdapterMainActivity(this, groupsList);

listViewGroups = (ListView) findViewById(R.id.listViewGroups);
listViewGroups.setAdapter(adapterMainActivity);

buttonSentToActivity = (Button) findViewById(R.id.buttonSendTo2Activity);
buttonSentToActivity.setOnClickListener(buttonSentToActivityListener);

Log.e("Group list size ", String.valueOf(groupsList.size()));
finalArray = new ArrayList<>();
for (int i = 0; i < resultGroupList.size(); i++) {
if (resultGroupList.get(i).selected) {
finalArray.add(resultGroupList.get(i).getName());
Log.e("final array size", String.valueOf(finalArray.size()));
}
}

}
public void ReadGroup(long cid) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONArray readArray = jsonObject.getJSONArray("groups");

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

Log.e("i is: ", String.valueOf(i));
JSONObject jssonRow = readArray.getJSONObject(i);

String groupName = jssonRow.getString("name");

Groups groups = new Groups();
groups.setName(groupName);
Log.e("NAME is: ", groupName);
groupsList.add(groups);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapterMainActivity.notifyDataSetChanged();
}
};

Log.e("Client id is: ", String.valueOf(cid));
ReadGroupRequesr readGroupRequest = new ReadGroupRequesr(cid, responseListener);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(readGroupRequest);

Log.e("out of the loop", "");
}

public static MainActivity getInstance() {
return yourActivity;
}

public void updateArrayList(List<Groups> arrayList) {
this.resultGroupList = arrayList;
}

View.OnClickListener buttonSentToActivityListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
//Bundle b= new Bundle();
//b.putStringArrayList("arrayList", (ArrayList<String>) finalArray);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putStringArrayListExtra("arrayList", (ArrayList<String>) finalArray);
//intent.putExtras(b);
Log.e("final array size", String.valueOf(finalArray.size()));
startActivity(intent);
}
};

}

Answer

Here's the solution for this Question:

My adapter:

public class ChooseContactsAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
public ArrayList<Contacts> contactsList;
public CheckBox checkBoxAdapter;

public ChooseContactsAdapter(Activity activity, ArrayList<Contacts> group) {
    this.activity = activity;
    this.contactsList = group;
}

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

@Override
public Object getItem(int position) {
    return contactsList.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if (inflater == null) {
        inflater = (LayoutInflater)             activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    if (convertView == null) {

        convertView = inflater.inflate(R.layout.custom_choose_contacts_sms,
     null);

        final TextView fNAme = (TextView)   convertView.findViewById(R.id.textViewCustomSMSSelectContactFName);
        TextView LName = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactLName);

        checkBoxAdapter = (CheckBox) convertView.findViewById(R.id.checkBoxSelectContact);

        checkBoxAdapter.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                CheckBox cb = (CheckBox) view;
                Contacts contacts = (Contacts) cb.getTag();
                contacts.setSelected(cb.isChecked());

                Toast.makeText(activity.getApplicationContext(),
                        "Clicked on Checkbox: " + cb.getText() +
                                " is " + cb.isChecked(),
                        Toast.LENGTH_LONG).show();

            }
        });


        final Contacts contacts = contactsList.get(position);


        fNAme.setText(contacts.getContactFName());
        LName.setText(contacts.getContactLName());
        checkBoxAdapter.setChecked(contacts.isSelected());
        checkBoxAdapter.setTag(contacts);
    }
    return convertView;
    }
    }

In my activity I have button to go from 1 activity to the 2 activity:

    private View.OnClickListener buttonSubmitGroupListener =new      View.OnClickListener() {
    @Override
    public void onClick(View view) {
       List <Integer> contactsIDArray= new ArrayList<Integer>();
        List<Contacts> arrayOfContacts= chooseContactsAdapter.contactsList;
        for(int i=0; i< arrayOfContacts.size(); i++){
            Contacts contacts= arrayOfContacts.get(i);

            if(contacts.isSelected()==true){
                contactsIDArray.add(contacts.getContactID());
            }
        }

        for (int i = 0; i < contactsIDArray.size(); i++) {
            Log.e("Id Array size ", String.valueOf(contactsIDArray.size()));
            Log.e("Selected id ", String.valueOf(contactsIDArray.get(i)));
        }

        intent = new Intent(getApplicationContext(), SendSMSActivity.class);
        Bundle b = new Bundle();
        b.putIntegerArrayList("checkedContacts", (ArrayList<Integer>) contactsIDArray);
        intent.putExtras(b);
        startActivity(intent);
    }
};

Second Activity add this code:

    Bundle b = getIntent().getExtras();
    List<Integer> result = new ArrayList<Integer>();
    result = b.getIntegerArrayList("checkedContacts");