Accessing the listview from onOptionsItemSelected - android

In the shopping cart activity I have a listview and I have placed a imagebutton on top of it as shown in the class_list_group.xml. When start of the activity I want to hide the imagebutton. But once press the edit button in the action bar (onOptionsItemSelected in the activity class) I want to display a relative layout which is carrying the imagebutton as shown in the xml file.
That is my question, my problem is how can I do it? any help will be appreciated. It crahses from what I have done saying null point exception.
Shoppingcartactivity.java class
public class ShoppingCartActivity extends Activity {
private TextView totalTV;
private TextView discountTV;
private TextView totalExclTV;
private TextView totalTaxTV;
private TextView netPriceTV;
private ProductAdapter mProductAdapter;
private ExpandableListView expListView;
private EditText couponET;
private ImageButton couponBTN;
private List<Product> mCartList;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
private String Strdiscount;
private double discount;
public JSONObject DiscountObj;
private double addSubTotal;
RelativeLayout hiddenEditDelete;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cart_activity);
ActionBar actionBar = getActionBar();
getActionBar().setIcon(
new ColorDrawable(getResources().getColor(
android.R.color.transparent)));
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
// Enabling Back navigation on Action Bar icon
actionBar.setDisplayHomeAsUpEnabled(true);
mCartList = ShoppingCartHelper.getCartList();
expListView = (ExpandableListView) findViewById(R.id.lvExp);
mProductAdapter = new ProductAdapter(this, mCartList,
getLayoutInflater(), true);
// setting list adapter
expListView.setAdapter(mProductAdapter);
totalTV = (TextView) findViewById(R.id.total_valueamount);
discountTV = (TextView) findViewById(R.id.discount_valueamount);
totalExclTV = (TextView) findViewById(R.id.exl_tax_valueamount);
totalTaxTV = (TextView) findViewById(R.id.ttl_tax_valueamount);
netPriceTV = (TextView) findViewById(R.id.net_price_valueamount);
couponBTN = (ImageButton) findViewById(R.id.btncoupon);
couponET = (EditText) findViewById(R.id.ET_coupon);
hiddenEditDelete = (RelativeLayout) findViewById(R.id.rl_cartedit);
hiddenEditDelete.setVisibility(View.GONE);
couponET.setEnabled(false);
couponBTN.setEnabled(false);
priceCalculation();
double taxamount = (addSubTotal * 5) / 100;
double netTotal = addSubTotal + taxamount;
DecimalFormat df = new DecimalFormat("#.##");
addSubTotal = Double.valueOf(df.format(addSubTotal));
taxamount = Double.valueOf(df.format(taxamount));
netTotal = Double.valueOf(df.format(netTotal));
totalTV.setText(Double.toString(addSubTotal));
discountTV.setText("0.0");
totalExclTV.setText(Double.toString(addSubTotal));
totalTaxTV.setText(Double.toString(taxamount));
netPriceTV.setText(Double.toString(netTotal));
// couponBTN.setOnClickListener(new View.OnClickListener() {
// public void onClick(View v) {
//
// try {
// String CouponCode = couponET.getText().toString();
//
// if (!Utility.isNotNull(CouponCode)) {
// Toast.makeText(getApplicationContext(),
// "Insert coupon code", Toast.LENGTH_LONG).show();
// } else {
// new CouponAsyncTask(ShoppingCartActivity.this)
// .execute(CouponCode);
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// });
}
public void loadCouponData() {
Strdiscount = DiscountObj.optString("Discount");
try {
Log.i("Discount", DiscountObj.getString("Discount"));
} catch (JSONException e) {
e.printStackTrace();
}
}
public void priceCalculation() {
for (int i = 0; i < mCartList.size(); i++) {
if (!mCartList.isEmpty()) {
couponET.setEnabled(true);
couponBTN.setEnabled(true);
}
Product cat = mCartList.get(i);
addSubTotal += cat.subTotal;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_cart, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
finish();
overridePendingTransition(R.anim.slide_in_left,
R.anim.slide_out_right);
return true;
case R.id.action_edit:
hiddenEditDelete.setVisibility(View.VISIBLE);
overridePendingTransition(R.anim.slide_in_right,
R.anim.slide_out_left);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
class_list_group.xml class
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/shareLILayout1"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="horizontal"
android:paddingTop="3dp"
android:weightSum="5" >
<TextView
android:id="#+id/lblListHeader"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_weight="3"
android:paddingBottom="4dp"
android:paddingLeft="28dp"
android:paddingTop="4dp"
android:singleLine="true"
android:textColor="#000000"
android:textSize="13sp"
android:textStyle="bold" />
</LinearLayout>
<RelativeLayout
android:id="#+id/rl_cartedit"
android:layout_width="60dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:gravity="center"
android:orientation="horizontal"
android:paddingBottom="4dp" >
<ImageButton
android:id="#+id/btneditcartitem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:background="#ffffff"
android:src="#drawable/edititem" />
</RelativeLayout>
</RelativeLayout>
ProductAdapter .java
public class ProductAdapter extends BaseExpandableListAdapter {
private List<Product> mCartList;
private Context _context;
private List<Product> _cartList;
private boolean mShowQuantity;
public ProductAdapter(Context context, List<Product> cartList,
LayoutInflater inflater, boolean showQuantity) {
this._context = context;
this._cartList = cartList;
mShowQuantity = showQuantity;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return _cartList.get(groupPosition).getItems().get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return _cartList.get(groupPosition).getItems().get(childPosition)
.hashCode();
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) _context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.cart_list_item, parent, false);
}
TextView itemSize = (TextView) v.findViewById(R.id.lblListItemSize);
Item det = _cartList.get(groupPosition).getItems().get(childPosition);
itemSize.setText(det.itemName + " ( " + det.price + " ) ");
mCartList = ShoppingCartHelper.getCartList();
return v;
}
#Override
public int getChildrenCount(int groupPosition) {
int size = _cartList.get(groupPosition).getItems().size();
System.out.println("Child for group [" + groupPosition + "] is ["
+ size + "]");
return size;
}
#Override
public Object getGroup(int groupPosition) {
return this._cartList.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._cartList.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(final int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) _context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.cart_list_group, parent, false);
}
TextView groupName = (TextView) v.findViewById(R.id.lblListHeader);
TextView groupQty = (TextView) v.findViewById(R.id.lbl_qty);
TextView groupSubtotal = (TextView) v.findViewById(R.id.lblsubtotal);
final Product cat = _cartList.get(groupPosition);
// ShoppingCartEntry catalog = ShoppingCartHelper.getByProduct(cat);
// int productIndex = getIntent().getExtras().getInt(
// ShoppingCartHelper.PRODUCT_INDEX);
// final Product selectedProduct = catalog.get(productIndex);
groupName.setText(cat.description);
groupQty.setText(String.valueOf(cat.quantity));
groupSubtotal.setText(Double.toString(cat.subTotal));
ImageButton editIB = (ImageButton) v.findViewById(R.id.btneditcartitem);
if (cat.itemCategory != null && cat.itemCategory.equals("Pizza"))
editIB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent next = new Intent(_context, ActivityEdit.class);
Bundle b = new Bundle();
b.putDouble("subTotal", cat.subTotal);
next.putExtras(b);
next.putExtra("description", cat.description);
_context.startActivity(next);
((Activity) _context).overridePendingTransition(
R.anim.slide_in_right, R.anim.slide_out_left);
}
});
return v;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
cart_Activity
<ExpandableListView
android:id="#+id/lvExp"
android:layout_width="match_parent"
android:layout_height="162dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/grid_topics"
android:cacheColorHint="#00000000"
android:groupIndicator="#drawable/group_indicator" >
</ExpandableListView>

You haven't initialized hiddenEditDelete before using it in the onCreate method and that's why NPE is thrown. Also, I believe setContentView should be called last
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
expListView = (ExpandableListView) findViewById(R.id.lvExp);
mProductAdapter = new ProductAdapter(this, mCartList,
getLayoutInflater(), true);
expListView.setAdapter(mProductAdapter);
hiddenEditDelete = (RelativeLayout) findViewById(R.id.rl_cartedit);
hiddenEditDelete.setVisibility(View.GONE);
setContentView(R.layout.cart_activity);
}

The problem is you haven't took any reference for hiddenEditDelete (like expListView) before accessing it , You have to instantiate it with the proper layout id before using it. Then and then you can do whatever you want with the layout. Everything else is correct in onCreate()
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cart_activity);
expListView = (ExpandableListView) findViewById(R.id.lvExp);
mProductAdapter = new ProductAdapter(this, mCartList,
getLayoutInflater(), true);
expListView.setAdapter(mProductAdapter);
hiddenEditDelete.setVisibility(View.GONE);
}

Related

Checkbox for gridview inside listview in Android

I have a problem statement in my booking app such that user can delete all the booking of the particular date or all the dates, see this image:
I have tried to add data to the grid view using multiple adapters for listview and the inner gridview, but it's taking data replication. How can I solve this problem?
Each date represents the listview with checkbox,and the UH,U1 etc represents the item of gridview. I want to pass the selected venue id ie. UH,U! etc in a listview and its corresponding dates
Try the sample below :)
MainActivity.java:
public class MainActivity extends Activity {
Button clearChecks;
ExpandableListView expandableListView;
ExpandableListGridAdapter expandableListAdapter;
int lastExpandedPosition = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
expandableListView = findViewById(R.id.expandedListView);
clearChecks = findViewById(R.id.btnClearChecks);
List<String> listTitle = genGroupList();
expandableListAdapter = new ExpandableListGridAdapter(this, listTitle, genChildList(listTitle));
expandableListView.setAdapter(expandableListAdapter);
expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
if(lastExpandedPosition != -1 && (lastExpandedPosition != groupPosition)){
expandableListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
});
clearChecks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
expandableListAdapter.clearChecks();
}
});
}
private List<String> genGroupList(){
List<String> listGroup = new ArrayList<>();
for(int i=1; i<10; i++){
listGroup.add("Group: " + i);
}
return listGroup;
}
private Map<String, List<ChildItemSample>> genChildList(List<String> header){
Map<String, List<ChildItemSample>> listChild = new HashMap<>();
for(int i=0; i<header.size(); i++){
List<ChildItemSample> testDataList = new ArrayList<>();
int a = (int)(Math.random() * 8);
for(int j=0; j<a; j++){
ChildItemSample testItem = new ChildItemSample("Child " + (j + 1));
testDataList.add(testItem);
}
listChild.put(header.get(i), testDataList);
}
return listChild;
}
}
ChildItemSample.java:
public class ChildItemSample {
private boolean checked;
private String name;
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ChildItemSample(){
checked = false;
name = "";
}
public ChildItemSample(String name){
checked = false;
this.name = name;
}
}
ExpandableListGridAdapter.java:
public class ExpandableListGridAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> listGroup;
private Map<String, List<ChildItemSample>> listChild;
private int checkedBoxesCount;
private boolean[] checkedGroup;
public ExpandableListGridAdapter(Context context, List<String> listGroup, Map<String,
List<ChildItemSample>> listChild) {
this.context = context;
this.listGroup = listGroup;
this.listChild = listChild;
checkedBoxesCount = 0;
checkedGroup = new boolean[listGroup.size()];
}
#Override
public int getGroupCount() {
return listGroup.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return 1;
}
#Override
public String getGroup(int groupPosition) {
return listGroup.get(groupPosition);
}
#Override
public ChildItemSample getChild(int groupPosition, int childPosition) {
return listChild.get(listGroup.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean b, View view, ViewGroup viewGroup) {
String itemGroup = getGroup(groupPosition);
GroupViewHolder groupViewHolder;
if(view == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.expanded_list_group, null);
groupViewHolder = new GroupViewHolder();
groupViewHolder.tvGroup = view.findViewById(R.id.tv_group);
groupViewHolder.cbGroup = view.findViewById(R.id.cb_group);
groupViewHolder.cbGroup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = (int)view.getTag();
checkedGroup[pos] = !checkedGroup[pos];
for(ChildItemSample item : listChild.get(listGroup.get(pos))){
item.setChecked(checkedGroup[pos]);
}
notifyDataSetChanged();
}
});
view.setTag(groupViewHolder);
}else {
groupViewHolder = (GroupViewHolder)view.getTag();
}
groupViewHolder.tvGroup.setText(String.format("%s (%d)", itemGroup, listChild.get(listGroup.get(groupPosition)).size()));
if(checkedGroup[groupPosition]) groupViewHolder.cbGroup.setChecked(true);
else groupViewHolder.cbGroup.setChecked(false);
groupViewHolder.cbGroup.setTag(groupPosition);
return view;
}
#Override
public View getChildView(final int groupPosition, int childPosition, boolean b, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_grid_item, null);
GridLayout childLayout = view.findViewById(R.id.layout_child);
for(int i = 0; i < listChild.get(listGroup.get(groupPosition)).size(); i++){
ChildItemSample expandedListText = getChild(groupPosition, i);
CheckBox cbChild = new CheckBox(context);
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
params.width = (int)(80 * context.getResources().getDisplayMetrics().density);
cbChild.setLayoutParams(params);
cbChild.setChecked(expandedListText.isChecked());
cbChild.setText(expandedListText.getName());
cbChild.setTag(i);
childLayout.addView(cbChild);
cbChild.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckBox cb = (CheckBox) view;
int pos = (int) view.getTag();;
ChildItemSample selectedItem = listChild.get(listGroup.get(groupPosition)).get(pos);
selectedItem.setChecked(cb.isChecked());
if(cb.isChecked()){
checkedBoxesCount++;
Toast.makeText(context,"Checked value is: " +
listChild.get(listGroup.get(groupPosition)).get(pos).getName(),
Toast.LENGTH_SHORT).show();
}else {
checkedBoxesCount--;
if(checkedBoxesCount == 0){
Toast.makeText(context,"nothing checked",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context,"unchecked",Toast.LENGTH_SHORT).show();
}
}
notifyDataSetChanged();
}
});
}
return view;
}
public void clearChecks() {
for(int i=0; i<checkedGroup.length; i++) checkedGroup[i] = false;
for(List<ChildItemSample> value : listChild.values()) {
for (ChildItemSample sample : value) {
sample.setChecked(false);
}
}
checkedBoxesCount = 0;
notifyDataSetChanged();
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
private class GroupViewHolder {
CheckBox cbGroup;
TextView tvGroup;
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/btnClearChecks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Clear Checks" />
<ExpandableListView
android:id="#+id/expandedListView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ExpandableListView>
</LinearLayout>
expanded_list_group.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants" >
<CheckBox
android:id="#+id/cb_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_gravity="center_vertical" />
<TextView
android:id="#+id/tv_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text"
android:textSize="30sp" />
</LinearLayout>
list_grid_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_child"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="60dp"
android:columnCount="3"
android:orientation="horizontal">
</GridLayout>
Hope that helps!

Filter several ListViews via SearchView

I have implemented precisely ONE ListView (with header attached) filtering according to SearchView input. Now I'm planning to make SearchView filter several ListViews and I wonder how to do it. I'm stuck and have no ideas. The main principle of filtering is such:
We have several categories(i.e. accomodation, places of interest), which serve as headers (basically, the picture of category) displayed with ListViews attached for each of the category. When user enters the search query, the application needs to have all the ListViews filtered at once. The structure of the window is this:
->Header of the current category
ListView #1
When user enters input, all the available categories are displayed and the filter is applied for them:
->Header of the current category
Filtered ListView #1
->Header #2
Filtered ListView #2
...
->Header #8
Filtered ListView #8
I seek for the clearest/most genious way for performing this. Worth to mention, we know the exact count of categories.
I'm posting my code snippets(ONE ListView (with header attached) filtering according to SearchView input). Moreover, I print the message if search returns no results so that the user can contact us, if he desires.
list_header.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="#+id/top"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_weight="1"
android:gravity="center">
<View
android:id="#+id/line_left1"
android:layout_width="0dp"
android:layout_height="1dp"
android:layout_weight="0.45"
android:background="#FFFFFF" />
<ImageView
android:id="#+id/small_icon"
android:layout_width="60dp"
android:layout_height="80dp"
android:layout_weight="0.1"
android:src="#drawable/pavalgyk" />
<View
android:id="#+id/line_left2"
android:layout_width="0dp"
android:layout_height="1dp"
android:layout_weight="0.45"
android:background="#FFFFFF" />
</LinearLayout>
</LinearLayout>
alllists.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="5dp"
android:background="#drawable/background"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="5dp">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:background="#drawable/card"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/search_window_text"
android:textSize="16dp"
android:textStyle="normal"
android:autoLink="email"
android:fontFamily="sans-serif-light" />
</RelativeLayout>
</LinearLayout>
AllLists.java
public class AllLists extends android.support.v4.app.Fragment {
private TypedArray navMenuIcons;
private Context context = null;
private int position = 0;
private String location;
private List<Item> items = new ArrayList<Item>();
private List<Item> tmp_items = new ArrayList<Item>();
private ListView listView;
private CustomListAdapter adapter;
private SearchView mSearchView;
private String tmp_s = "";
private static Locale myLocale;
private EasyTracker easyTracker = null;
private RelativeLayout relativeLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.alllists, container, false);
View header = inflater.inflate(R.layout.list_header, null);
ImageView image = (ImageView) header.findViewById(R.id.small_icon);
relativeLayout = (RelativeLayout) rootView.findViewById(R.id.relativeLayout);
relativeLayout.setVisibility(View.GONE);
setLanguage();
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
Bundle bundle = getArguments();
position = bundle.getInt("position");
location = bundle.getString("location");
image.setImageDrawable(navMenuIcons.getDrawable(position));
context = getActivity().getApplicationContext();
easyTracker = EasyTracker.getInstance(context);
DatabaseHandler db = new DatabaseHandler(context);
items = db.getAllItems(location);
tmp_items = db.getAllItems(location);
listView = (ListView) rootView.findViewById(R.id.list);
adapter = new CustomListAdapter(context, items);
listView.addHeaderView(header, "", false);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int list_position, long id) {
easyTracker.send(MapBuilder.createEvent("List",
location, adapter.getItems().get(list_position - 1).getName(), null).build());
if (location.equals("accommodation") || location.equals("eat") || location.equals("events")
|| location.equals("entertainment") || location.equals("places") || location.equals("cinema")) {
Intent i = new Intent(context, ItemScreen.class);
i.putExtra("position", list_position - 1);
i.putExtra("location", location);
i.putExtra("name", adapter.getItems().get(list_position - 1).getRealName());
startActivity(i);
} else if (location.equals("taxi")) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + adapter.getItems().get(list_position - 1).getType()));
PackageManager manager = context.getPackageManager();
List<ResolveInfo> infos = manager.queryIntentActivities(intent, 0);
if (infos.size() > 0)
startActivity(intent);
else
Toast.makeText(context, R.string.cant_handle, Toast.LENGTH_SHORT).show();
}
}
});
setHasOptionsMenu(true);
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
MenuItem searchItem = menu.findItem(R.id.action_search);
mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
easyTracker.send(MapBuilder.createEvent("Search",
"search", s, null).build());
if (TextUtils.isEmpty(s)) {
adapter = new CustomListAdapter(context, tmp_items);
listView.setAdapter(adapter);
}
if (tmp_s.length() > s.length()) {
adapter.getFilter(tmp_items, true).filter(s, new Filter.FilterListener() {
public void onFilterComplete(int count) {
if (count == 0)
relativeLayout.setVisibility(View.VISIBLE);
else
relativeLayout.setVisibility(View.GONE);
}
});
} else {
adapter.getFilter(tmp_items, false).filter(s, new Filter.FilterListener() {
#Override
public void onFilterComplete(int count) {
if (count == 0)
relativeLayout.setVisibility(View.VISIBLE);
else
relativeLayout.setVisibility(View.GONE);
}
});
}
tmp_s = s;
return false;
}
});
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
mSearchView.setQuery("", false);
}
}
CustomListAdapted.java
public class CustomListAdapter extends BaseAdapter {
private Context context;
private List<Item> items;
private LayoutInflater inflater;
private ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Context context, List<Item> items) {
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.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) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_item, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView image = (NetworkImageView) convertView.findViewById(R.id.image);
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView type = (TextView) convertView.findViewById(R.id.type);
Item i = items.get(position);
image.setImageUrl(i.getIcon(), imageLoader);
if(items.get(0).getName().contains("taksi"))
image.setDefaultImageResId(R.drawable.telefonas);
else
image.setDefaultImageResId(R.drawable.be_fono);
name.setText(i.getRealName());
type.setText(i.getType());
return convertView;
}
public List<Item> getItems(){
return items;
}
public Filter getFilter(final List<Item> all_items, final boolean deleted) {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
FilterResults results = new FilterResults();
if (charSequence == null || charSequence.length() == 0) {
results.values = items;
results.count = items.size();
} else {
List<Item> filtered_items = new ArrayList<Item>();
if(deleted)
items = all_items;
for (int i = 0; i < items.size(); i++) {
String modifiedName = items.get(i).getRealName().toLowerCase();
String modifiedQuery = charSequence.toString().toLowerCase();
modifiedName = encode_lithuanian(modifiedName);
modifiedQuery = encode_lithuanian(modifiedQuery);
if (modifiedName.contains(modifiedQuery))
filtered_items.add(items.get(i));
}
results.values = filtered_items;
results.count = filtered_items.size();
}
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
items = (List<Item>) filterResults.values;
notifyDataSetChanged();
}
public int show_size(){
return items.size();
}
};
}
}
Create adapter for different list views.
Then in the edittext aftertextchange listener apply the text filter for all the adapters. Have a look at:
http://www.androidbegin.com/tutorial/android-search-listview-using-filter/
adapter1 = new ListViewAdapter(this, arraylist1);
list1.setAdapter(adapter1);
adapter2 = new ListViewAdapter(this, arraylist2);
list2.setAdapter(adapter2);
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
//TODO Auto-generated method stub
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter1.filter(text);
adapter2.filter(text);
....
}
#Riasat's answer inspired me and I think it could be possible to do it without any code repetition: of course for each list view, you'd have a adapter with will be more or less the same. But it could be great to create a notifier, which will say to all the adapter to refresh. Something like:
An interface to go a bit further as your only requirements:
/**
* Created by laurentmeyer on 03/03/15.
*/
public interface RefreshInterface {
void refresh();
void searchForText(String searchedText);
void searchWithSomethingElse(Object SomethingElse);
}
Then modify a bit the adapter:
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
/**
* Created by laurentmeyer on 03/03/15.
*/
public class CustomListAdapter extends BaseAdapter implements RefreshInterface{
private Context context;
private List<Item> items;
private LayoutInflater inflater;
private ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Context context, List<Item> items) {
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.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) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_item, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView image = (NetworkImageView) convertView.findViewById(R.id.image);
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView type = (TextView) convertView.findViewById(R.id.type);
Item i = items.get(position);
image.setImageUrl(i.getIcon(), imageLoader);
if(items.get(0).getName().contains("taksi"))
image.setDefaultImageResId(R.drawable.telefonas);
else
image.setDefaultImageResId(R.drawable.be_fono);
name.setText(i.getRealName());
type.setText(i.getType());
return convertView;
}
public List<Item> getItems(){
return items;
}
public Filter getFilter(final List<Item> all_items, final boolean deleted) {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
FilterResults results = new FilterResults();
if (charSequence == null || charSequence.length() == 0) {
results.values = items;
results.count = items.size();
} else {
List<Item> filtered_items = new ArrayList<Item>();
if(deleted)
items = all_items;
for (int i = 0; i < items.size(); i++) {
String modifiedName = items.get(i).getRealName().toLowerCase();
String modifiedQuery = charSequence.toString().toLowerCase();
modifiedName = encode_lithuanian(modifiedName);
modifiedQuery = encode_lithuanian(modifiedQuery);
if (modifiedName.contains(modifiedQuery))
filtered_items.add(items.get(i));
}
results.values = filtered_items;
results.count = filtered_items.size();
}
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
items = (List<Item>) filterResults.values;
notifyDataSetChanged();
}
public int show_size(){
return items.size();
}
};
}
// What you'll do when you'll want to refresh (why not?)
#Override
public void refresh() {
}
// What you'll do when you'll want to search from SearchView
#Override
public void searchForText(String searchedText) {
}
// What you'll do when you'll want to have a look with another cool Object like a LatLong or some other stuff (optional, of course)
#Override
public void searchWithSomethingElse(Object SomethingElse) {
}
}
And then your Fragment will also change a bit but not as much as in the other solution:
import java.util.ArrayList;
/**
* Created by laurentmeyer on 03/03/15.
*/
public class AllLists extends android.support.v4.app.Fragment {
private TypedArray navMenuIcons;
private Context context = null;
private int position = 0;
private String location;
private List<Item> items = new ArrayList<Item>();
private List<Item> tmp_items = new ArrayList<Item>();
private ListView listView;
private CustomListAdapter adapter;
private SearchView mSearchView;
private String tmp_s = "";
private static Locale myLocale;
private EasyTracker easyTracker = null;
private RelativeLayout relativeLayout;
/*
Here is a modification
*/
// Create a ArrayList containing all the adapters (which are directly connected to the listViews)
// which will need to be refreshed by the search view. I made it static because maybe you can use
// it in other instances and it could be easier.
public static ArrayList<RefreshInterface> toBeRefreshed;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.alllists, container, false);
View header = inflater.inflate(R.layout.list_header, null);
ImageView image = (ImageView) header.findViewById(R.id.small_icon);
relativeLayout = (RelativeLayout) rootView.findViewById(R.id.relativeLayout);
relativeLayout.setVisibility(View.GONE);
setLanguage();
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
Bundle bundle = getArguments();
position = bundle.getInt("position");
location = bundle.getString("location");
image.setImageDrawable(navMenuIcons.getDrawable(position));
context = getActivity().getApplicationContext();
easyTracker = EasyTracker.getInstance(context);
DatabaseHandler db = new DatabaseHandler(context);
items = db.getAllItems(location);
tmp_items = db.getAllItems(location);
listView = (ListView) rootView.findViewById(R.id.list);
adapter = new CustomListAdapter(context, items);
/*
Here is a modification
*/
toBeRefreshed.add(adapter);
listView.addHeaderView(header, "", false);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int list_position, long id) {
easyTracker.send(MapBuilder.createEvent("List",
location, adapter.getItems().get(list_position - 1).getName(), null).build());
if (location.equals("accommodation") || location.equals("eat") || location.equals("events")
|| location.equals("entertainment") || location.equals("places") || location.equals("cinema")) {
Intent i = new Intent(context, ItemScreen.class);
i.putExtra("position", list_position - 1);
i.putExtra("location", location);
i.putExtra("name", adapter.getItems().get(list_position - 1).getRealName());
startActivity(i);
} else if (location.equals("taxi")) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + adapter.getItems().get(list_position - 1).getType()));
PackageManager manager = context.getPackageManager();
List<ResolveInfo> infos = manager.queryIntentActivities(intent, 0);
if (infos.size() > 0)
startActivity(intent);
else
Toast.makeText(context, R.string.cant_handle, Toast.LENGTH_SHORT).show();
}
}
});
setHasOptionsMenu(true);
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
MenuItem searchItem = menu.findItem(R.id.action_search);
mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
easyTracker.send(MapBuilder.createEvent("Search",
"search", s, null).build());
if (TextUtils.isEmpty(s)) {
adapter = new CustomListAdapter(context, tmp_items);
listView.setAdapter(adapter);
}
if (tmp_s.length() > s.length()) {
/*
Here call the logic you implemented in your adapter functions like:
for (RefreshInterface r : toBeRefreshed){
r.filter(String)
}
*/
} else {
/*
Same as above
*/
}
tmp_s = s;
return false;
}
});
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
mSearchView.setQuery("", false);
}
}

Android displaying list using expandableListView

I have followed this example tutorial and developed a sample application http://www.androidhive.info/2013/07/android-expandable-list-view-tutorial/
If i click on Core i want to load one more list in the same Screen under Core,How Could i do this?using my below code i am able to load the child list in another Screen,help?
My Code for ChildClickListener goes here:
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
Log.d("onChildClick", "onChildClick");
String position = (String) parentItems.get(groupPosition);
Log.d("position", position);
String child = listDataChild.get(position).get(childPosition);
Log.d("child", child);
if (child.equalsIgnoreCase("Core")) {
ArrayList<String> parentItems = new ArrayList<String>();
HashMap<String, List<String>> listDataChild = new HashMap<String, List<String>>();
ArrayList<String> childItems = new ArrayList<String>();
childItems.add("corejava");
childItems.add("corejava");
childItems.add("corejava");
childItems.add("corejava");
parentItems.add(position);
listDataChild.put(parentItems.get(0), childItems);
expandableList = (ExpandableListView) findViewById(R.id.lvExp);
CoreAdapter adapter = new CoreAdapter(parentItems,
listDataChild);
CustExpListview SecondLevelexplv = new CustExpListview(
MainActivity.this);
adapter.setInflater(
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE),
MainActivity.this);
SecondLevelexplv.setAdapter(adapter);
SecondLevelexplv.setGroupIndicator(null);
expandableList.setAdapter(adapter);
}
i write one treeView adapter for you, you can use this and put many level as you want, for that you need just copy following code:
MainActivity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// add data for test on one list<AccountHierarchical>
AccountHierarchical obj = new AccountHierarchical();
obj.setLevelId(1);
obj.setTitle("level 1");
AccountHierarchical obj2 = new AccountHierarchical();
obj2.setLevelId(1);
obj2.setTitle("level 2");
AccountHierarchical obj3 = new AccountHierarchical();
obj3.setLevelId(1);
obj3.setTitle("level 3");
List<AccountHierarchical> emptyList = new ArrayList<AccountHierarchical>();
obj3.setList(emptyList);
List<AccountHierarchical> list2 = new ArrayList<AccountHierarchical>();
list2.add(obj3);list2.add(obj3);list2.add(obj3);list2.add(obj3);list2.add(obj3);
obj2.setList(list2);
List<AccountHierarchical> list = new ArrayList<AccountHierarchical>();
list.add(obj2);list.add(obj2);list.add(obj2);list.add(obj2);list.add(obj2);
obj.setList(list);
List<AccountHierarchical> result = new ArrayList<AccountHierarchical>();
result.add(obj);result.add(obj);result.add(obj);result.add(obj);
// create Adapter
TreeView adapter = new TreeView(result, this,
getLayoutInflater() , false, 0);
ExpandableListView expandList = (ExpandableListView)findViewById(R.id.expandableList_tree);
expandList.setGroupIndicator(null);
expandList.setAdapter(adapter);
}
CustExpListview:
public class CustExpListview extends ExpandableListView {
int intGroupPosition, intChildPosition, intGroupid;
public CustExpListview(Context context) {
super(context);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// widthMeasureSpec = MeasureSpec.makeMeasureSpec(400,
// MeasureSpec.AT_MOST);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(600,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
AccountHierarchical:
public class AccountHierarchical {
List<AccountHierarchical> list;
private String Title;
private int Id;
public int getId() {
return Id;
}
public void setLevelId(int Id) {
this.Id = Id;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public List<AccountHierarchical> getList() {
return list;
}
public void setList(List<AccountHierarchical> list) {
this.list = list;
}
}
TreeView:
public class TreeView extends BaseExpandableListAdapter implements
OnClickListener {
List<AccountHierarchical> list;
LayoutInflater inflatter;
static Context context;
boolean checkGroup;
int position;
static ProgressDialog ProgressDialog;
public TreeView( List<AccountHierarchical> list, Context context,
LayoutInflater inflatter, boolean checkGroup, int position
) {
this.list = list;
TreeView.context = context;
this.inflatter = inflatter;
this.checkGroup = checkGroup; // this is true when you call from inner.
this.position = position;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return list.get(groupPosition).getList().get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return list.get(groupPosition).getList().get(childPosition).getId();
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
if (checkGroup)
groupPosition = position;
List<AccountHierarchical> childtemp = list.get(groupPosition)
.getList();
// call this adapter again for creating another level
if (childtemp.get(childPosition).getList().size() > 0) {
CustExpListview SecondLevelexplv = new CustExpListview(context);
TreeView adapter = null;
adapter = new TreeView(childtemp, context,
inflatter, true, childPosition);
SecondLevelexplv.setGroupIndicator(null);
SecondLevelexplv.setAdapter(adapter);
return SecondLevelexplv;
}
// call one layout, this is last child
else {
convertView = inflatter.inflate(R.layout.grouprow, null);
TextView tv = (TextView) convertView.findViewById(R.id.grouprow);
tv.setText(list.get(groupPosition).getList().get(childPosition)
.getTitle());
tv.setPadding(0, 0, 20, 0);
convertView.setTag(list.get(groupPosition).getList()
.get(childPosition) );
convertView.setId(position);
convertView.setOnClickListener(this);
return convertView;
}
}
#Override
public int getChildrenCount(int groupPosition) {
return list.get(groupPosition).getList().size();
}
#Override
public Object getGroup(int groupPosition) {
return list.get(groupPosition);
}
#Override
public int getGroupCount() {
if (checkGroup)
return 1;
return list.size();
}
#Override
public long getGroupId(int groupPosition) {
return list.get(groupPosition).getId();
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
if (convertView == null)
convertView = inflatter.inflate(R.layout.grouprow, null);
TextView tv = (TextView) convertView.findViewById(R.id.grouprow);
if (checkGroup)
tv.setText(list.get(position).getTitle());
else
tv.setText(list.get(groupPosition).getTitle());
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
#Override
public void onClick(View v) {
// your onClick method
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ExpandableListView
android:id="#+id/expandableList_tree"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ExpandableListView>
</RelativeLayout>
grouprow.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/grouprow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:text=""/>
</RelativeLayout>
snap:
You have to create a layout in the xml file (from where your core textview comes from) and display an image view below
onClick of that imageView you will just have to make your layout Gone and Visible
I have just given you direction rest relies on your skill :)
<RelativeLayout
android:id="#+id/option"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:gravity="center"
android:orientation="horizontal" >
</RelativeLayout>
<RelativeLayout
android:id="#+id/linear"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="horizontal" >
<ImageView
android:id="#+id/navigationIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:src="#drawable/nn" />
<ImageView
android:id="#+id/callOption"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/phonee" />
<ImageView
android:id="#+id/imageViewfeedback"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="#drawable/editer" />
</RelativeLayout>
In Jave File
linear.setVisibility(View.GONE);
option.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
if(count==0)
{
linear.setVisibility(View.VISIBLE);
count=1;
}
else
{
linear.setVisibility(View.GONE);
count=0;
}
}
});
You need to switch to Three-Level of Expandable ListView which contains the subchild inside child.
Also check out ExpandableListView with 3 Childs

How to get the check box selected position

How to get the selected position in checkbox itemId.
I have two item Veg and non-veg item. I want the result for veg Items only. I show the screen in veg items .But it is not working for veg list checked items.
Response
|1|Amaretto cookies|True
is itemId
food item
True/False.
Based on True or False I need to check the check boxes and retrieve the checked items
Veg items:
|21|1|Amaretto cookies|True|2|Amish White Bread|True|6|Caesar Salad|True|10|Guacamole|True|13|Macaroni and Cheese|True|16|Pancakes|True|17|Pasta|True|18|Ribollita|True|20|Pizza|True|21|Seven Layer Taco Dip|True|22|Shrimp Bisque|True|23|Spicy Bean Salsa|True|24|Sopapilla Cheesecake|True|25|Sopapilla Cheesecake Pie|True|26|Vegetarian Tortilla Stew|True|561|food|True|563|asdf|True|574|veg|True|579|a|True|593|hjg|True|619|hhy|True|
Non- Veg items:
|12|3|Barbeque|False|4|Buffalo Chicken Wings|False|5|Burgers|False|7|Classic Lasagna|False|8|Chicken Chow Mein|False|9|Fried Chicken|False|11|Japanese sushi|False|12|Mezze|False|14|Mutton Pepper Gravy|False|15|Paella Valenciana|False|19|Phad Thai Recipe|False|578|Pizza|False|
Url:
String user_url="http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/version21/mmealitems.aspx?uname="+LoginForm.str1+"&occasion="+occasionval;
Code:
httpclass obj = new httpclass();
result = obj.server_conn(user_url);
System.out.println(result);
if (result != null)
{
token = new StringTokenizer2(result, "");
}
value = new ArrayList<String>();
while (token.hasMoreTokens())
{
value.add(token.nextToken());
}
value.add(Integer.toString(value.size()));
Integer k=null;
table=new Hashtable<Integer,ArrayList<String>>();
itemId = new ArrayList<String>();
stritem = new ArrayList<String>();
vegitems = new ArrayList<String>();
nonvegitems = new ArrayList<String>();
int id=0,c=0,n=value.size();
for(int j=0; j<n; j++)
{
z = value.get(j);
String[] mystring = z.split("<br>");
int arraysize = mystring.length;
for(int a=0; a<arraysize-1;a++)
{
str2.add(mystring[0]);
str3.add(mystring[1]);
}
}
for(int g=0; g<str2.size();g++)
{
String name = str2.get(g);
token2 = new StringTokenizer2(name, "|", false);
while (token2.hasMoreTokens())
{
vegitems.add(token2.nextToken());
}
}
for(int x=1;x<vegitems.size();x++)
{
itemId.add(vegitems.get(x));
x=x+1;
stritem.add(vegitems.get(x));
x=x+1;
status.add(vegitems.get(x));
}
setListAdapter(new IconicAdapter(this));
selection = (TextView) findViewById(R.id.selection);
getListView().setTextFilterEnabled(true);
save.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tru = new StringBuffer();
fals = new StringBuffer();
for (int i = 0; i<status.size();i++)
{
if (status.get(i).equals("True"))
tru.append(itemId.get(i)+",");
else
fals.append(itemId.get(i)+",");
}
boolean netvalue = false;
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isAvailable()) {
String user_url="http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/version21/minsertmealchoiceNew.aspx?uname="+username+"&occasion="+occasionval+
"&choice="+tru+fals+"&ownchoice=&category=";
httpclass obj = new httpclass();
result = obj.server_conn(user_url);
StringTokenizer st = new StringTokenizer(result, "|");
result = st.nextToken();
if ((result.equals("Engagement 1&")) || (result.equals("Wedding 1&")) || (result.equals("Reception 1&")))
{
#SuppressWarnings("rawtypes")
class IconicAdapter extends ArrayAdapter
{
Activity context;
#SuppressWarnings("unchecked")
IconicAdapter(Activity context)
{
super(context, R.layout.rsvp_mealsse, stritem);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = context.getLayoutInflater();
View row = inflater.inflate(R.layout.rsvp_mealsse,null);//viewappointlist, null);
TextView index = (TextView) row.findViewById(R.id.index);
index.setText(String.valueOf(position+1)+".");
TextView label = (TextView) row.findViewById(R.id.title);
label.setText(stritem.get(position));
CheckBox check=(CheckBox)row.findViewById(R.id.check);
check.setId(Integer.parseInt(itemId.get(position)));
if(status.get(position).equals("True"))
check.setChecked(true);
else
check.setChecked(false);
check.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
int ind=itemId.indexOf(String.valueOf(buttonView.getId()));
status.set(ind, String.valueOf(isChecked));
}
});
return (row);
}
}
Snap :
This is what it should look like.False items are checked in the snap
Above shows the full code of my project.
These are my requirements:
It is all about event planner for Food. The invited guests can select and save the interested food items such as pizza, Caesar salad, Ameretocokies etc from the items list and mail to the inviter so that the inviter can view the saved items and arrange for the selected items.
I picked the solution from Romain Guy's solution #
https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M
I have used a ViewHolder pattern for smooth scrolling and performance. I have used a SparseBooleanArray to get checked items.
I assume you want the items whose corresponding check boxes are checked.
Also check this to understand listview re-cycles views
How ListView's recycling mechanism works
public class dsds extends Activity
{
ListView lv;
String result = null;
StringTokenizer2 token = null,token2=null;;
ArrayList<String> value,value2 = null;
ArrayList<String> str = null;
ArrayList<String> str2 = null;
ArrayList<String> newstatus=null;
Hashtable<Integer, String> checkstatus=null;
ArrayList<String>stateId=null;
StringBuffer tru,fals;
private SparseBooleanArray mCheckStates;
String z;
ArrayList<Holder> ha = new ArrayList<Holder>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
str2 = new ArrayList<String>();
stateId = new ArrayList<String>();
newstatus=new ArrayList<String>();
lv = (ListView) findViewById(R.id.listView1);
Button b= (Button) findViewById(R.id.button1);
new TheTask().execute();
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
StringBuilder result = new StringBuilder();
for(int i=0;i<str2.size();i++)
{
if(mCheckStates.get(i)==true)
{
result.append(str2.get(i));
result.append("\n");
}
}
Toast.makeText(dsds.this, result, 1000).show();
}
});
}
class TheTask extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/version21/mmealitems.aspx?uname=abcdefg&occasion=Engagement");
try
{
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity);
if (_response != null)
{
//alertbox("",result);
String[] mystring = _response.split("<br>"); // splt by break
token = new StringTokenizer2(mystring[0], "|", false);// split by |
token2 = new StringTokenizer2(mystring[1], "|", false);
}
/////// for veg
value = new ArrayList<String>();
while (token.hasMoreTokens())
{
value.add(token.nextToken());
}
for(int i=1;i<value.size()-1;i=i+3)
{
// Log.i("....Veg ids.......",""+value.get(i));
stateId.add(value.get(i));
}
for(int i=2;i<value.size()-1;i=i+3)
{
str2.add(value.get(i));
// Log.i("....Veg ids.......",""+value.get(i));
}
for(int i=3;i<=value.size()-1;i=i+3)
{
newstatus.add(value.get(i));
// Log.i("....Veg ids.......",""+value.get(i));
}
// add all to list of Holder
for(int h=0;h<str2.size();h++)
{
Holder holder = new Holder();
holder.setTitle(str2.get(h));
holder.setId(stateId.get(h));
if(newstatus.get(h).equals("False"))
{
holder.setCheck(true);
}
else
{
holder.setCheck(false);
}
ha.add(holder);
}
}catch(Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
lv.setAdapter(new IconicAdapter(dsds.this));
}
}
#SuppressWarnings("rawtypes")
class IconicAdapter extends ArrayAdapter implements CompoundButton.OnCheckedChangeListener
{
Activity context;
LayoutInflater mInflater;
#SuppressWarnings("unchecked")
IconicAdapter(Activity context)
{
super(context, R.layout.list_item, str2);
mCheckStates = new SparseBooleanArray(str2.size());
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if(convertView==null)
{
convertView=mInflater.inflate(R.layout.list_item,parent,false);
holder = new ViewHolder();
holder.tv1 = (TextView) convertView.findViewById(R.id.textView1);
holder.tv2 = (TextView) convertView.findViewById(R.id.textView2);
holder.cb = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
Holder hol = ha.get(position);
holder.tv1.setText(hol.getId().toString());
holder.tv2.setText(hol.getTitle().toString());
if(hol.isCheck()==true)
{
holder.cb.setChecked(mCheckStates.get(position, true));
holder.cb.setTag(position);
}
else
{
holder.cb.setChecked(mCheckStates.get(position, false));
holder.cb.setTag(position);
}
holder.cb.setOnCheckedChangeListener(this);
return convertView;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
static class ViewHolder
{
TextView tv1,tv2;
CheckBox cb;
}
}
Holder class
public class Holder {
String title;
String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
boolean check;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isCheck() {
return check;
}
public void setCheck(boolean check) {
this.check = check;
}
}
text.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
<ListView
android:id="#+id/listView1"
android:layout_above="#id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
list_tiem.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="33dp"
android:layout_marginTop="40dp"
android:text="TextView" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView1"
android:layout_centerHorizontal="true"
android:text="TextView" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView2"
android:layout_alignBottom="#+id/textView2"
android:layout_alignParentRight="true"
android:text="CheckBox" />
</RelativeLayout>
Snap
Now 1 and 2 are checked and when you click the button at the bottom you see the selected text. I checked 1 and 2 manually. However it depends on the response ie True or False. Right now all veg items are true.
Note: The list displays only veg items
If you are using list-view and you want to check list-view item then you can use below code.
int len = mListView.getCount();
SparseBooleanArray checked = mListView.getCheckedItemPositions();
for (int i = 0; i < len; i++)
if (checked.get(i)){
..... // Your code whatever you want to do with selected item..
}
else{
....
}

How to get checkbox state in a gridview

i need to get the check-box state from a grid-view when clicking on a button
i tried many things but the state is always "false"
here is my code
this is the adapter
public class CustomSuggestFriends extends ArrayAdapter<Items_FriendsRequest> {
Context context;
dbManage objDB;
Items_FriendsRequest Items_SuggestFriends;
List<Items_FriendsRequest>items;
int Position;
SharedPreferences SharedP;
String user_id="1002", secret_id = "2143054018";
String u_id="1025", ut_ = "1";
public CustomSuggestFriends(Context context, int textViewResourceId,
List<Items_FriendsRequest> objects) {
super(context, textViewResourceId, objects);
this.context = context;
}
private class viewHolder {
private ImageView userImage;
private TextView userName;
private CheckBox checkbox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
viewHolder holder = null;
ImageLoader_Crop imageLoader_Crop;
Items_SuggestFriends = getItem(position);
Position = position;
objDB = new dbManage(getContext());
items = objDB.select_SuggestFriends();
objDB.CloseDataBase();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
imageLoader_Crop = new ImageLoader_Crop(context.getApplicationContext());
if (convertView == null) {
convertView = inflater.inflate(R.layout.items_suggestdriends, null);
holder = new viewHolder();
holder.userImage = (ImageView) convertView
.findViewById(R.id.Items_SuggestFriends_userImage);
holder.userName = (TextView) convertView
.findViewById(R.id.Items_SuggestFriends_NameTXT);
holder.checkbox = (CheckBox) convertView
.findViewById(R.id.Items_SuggestFriends_checkBox);
holder.checkbox.setTag(position);
holder.checkbox.setChecked(items.get(position).isSelected());
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
items.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
Log.v("Changed",items.get(getPosition).getId_()+"");
}
});
convertView.setTag(holder);
} else {
holder = (viewHolder) convertView.getTag();
}
holder.userName.setText(Items_SuggestFriends.getName_());
String SuggestF = Items_SuggestFriends.getSuggestFriendsSEND();
if (SuggestF.equals("0")) {
holder.checkbox.setVisibility(View.VISIBLE);
} else if (SuggestF.equals("1")) {
holder.checkbox.setVisibility(View.GONE);
}
String imageURL = "";
imageURL = functionspackage.Constants.server_file + "1/s/"
+ Items_SuggestFriends.getId_() + "."
+ Items_SuggestFriends.getRand_() + ".jpg";
holder.userImage.setTag(imageURL);
imageLoader_Crop.DisplayImage(imageURL, context, holder.userImage);
return convertView;
}
}
this is my class its got a button called send
and in this button i need to get the ids of what is cheked
public class SuggestFriends extends Activity {
int count;
dbManage objDB;
SharedPreferences SharedP;
String user_id, secret_id = "";
public static String u_id, ut_ = "";
Button send, cancel;
List<Items_FriendsRequest> SuggestFriendsItems;
GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.displayphoto_from_album);
initialise_View();
here i need to get the values but its always false!!!!
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
count = gridView.getCount();
objDB = new dbManage(SuggestFriends.this);
SuggestFriendsItems = objDB.select_SuggestFriends();
objDB.CloseDataBase();
SparseBooleanArray sparseBooleanArray = gridView
.getCheckedItemPositions();
// add the id of the ones that been checked . . to string with
// (,)
for (int i = 0; i < count; i++) {
if(sparseBooleanArray.valueAt(i) == true) {
Log.e(sparseBooleanArray.get(i)+"",SuggestFriendsItems.get(i).getId_()+"");
} else if (!sparseBooleanArray.get(i)) {
Log.e(sparseBooleanArray.get(i) +"",SuggestFriendsItems.get(i).getId_()+"");
gridView.getItemAtPosition(i);
}
}
}
});
SharedP = getSharedPreferences(functionspackage.Constants.SharedP_name,
0);
user_id = SharedP.getString(functionspackage.Constants.SharedP_user_id,
null);
secret_id = SharedP.getString(
functionspackage.Constants.SharedP_secret_id, null);
if (getIntent().hasExtra(functionspackage.Constants.Extra_Uid)) {
u_id = getIntent().getStringExtra(
functionspackage.Constants.Extra_Uid);
}
if (getIntent().hasExtra(functionspackage.Constants.Extra_ut)) {
ut_ = getIntent().getStringExtra(
functionspackage.Constants.Extra_ut);
}
SuggestFriends_AsyncTask Async = new SuggestFriends_AsyncTask();
Async.execute(user_id, secret_id, u_id, ut_);
}
// ///////////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
String response = "";
class SuggestFriends_AsyncTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
response = "";
response = functionspackage.methodes.HTTP_fileInf_OPhotos(
functionspackage.Constants.server_Web_Profiles
+ "/suggest/" + params[3] + "/" + params[2],
params[0], params[1], 0);
functionspackage.methodes.install_JSON_SuggestFriends(
SuggestFriends.this, response);
objDB = new dbManage(SuggestFriends.this);
SuggestFriendsItems = objDB.select_SuggestFriends();
objDB.CloseDataBase();
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
CustomSuggestFriends adapterSuggestFriends = new CustomSuggestFriends(
SuggestFriends.this, R.layout.items_suggestdriends,
SuggestFriendsItems);
gridView.setAdapter(adapterSuggestFriends);
gridView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE);
}
}
// ///////////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
private void initialise_View() {
gridView = (GridView) findViewById(R.id.DisplayPhoto_gridView);
gridView.setNumColumns(3);
gridView.setBackgroundColor(Color.BLACK);
send = (Button) findViewById(R.id.SendSuggestBotton);
cancel = (Button) findViewById(R.id.CancelsuggestFrindes);
}
}
this is the log
Use a Sparse Boolean Array
Check this link here
https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M
Check Romain Guy Solution. Use GridView instead of Listview.
Similar to the one answered here. Instead of listview use gridview.
in gridview checkbox is unchecked while scrolling gridview up and down
Heres' another example. Same use gridview instead of Listview
How to change the text of a CheckBox in listview?
Here's the complete example
public class MainActivity extends Activity implements
AdapterView.OnItemClickListener {
int count;
private CheckBoxAdapter mCheckBoxAdapter;
String[] GENRES = new String[] {
"Action", "Adventure", "Animation", "Children", "Comedy",
"Documentary", "Drama",
"Foreign", "History", "Independent", "Romance", "Sci-Fi",
"Television", "Thriller"
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final GridView listView = (GridView) findViewById(R.id.lv);
// listView.setItemsCanFocus(false);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(this);
mCheckBoxAdapter = new CheckBoxAdapter(this, GENRES);
listView.setAdapter(mCheckBoxAdapter);
Button b= (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
StringBuilder result = new StringBuilder();
result.append("Checked at position");
result.append("\n");
for(int i=0;i<mCheckBoxAdapter.mCheckStates.size();i++)
{
if(mCheckBoxAdapter.mCheckStates.get(i)==true)
{
result.append(mCheckBoxAdapter.mCheckStates.get(i)+" at"+i);
result.append("\n");
}
}
Toast.makeText(MainActivity.this, result, 10000).show();
}
});
}
public void onItemClick(AdapterView parent, View view, int
position, long id) {
mCheckBoxAdapter.toggle(position);
}
class CheckBoxAdapter extends ArrayAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
String[] gen;
CheckBoxAdapter(MainActivity context, String[] genres)
{
super(context,0,genres);
mCheckStates = new SparseBooleanArray(genres.length);
mInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gen= genres;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return gen.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.checkbox, null);
tv= (TextView) vi.findViewById(R.id.textView1);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :"+ gen [position]);
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
activit_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<GridView
android:id="#+id/lv"
android:layout_width="wrap_content"
android:numColumns="2"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
checkbox.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="34dp"
android:text="TextView" />
<CheckBox
android:id="#+id/checkBox1"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1"
android:layout_marginRight="22dp"
android:layout_marginTop="23dp" />
</RelativeLayout>
Snap shot
There is a lot of unecessary code in you question in my opinion (way better than too little, though), try change:
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
// -- buttonView.isChecked() changed to isChecked -- //
items.get(getPosition).setSelected(isChecked); // Set the value of checkbox to maintain its state.
Log.v("Changed",items.get(getPosition).getId_()+"");
}
If that does not work please show clearly where you read the false value and expect true.

Categories

Resources