Multiple choice listview not showing all objects - android

I am following a tutorial about multiple choice listview in android.
When executing the app, the listview shows some items, not all of them. After clicking on the listview, it shows all items.
I want to know where is the reason of that issue.
This is the code for MainActivity class:
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
FloatingActionButton fab;
ListView list;
TextView txt_menu;
String dipilih;
private static final String TAG = MainActivity.class.getSimpleName();
Adapter adapter;
ProgressDialog pDialog;
List<Data> itemList = new ArrayList<Data>();
// Sesuaikan dengan IP Address PC/LAptop atau ip emulator bawaan android 10.0.2.2
private static String url = "https://.../test/menu.php";
public static final String TAG_NAMA = "nama";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab = (FloatingActionButton) findViewById(R.id.fab);
list = (ListView) findViewById(R.id.list_menu);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (Data hold : adapter.getAllData()) {
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getMenu();
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(dipilih);
}
});
callVolley();
adapter = new Adapter(this, (ArrayList<Data>) itemList);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
adapter.setCheckBox(position);
}
});
}
private void formSubmit(String hasil){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.form_submit, null);
dialog.setView(dialogView);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setTitle("Menu Yang Dipilih");
dialog.setCancelable(true);
txt_menu = (TextView) dialogView.findViewById(R.id.txt_menu);
txt_menu.setText(hasil);
dialog.setNeutralButton("CLOSE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
}
private void callVolley(){
itemList.clear();
// menapilkan dialog loading
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
showDialog();
// membuat request JSON
JsonArrayRequest jArr = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hideDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Data item = new Data();
item.setMenu(obj.getString(TAG_NAMA));
// menambah item ke array
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifikasi adanya perubahan data pada adapter
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideDialog();
}
});
// menambah request ke request queue
AppController.getInstance().addToRequestQueue(jArr);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
And this is the Adapter class:
public class Adapter extends BaseAdapter {
private Context activity;
private ArrayList<Data> data;
private static LayoutInflater inflater = null;
private View vi;
private ViewHolder viewHolder;
public Adapter(Context context, ArrayList<Data> items) {
this.activity = context;
this.data = items;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
vi = view;
final int pos = position;
Data items = data.get(pos);
if(view == null) {
vi = inflater.inflate(R.layout.list_row, null);
viewHolder = new ViewHolder();
viewHolder.checkBox = (CheckBox) vi.findViewById(R.id.cb);
viewHolder.menu = (TextView) vi.findViewById(R.id.nama_menu);
vi.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
viewHolder.menu.setText(items.getMenu());
}
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
return vi;
}
public ArrayList<Data> getAllData(){
return data;
}
public void setCheckBox(int position){
Data items = data.get(position);
items.setCheckbox(!items.isCheckbox());
notifyDataSetChanged();
}
public class ViewHolder{
TextView menu;
CheckBox checkBox;
}
}
If you need other code parts to detect the problem, please let me know.
EDIT
First launch
After clicking on the listview

The problem is this bit of your code in your adapter's getView() callback:
if(view == null) {
...
}else {
...
viewHolder.menu.setText(items.getMenu());
}
What's happening here is that you're only caling setText() when the item view is recycled by the ListView. The reason everything shows up after you click a checkbox is that the ListView rebinds everything when you call notifyDataSetChanged().
You should call this method outside of the if/else statement so that it is executed every time.
if(view == null) {
...
}else {
...
}
viewHolder.menu.setText(items.getMenu());

I think the issue you are having is coming from the getView() method in your Adapter class.
Since you are using a ViewHolder to recycle objects you are first checking if the exist first before creating them if(view == null). But, you are only creating them and not assigning the TextView objects a String value. You only do that once the object has already been created. So, when you click on an item, you are calling notifyDataSetChanged causing the list to be updated. Then the values are set in the `TextView.
So try this instead: put the line viewHolder.menu.setText(items.getMenu()); outside the conditional statement:
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
vi = view;
final int pos = position;
Data items = data.get(pos);
if(view == null) {
vi = inflater.inflate(R.layout.list_row, null);
viewHolder = new ViewHolder();
viewHolder.checkBox = (CheckBox) vi.findViewById(R.id.cb);
viewHolder.menu = (TextView) vi.findViewById(R.id.nama_menu);
vi.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.menu.setText(items.getMenu());
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
return vi;
}

try this once
adapter = new Adapter(this, (ArrayList) itemList);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
adapter.setCheckBox(position);
}
});
list.setAdapter(adapter);
}
set adapter at the end

Related

Listview items with checkbox checked at start

I have a fragment with a listView.
The view is populated from a remote received JSON array as follows:
private void callVolley(){
SharedPreferences prefs3 =
getActivity().getSharedPreferences(MIEXAMEN, Context.MODE_PRIVATE);
final String id_materia= "42";
final String num_examen= "787878";
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Cargando temas de la materia seleccionada...");
showDialog();
JsonArrayRequest jArr = new JsonArrayRequest(url+"?id="+id_materia, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hideDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Data item = new Data();
item.setMenu(obj.getString(TAG_NOMBRE));
item.setId(obj.getString(TAG_ID));
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
// list.invalidateViews();
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideDialog();
}
});
AppController.getInstance().addToRequestQueue(jArr);
}
Then I add programmatically a checkbox to each list item.
This is the adapter:
public class Adapter extends BaseAdapter {
private Context activity;
private ArrayList<Data> data;
private static LayoutInflater inflater = null;
private View vi;
private ViewHolder viewHolder;
public Adapter(Context context, ArrayList<Data> items) {
this.activity = context;
this.data = items;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
vi = view;
final int pos = position;
Data items = data.get(pos);
if(view == null) {
vi = inflater.inflate(R.layout.list_row, null);
viewHolder = new ViewHolder();
viewHolder.checkBox = (CheckBox) vi.findViewById(R.id.cb);
viewHolder.menu = (TextView) vi.findViewById(R.id.nama_menu);
vi.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.menu.setText(items.getMenu());
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
return vi;
}
public ArrayList<Data> getAllData(){
return data;
}
public void setCheckBox(int position){
Data items = data.get(position);
items.setCheckbox(!items.isCheckbox());
notifyDataSetChanged();
}
public class ViewHolder{
TextView menu;
CheckBox checkBox;
}
}
At start I need all checkboxes to be checked.
Then the user can check/uncheck the desired items.
On the fragment there is a button that reads all items checkbox states.
What should I implement to put all items in status checked so that on button clicked all items are recognized as checked?
This is a screenshot at start with all items unchecked:
EDIT
Code for the button onClickListener in the fragment:
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkbox = "";
checkbox_id = "";
for (Data hold : adapter.getAllData()) {
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getMenu();
checkbox_id += hold.getId()+",";
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
String preguntas = checkbox_id;
mPref = getActivity().getSharedPreferences(MIEXAMEN, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mPref.edit();
editor.putString("preguntas_numero_string",preguntas);
editor.putString("preguntas_string",dipilih);
Log.d("seleccion","seleccion preguntas "+preguntas);
Log.d("seleccion","seleccion dipilih "+dipilih);
editor.apply();
} else {
dipilih = "No has seleccionado ningĂșn tema.";
}
formSubmit(dipilih);
}
});
Do the following changes:
When you are adding Data to the list of Data.
Data item = new Data();
item.setMenu(obj.getString(TAG_NOMBRE));
item.setId(obj.getString(TAG_ID));
item.setCheckbox(true)
itemList.add(item);
This will initially make the checkbox checked.
Edit:
Update your xml layout. in your CheckBox put this attribute.
android:clickable="false"
Update your list setOnItemClickListener
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adapter.setCheckBox(position);
}
});
Try replacing with the below code
viewHolder.checkBox.setChecked(true);
instead of
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
Use this. It should work. -
Initially this -
viewHolder.checkBox.setChecked(true);
Then
viewHolder.checkBox.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton
buttonView,boolean isChecked) {
if(isChecked){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
}
}
);

Populating a ListView with an ArrayList - ListView doesn't populate

I want to populate a ListView (with checkbox) with an ArrayList.
The ArrayList gets data from a server and contains my Shop's class objects, and it's filled in my function onPostExecute.
I'm trying to populate listview with shop name but not populating! Any suggestions?
onPostExecute
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (processDialog.isShowing()) {
processDialog.dismiss();
}
if (success == 1) {
if (null != restulJsonArray) {
for (int i = 0; i < restulJsonArray.length(); i++) {
try {
JSONObject jsonObject = restulJsonArray.getJSONObject(i);
favouriteShopsList.add(new Shop(jsonObject.getInt("id"),jsonObject.getString("azienda"), false));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
I checked and the list is not empty.
In my onCreate function, i execute the AsyncTask to get data from server and then i try to populate my ListView with a custom adapter. This is my onCreate function:
My Activity
public class NearestShopActivity extends AppCompatActivity{
private ProgressDialog processDialog;
private JSONArray restulJsonArray;
private int success = 0;
private Context context;
private ArrayList<Shop> favouriteShopsList = new ArrayList<Shop>();
private ArrayAdapter<Shop> listAdapter;
private ListView listView;
private CheckBox checkBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearest_shop);
context = NearestShopActivity.this;
new ServiceStubAsyncTask(this, this).execute();
listView = (ListView) findViewById(R.id.activityNearestShopList);
listAdapter = new ShopArrayAdapter(this, favouriteShopsList);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View item, int position, long id){
Shop shop = listAdapter.getItem(position);
shop.toggleChecked();
ShopViewHolder viewHolder = (ShopViewHolder) item.getTag();
viewHolder.getCheckBox().setChecked(shop.isChecked());
}
});
final Button continueBtn = (Button) findViewById(R.id.activityNearestShopContinueBtn);
continueBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
for(int i=0; i<listAdapter.getCount(); i++){
Shop shop = listAdapter.getItem(i);
if(shop.isChecked()){
Toast.makeText(context, "Checked: " + shop.getAzienda(), Toast.LENGTH_LONG).show();
}
}
}
});
}
private class ServiceStubAsyncTask extends AsyncTask<Void, Void, Void> {...}
}
I also post my ShopArrayAdapter class:
private static class ShopArrayAdapter extends ArrayAdapter<Shop>{
private LayoutInflater inflater;
public ShopArrayAdapter(Context context, List<Shop> favouriteShopsList) {
super(context, R.layout.activity_nearest_shop_item, R.id.activityNearestShopItem, favouriteShopsList);
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
Shop shop = (Shop) this.getItem(position);
CheckBox checkBox;
TextView textView;
if(convertView == null){
convertView = inflater.inflate(R.layout.activity_nearest_shop_item, null);
textView = (TextView) convertView.findViewById(R.id.activityNearestShopItem);
checkBox = (CheckBox) convertView.findViewById(R.id.activityNearestShopCheckbox);
convertView.setTag(new ShopViewHolder(textView, checkBox));
checkBox.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
CheckBox cb = (CheckBox) v;
Shop shop = (Shop) cb.getTag();
shop.setChecked(cb.isChecked());
}
});
}else{
ShopViewHolder viewHolder = (ShopViewHolder) convertView.getTag();
checkBox = viewHolder.getCheckBox();
textView = viewHolder.getTextView();
}
checkBox.setTag(shop);
checkBox.setChecked(shop.isChecked());
textView.setText(shop.getAzienda());
return convertView;
}
}
Your adapter doesn't know you've added new data here:
favouriteShopsList.add(new Shop(jsonObject.getInt("id"),jsonObject.getString("azienda"), false));
try calling notifydatasetchanged() after you've added new data:
listAdapter.notifyDataSetChanged()

Listview is not updating after SwipeRefreshLayout

I have code to show listview from my server, but when I update the data from server and refresh it in my app, the listview still getting the old data, and after several minutes when I open the app again, it updated the new data that I updated before.
My Main Fragment
public class DosenFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
ListView list;
SwipeRefreshLayout swipe;
List<Dosen> itemList = new ArrayList<>();
AdapterDosen adapter;
private static final String TAG = DosenFragment.class.getSimpleName();
private static String url_select = Server.URL + "select.php";
public static final String TAG_ID_DOSEN = "id_dosen";
public static final String TAG_NAME = "name";
public static final String TAG_STATUS = "status";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.matkul_list, container, false);
swipe = (SwipeRefreshLayout) v.findViewById(R.id.swipe_refresh_layout);
list = (ListView) v.findViewById(R.id.list);
adapter = new AdapterDosen(getActivity(), itemList);
list.setAdapter(adapter);
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
itemList.clear();
adapter.notifyDataSetChanged();
callVolley();
}
});
return v;
}
#Override
public void onRefresh() {
itemList.clear();
adapter.notifyDataSetChanged();
callVolley();
}
private void callVolley() {
swipe.setRefreshing(true);
JsonArrayRequest jArr = new JsonArrayRequest(url_select, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Dosen item = new Dosen();
item.setId_dosen(obj.getString(TAG_ID_DOSEN));
item.setName(obj.getString(TAG_NAME));
item.setAlamat(obj.getString(TAG_STATUS));
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
AppController.getInstance().addToRequestQueue(jArr);
}
}
I have tried to do something with itemList.clear(); and adapter.notifyDataSetChanged(); but nothing change.
My Main Adapter
public class AdapterDosen extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Dosen> items;
public AdapterDosen(Activity activity, List<Dosen> items) {
this.activity = activity;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int location) {
return items.get(location);
}
#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.list_row, null);
Dosen data = items.get(position);
TextView id = (TextView) convertView.findViewById(R.id.id);
TextView name = (TextView) convertView.findViewById(R.id.nama);
TextView alamat = (TextView) convertView.findViewById(R.id.alamat);
id.setText(data.getId_dosen());
name.setText(data.getName());
alamat.setText(data.getAlamat());
return convertView;
}
}
I'm sorry for my bad english.
Please help.
try this , add this method in your adatper
public void updateList(List<Dosen> newlist) {
items.clear();
items.addAll(newlist);
this.notifyDataSetChanged();
}
and in callVolley() method , replace this
adapter.notifyDataSetChanged();
with
adapter.updateList();
Hope this helps
Use the below Code...
/* Within the RecyclerView.Adapter class */
// Clean all elements of the recycler
public void clear() {
items.clear();
notifyDataSetChanged();
}
// Add a list of items -- change to type used
public void addAll(List<Dosen> newlist) {
items.addAll(newlist);
notifyDataSetChanged();
}
callvolly() method inside.
adapter.clear();
adapter.addAll(item);
public void onRefresh() {
callVolley();
}
please try this code i have changed something it will work fine
public class AdapterDosen extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Dosen> items;
public AdapterDosen(Activity activity, List<Dosen> items) {
this.activity = activity;
this.items = items;
}
public void setData(List<Dosen> items){
this.items = items
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int location) {
return items.get(location);
}
#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.list_row, null);
Dosen data = items.get(position);
TextView id = (TextView) convertView.findViewById(R.id.id);
TextView name = (TextView) convertView.findViewById(R.id.nama);
TextView alamat = (TextView) convertView.findViewById(R.id.alamat);
id.setText(data.getId_dosen());
name.setText(data.getName());
alamat.setText(data.getAlamat());
return convertView;
}
}
public class DosenFragment extends Fragment implements
SwipeRefreshLayout.OnRefreshListener {
ListView list;
SwipeRefreshLayout swipe;
List<Dosen> itemList = new ArrayList<>();
AdapterDosen adapter;
private static final String TAG = DosenFragment.class.getSimpleName();
private static String url_select = Server.URL + "select.php";
public static final String TAG_ID_DOSEN = "id_dosen";
public static final String TAG_NAME = "name";
public static final String TAG_STATUS = "status";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.matkul_list, container, false);
swipe = (SwipeRefreshLayout)
v.findViewById(R.id.swipe_refresh_layout);
list = (ListView) v.findViewById(R.id.list);
adapter = new AdapterDosen(getActivity(), itemList);
list.setAdapter(adapter);
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
itemList.clear();
adapter.notifyDataSetChanged();
callVolley();
}
});
return v;
}
#Override
public void onRefresh() {
//itemList.clear();
//adapter.notifyDataSetChanged();
callVolley();
}
private void callVolley() {
swipe.setRefreshing(true);
JsonArrayRequest jArr = new JsonArrayRequest(url_select, new
Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
itemList .clear();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj =
response.getJSONObject(i);
Dosen item = new Dosen();
item.setId_dosen(obj.getString(TAG_ID_DOSEN));
item.setName(obj.getString(TAG_NAME));
item.setAlamat(obj.getString(TAG_STATUS));
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.setData(itemList );
adapter.notifyDataSetChanged();
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
AppController.getInstance().addToRequestQueue(jArr);
}

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);
}
};
}
At the very first, manage your checkboxes :
In your activity class add a boolean array or arraylist having size same as your list array size and initialize it with all value as false initially :
String[] titlesArray;
ArrayList<Boolean> arrChecked;
// initialize arrChecked boolean array and add checkbox value as false initially for each item of listview
arrChecked = new ArrayList<Boolean>();
for (int i = 0; i < titles.size(); i++) {
arrChecked.add(false);
}
Now replace your adapter class with this :
class VivzAdapter extends ArrayAdapter<String> implements OnCheckedChangeListener {
Context context;
int[] images;
String[] titlesArray, descrptionArray;
List<Integer> positions = new ArrayList<Integer>();
ArrayList<Boolean> arrChecked;
VivzAdapter(Context context, String[] titles, int[] images, String[] description, ArrayList<Boolean> arrChecked) {
super(context, R.layout.single_row, R.id.textView1, titles);
this.context = context;
this.images = images;
this.titlesArray = titles;
this.descrptionArray = description;
this.arrChecked = arrChecked;
}
class MyViewHolder {
ImageView myImage;
TextView myTitle;
TextView myDescription;
CheckBox box;
MyViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.imageView1);
myTitle = (TextView) v.findViewById(R.id.textView1);
myDescription = (TextView) v.findViewById(R.id.textView2);
box = (CheckBox) v.findViewById(R.id.checkBox1);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder holder = null;
if (row == null) {
// 1.Âștime
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//row contem RelativeLayout(root) em single_row.xml
row = inflater.inflate(R.layout.single_row, parent, false);
holder = new MyViewHolder(row);
row.setTag(holder);
//Log.d("VIVZ", "Creating a new Row");
} else {
//reciclamos aqui, qeremos usar antigo objecto holder
holder = (MyViewHolder) row.getTag();
//Log.d("VIVZ", "Recycling stuff");
}
holder.myImage.setImageResource(images[position]);
holder.myTitle.setText(titlesArray[position]);
holder.myDescription.setText(descrptionArray[position]);
//set position as id
holder.box.setId(position);
//set onClickListener of checkbox rather than onCheckedChangeListener
holder.box.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
if (arrChecked.get(id)) {
//if checked, make it unchecked
arrChecked.set(id, false);
} else {
//if unchecked, make it checked
arrChecked.set(id, true);
}
}
});
//set the value of each checkbox from arrChecked boolean array
holder.box.setChecked(arrChecked.get(position));
return row;
}
}
After that, implement click listener of send button say btnSend button (I am considering that you are sending your data from one activity to another activity on click of send button) :
btnSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<String> arrTempList = new ArrayList();
for(int i=0; i<titles.size(); i++){
if(arrChecked.get(i) == true){
arrTempList.add(titles[i]);
}
}
// here you can send your arrTempList which is having checked items only
}
});
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");

ListView click show/hide all check box

I am having a listview and it has one checkbox and two textfields , i would like to change check box visibility properties from listview on click funtion, i am able to change the properties from inside the getView funtion but i want it from listview click. Help me find a solution
public class HelpList extends Fragment {
amfFunctions amf;
MyCustomAdapter dataAdapter = null;
Database_Contact contact = new Database_Contact();
DBHelper mydb = new DBHelper(getActivity());
public static final int PICK_CONTACT = 1;
public String user_phone_number;
public String buddyName;
public String buddyNum;
LayoutInflater vi;
View v ;
Fragment fragment = null;
Button myAddButton,myDelButton;
int selected = 0;
Boolean isInternetPresent = false;
ConnectionDetector cd;
ArrayList<Database_Contact> selectedList = new ArrayList<>();
Database_Contact addcontacts = new Database_Contact();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.activity_helplist, container, false);
// Inflate the layout for this fragment
displayListView();
cd = new ConnectionDetector(getActivity());
myDelButton = (Button)v. findViewById(R.id.deleteContact);
myDelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
DeleteContact();
}
else{
Toast.makeText(getActivity(),
getString(R.string.nointernet), Toast.LENGTH_SHORT).show();
}
}
});
Constants.i = 0;
myAddButton = (Button)v. findViewById(R.id.Addanother);
myAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
Log.e("Myaddbutton text ", (String) myAddButton.getText());
if (isInternetPresent) {
if (myAddButton.getText().equals("Close")){
Toast.makeText(getActivity(),
getString(R.string.click_to_close), Toast.LENGTH_SHORT).show();
}
else{
AddContact();
}
}
else{
Toast.makeText(getActivity(),
getString(R.string.nointernet), Toast.LENGTH_LONG).show();
}
}
});
return v;
}
private void displayListView() {
mydb = new DBHelper(getActivity());
ArrayList<Database_Contact> contactlist = (ArrayList<Database_Contact>)
mydb.getAllDatabase_Contacts();
Collections.sort(contactlist, new Comparator<Database_Contact>() {
#Override
public int compare(Database_Contact lhs, Database_Contact rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(getActivity(),
R.layout.activity_allcontactlist, contactlist);
ListView listView = (ListView)v.findViewById(R.id.helplistview);
// Assign adapter to ListView
listView.setTextFilterEnabled(true);
listView.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Database_Contact contact = (Database_Contact)
parent.getItemAtPosition(position);
contact.isSelected();
}
});
}
private class MyCustomAdapter extends ArrayAdapter<Database_Contact> {
private ArrayList<Database_Contact> contactlist;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Database_Contact> contactlist) {
super(context, textViewResourceId, contactlist);
this.contactlist = new ArrayList<Database_Contact>();
this.contactlist.addAll(contactlist);
}
private class ViewHolder {
TextView code;
TextView Number;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
vi = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.activity_allcontactlist,
null);
holder = new ViewHolder();
holder.code = (TextView)
convertView.findViewById(R.id.helplist_name);
holder.Number = (TextView)
convertView.findViewById(R.id.helplist_num);
holder.name = (CheckBox)
convertView.findViewById(R.id.checkbox_all);
convertView.setTag(holder);
final ViewHolder finalHolder = holder;
final ViewHolder finalHolder1 = holder;
holder.code.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (finalHolder1.name.isShown() == false){
Constants.i = Constants.i+1;
myDelButton.setEnabled(true);
finalHolder.name.setVisibility(View.VISIBLE);
}
else if(finalHolder1.name.isShown() == true) {
finalHolder.name.setVisibility(View.GONE);
Constants.i = Constants.i-1;
if (Constants.i == 0){
myDelButton.setEnabled(false);
}
}
}
});
holder.Number.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (finalHolder1.name.isShown() == false){
Constants.i = Constants.i+1;
myDelButton.setEnabled(true);
finalHolder.name.setVisibility(View.VISIBLE);
}
else if(finalHolder1.name.isShown() == true) {
finalHolder.name.setVisibility(View.GONE);
Constants.i = Constants.i-1;
if (Constants.i == 0){
myDelButton.setEnabled(false);
}
}
}
});
holder.name.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Database_Contact contact = (Database_Contact)
cb.getTag();
contact.setSelected(cb.isChecked());
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
Database_Contact contact = contactlist.get(position);
holder.code.setText(contact.getName());
holder.Number.setText(contact.getPhoneNumber());
holder.name.setText("");
holder.name.setChecked(contact.isSelected());
holder.name.setTag(contact);
return convertView;
}
}
}
As I could not find any perfect solution i tried it in a different manner alough its a bit diffenrt from what i wanted i.e on click i used my displayListView() funtion and got the work done
ischeckboxVisible = true;
Runnable run = new Runnable() {
#Override
public void run() {
displayListView();
}
};
getActivity().runOnUiThread(run);
and coming to getView i have used:
if (!ischeckboxVisible)
{
holder.name.setVisibility(View.GONE);
}
if (ischeckboxVisible)
{
holder.name.setVisibility(View.VISIBLE);
}
so every time i do the click it changes the ischeckboxVisible to either true or false and initializes the displatListview() and it works.
I have had help from here Android hide and show checkboxes in custome listview on button click
Hope this might come in handy for some one out there.
Please check below code if it helps you,
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Database_Contact contact = (Database_Contact) contactlist.get(position);
contact.setSelected(!contact.isSelected());
if(contact.isSelected())
{
((CheckBox) view.findViewById(R.id.checkbox_all)).setVisibility(View.VISIBLE);
}
else
{
((CheckBox) view.findViewById(R.id.checkbox_all)).setVisibility(View.GONE);
}
}
});

Categories

Resources