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.
Related
I have a custom list view with a TextView and three ImageViews. On click of image view I want to start a new activity and pass the data of specific position to next activity. But I am getting null pointer exception.
I have use this for refernce http://jmsliu.com/2444/click-button-in-listview-and-get-item-position.html
Here is my code. This is main Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_employees);
toolbar = (Toolbar) findViewById(R.id.app_bar);
toolbar.setTitle("Manage Employees");
nPregress = (ProgressBar) findViewById(R.id.toolbar_progress_bar);
nPregress.setVisibility(View.GONE);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mainList = (ListView) findViewById(R.id.manageemployeeList);
employee1 = new ArrayList<Pojo>();
tii = new ArrayList<String>();
SharedPreferences prefs = getSharedPreferences("MyPref4", MODE_PRIVATE);
Set<String> set1 = prefs.getStringSet("employeename", null);
if (set1 != null ) {
List<String> nameList = new ArrayList<String>(0);
nameList.addAll(set1);
for (int i = 0; i < set1.size(); i++) {
pojo = new Pojo();
pojo.setMgEmpName(nameList.get(i));
employee1.add(pojo);
Log.e("namemmee0", "" + nameList.get(i));
}
mainAdapter = new EmployeesAdapter(EmployeesActivity.this, employee1);
mainList.setAdapter(mainAdapter);
} else {
new NetCheck().execute();
}
new NetCheck().execute();
emp_edit = (ImageView) findViewById(R.id.imgedit);
emp_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentRow = (View) v.getParent();
mainList = (ListView) parentRow.getParent();
final int position = mainList.getPositionForView(parentRow);
String emp_name = employee1.get(position).getMgEmpName().toString();
Intent i = new Intent(EmployeesActivity.this, EditEmployee.class);
i.putExtra("empname", emp_name);
startActivity(i);
}
});
}
I am getting exception at this line
emp_edit.setOnClickListener(new View.OnClickListener()
How can i do this? Please help me.
This is my Adapter. I have tried onClickListener in adpter also But i am not gtting proper data in next activity.. I get same value even if i select different list view items
public class EmployeesAdapter extends BaseAdapter {
TextView categoryName;
Pojo pojo;
private Context activity1;
ArrayList<Pojo> data1;
private ArrayList<Pojo> arraylist1 = null;
public static LayoutInflater inflater;
ImageView edit, delete, historyy;
String del_empid;
public EmployeesAdapter(Context ctx, ArrayList<Pojo> employee1) {
// TODO Auto-generated constructor stub
activity1 = ctx;
data1 = employee1;
inflater = (LayoutInflater) activity1
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arraylist1 = new ArrayList<Pojo>();
this.arraylist1.addAll(data1);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data1.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
v = inflater.inflate(R.layout.manage_emp_list, parent, false);
pojo = data1.get(position);
categoryName = (TextView) v.findViewById(R.id.employeeName);
categoryName.setText(pojo.getMgEmpName());
edit = (ImageView) v.findViewById(R.id.imgedit);
delete = (ImageView) v.findViewById(R.id.imgdelete);
historyy = (ImageView) v.findViewById(R.id.imgHistory);
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity1, EditEmployee.class);
intent.putExtra("empname", "" + pojo.getMgEmpName());
intent.putExtra("empmobile", "" + pojo.getMgEmpContact());
intent.putExtra("empemail", "" + pojo.getMgEmpEmail());
intent.putExtra("empappcost", "" + pojo.getMgEmpAppCost());
activity1.startActivity(intent);
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
del_empid = pojo.getMgEmp_id();
new NetCheck().execute();
}
});
historyy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity1, MainActivity.class);
activity1.startActivity(intent);
}
});
return v;
}
manage_emp_list of the custom list view
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/employeeName"
android:textColor="#000000"
android:textSize="18dp"
android:padding="5dp"
android:layout_marginLeft="5dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgdelete"
android:src="#drawable/delete32"
android:layout_marginRight="12dp"
android:layout_marginEnd="12dp"
android:layout_alignBottom="#+id/employeeName"
android:layout_toLeftOf="#+id/imgedit"
android:layout_toStartOf="#+id/imgedit"
android:clickable="true"
android:onClick="delete_empoyee"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgedit"
android:layout_marginRight="15dp"
android:layout_marginEnd="15dp"
android:src="#drawable/edit32"
android:layout_alignTop="#+id/imgdelete"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:clickable="true"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgHistory"
android:src="#drawable/history32"
android:clickable="true"
android:onClick="employee_history"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/imgdelete"
android:layout_toStartOf="#+id/imgdelete"
/>
Try this, There may be position mismatch when store it locally
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity1, EditEmployee.class);
intent.putExtra("empname", "" + data1.get(position).getMgEmpName());
intent.putExtra("empmobile", "" + data1.get(position).getMgEmpContact());
intent.putExtra("empemail", "" + data1.get(position).getMgEmpEmail());
intent.putExtra("empappcost", "" + data1.get(position).getMgEmpAppCost());
activity1.startActivity(intent);
}
});
Your getView() method should look like this in your adapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
pojo = data1.get(position);
ViewHolder holder;
if (pojo != null) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.manage_emp_list, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.categoryName.setText(pojo.getMgEmpName());
//holder.edit.setOnClickListener()...
//holder.delete.setOnclickListener()...
}
return convertView;
}
And add a static class in to your Adapter:
static class ViewHolder {
TextView categoryName;
ImageView edit;
ImageView delete;
ImageView historyy;
public ViewHolder(View view) {
categoryName = (TextView) v.findViewById(R.id.employeeName);
edit = (ImageView) v.findViewById(R.id.imgedit);
delete = (ImageView) v.findViewById(R.id.imgdelete);
historyy = (ImageView) v.findViewById(R.id.imgHistory);
}
}
I have a customListView with checkbox and textview and i woul like to sum the value that are checked and show it on the textview.
this is my code:
row2.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?android:attr/activatedBackgroundIndicator"
android:descendantFocusability="blocksDescendants"
android:padding="1dp" >
<CheckBox
android:id="#+id/cbBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true">
</CheckBox>
<TextView
android:id="#+id/tv_qta1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/tv_grm"
android:gravity="center_vertical|right"
android:paddingRight="5dp"
android:text="#string/v10000"
android:textColor="#android:color/holo_red_dark"
android:textSize="#dimen/size_edit_M"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_alignParentBottom="true" />
<TextView
android:id="#+id/tv_qta2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical|right"
android:paddingRight="5dp"
android:text="#string/v10000"
android:textColor="#000000"
android:textSize="#dimen/size_edit_M"
android:textStyle="bold"
android:layout_alignTop="#+id/tv_qta1"
android:layout_toLeftOf="#+id/tv_qta1"
android:layout_toStartOf="#+id/tv_qta1"
android:layout_marginLeft="10dp"
android:layout_alignParentBottom="true" />
<TextView
android:id="#+id/tv_grm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/grammi"
android:textColor="#000000"
android:textSize="#dimen/size_edit_M"
android:layout_alignParentTop="true"
android:gravity="center_vertical"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:id="#+id/tv_prodotto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="2dp"
android:text="#string/prodotto"
android:textColor="#000000"
android:textSize="#dimen/size_edit_M"
android:textStyle="italic"
android:layout_toRightOf="#+id/cbBox"
android:layout_alignParentTop="true"
android:gravity="center_vertical"
android:layout_toLeftOf="#+id/tv_qta2"
android:layout_toStartOf="#+id/tv_qta2"
android:layout_alignParentBottom="true" />
</RelativeLayout>
int the actyvity i create the listviecustom
if(userAdapterRct1 == null){
userAdapterRct1 = new ItemsListAdapterRct(getActivity().getBaseContext(), userArrayRct1);
userListRct1 = (ListView) rootView.findViewById(R.id.ListView01);
userListRct1.setItemsCanFocus(true);
userAdapterRct1.notifyDataSetChanged();
userListRct1.setAdapter(userAdapterRct1);
userAdapterRct1.notifyDataSetChanged();
}else
userAdapterRct1.notifyDataSetChanged();
if(userAdapterRct1 != null){
userListRct1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View v,int position, long id) {
// TODO Auto-generated method stub
RelativeLayout listItem = (RelativeLayout) v;
TextView clickedItemView = (TextView) listItem.findViewById(R.id.tv_prodotto);
CheckBox cbView = (CheckBox) listItem.findViewById(R.id.cbBox);
cbView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//Integer rct = (Integer) buttonView.getTag();
// create the suf of items checked
}
});
}
});
}
how create the sum of item checked?
ItemsListAdapterRct.java
class ItemsListAdapterRct extends BaseAdapter {
private LayoutInflater vi;
private ArrayList<User> data = new ArrayList<User>();
Context context;
public ItemsListAdapterRct(Context context, /*int layoutResourceId,*/ ArrayList<User> data) {
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.data = data;
this.context = context;
}
/** Add white line */
public void addItem(User item) {
data.add(item);
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
User p = getProduct(position);
if (convertView == null) {
holder = new ViewHolder();
convertView = vi.inflate(R.layout.row2, parent, false);//null);
holder.name = (TextView) convertView.findViewById(R.id.tv_prodotto);
holder.qty_ing = (TextView) convertView.findViewById(R.id.tv_qta1);
holder.qty_risc = (TextView) convertView.findViewById(R.id.tv_qta2);
holder.cbView = (CheckBox) convertView.findViewById(R.id.cbBox);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
if(holder.name != null) {
holder.name.setText(data.get(position).getName());
}
if(holder.qty_ing != null) {
holder.qty_ing.setText(String.valueOf(data.get(position).getQtyIng()));
}
if(holder.qty_risc != null) {
holder.qty_risc.setText(String.valueOf(data.get(position).getQtyRis()));
}
if(holder.cbView != null) {
holder.cbView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
getProduct((Integer) buttonView.getTag()).box = isChecked;
//
// // aggiorno il db
// DatabaseHelper dbRcp = new DatabaseHelper(context, ImportFragment.DB_DATABASE_STORE);
// int pos = (Integer) buttonView.getTag();
// Ricetta p = getProduct(pos);
// String box = "0";
// if(p.box) box = "1";
// long res = dbRcp.update_Riscala(p.id, p.name, "0", box);
// // Don't forget to close database connection
// dbRcp.closeDB();
}
});
//cbBuy.setOnCheckedChangeListener(myCheckChangList);
holder.cbView.setTag(position);
holder.cbView.setChecked(p.box);
}
return convertView;
}
User getProduct(int position) {
return ((User) getItem(position));
}
// /** Sort shopping list by name ascending */
// public void sortByNameAsc() {
// Comparator<User> comparator = new Comparator<User>() {
//
// #Override
// public int compare(User object1, User object2) {
// return ((String) object1.getName()).compareTo((String) object2.getName());
// }
// };
// Collections.sort(data, comparator);
// notifyDataSetChanged();
// }
//
// /** Sort shopping list by name descending */
// public void sortByNameDesc() {
// Comparator<User> comparator = new Comparator<User>() {
//
// #Override
// public int compare(User object1, User object2) {
// return ((String) object2.getName()).compareTo((String) object1.getName());
// }
// };
// Collections.sort(data, comparator);
// notifyDataSetChanged();
// }
//
// /** Sort shopping list by date ascending */
// public void sortByTipoAsc() {
// Comparator<User> comparator = new Comparator<User>() {
//
// #Override
// public int compare(User object1, User object2) {
// return ((String) object1.getTipoIng()).compareTo((String) object2.getTipoIng());
// }
// };
// Collections.sort(data, comparator);
// notifyDataSetChanged();
// }
//
// /** Sort shopping list by date descending */
// public void sortByTipoDesc() {
// Comparator<User> comparator = new Comparator<User>() {
//
// #Override
// public int compare(User object1, User object2) {
// return ((String) object2.getTipoIng()).compareTo((String) object1.getTipoIng());
// }
// };
// Collections.sort(data, comparator);
// notifyDataSetChanged();
// }
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
/** Helper class acting as a holder of the information for each row */
private class ViewHolder {
public CheckBox cbView;
public TextView name;
public TextView qty_risc;
public TextView qty_ing;
}
}
I would like to sum the value signed by red and put the result in the bottom textview
view image
try Check List, it is demonstrating the same scenario [List with checks showing sum of the checked]
In your ItemsListAdapterRct declare int val
int totalChecked = 0;
then in your onCheckedChanged
if(isChecked){
totalChecked+=1;
}else if(totalChecked!=0){
totalChecked-=1;
}
And write this function to your onCheckedChanged
public int getTotalChecked(){
return totalChecked;
}
then call it when you need;
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{
....
}
My project contains listView(homelistView) that contains button(btnList).
When I click on button(btnList) it must go to another Activity. I tried a lot but I didn't find a good example.
Please suggest me a good example regarding this.
Below is my code:
Here is my listview contains button. When on click of button it must go to other activity
--------------------------------A--
text text button(btnList) B
--------------------------------C---
text text BUTTON(btnList) D
--------------------------------E--
homempleb.xml
Before i used this code in xml. buttonlist worked fine for me as per below code
<ListView
android:id="#+id/homelistView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.04"
android:dividerHeight="0dip" >
</ListView>
EfficientAdapter.java
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context=context;
}
In your ViewHolder class you need to add `Button btnList.`
holder.btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent next=new Intent(context, SeviceDetails.class);
context.startActivity(next);
}
});
homempleb.xml
Currently i added scroll index to my listview and changed the code as per below.. Listbutton is not working for me now.. Plz help me u can see code for quick reference in EfficientAdapter.JAVA-----> getview method--->holder.btnList.
<com.woozzu.android.widget.IndexableListView
android:id="#+id/homelistView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.04"
android:dividerHeight="0dip" >
</com.woozzu.android.widget.IndexableListView>
MainActivity.java
public class MainActivity extends Activity implements
SearchView.OnQueryTextListener, SearchView.OnCloseListener {
private ListView listView;
// private IndexableListView listView;
private SearchView search;
EfficientAdapter objectAdapter;
// EfficientAdapter2 objectAdapter1;
int textlength = 0;
private CheckBox checkStat, checkRoutine, checkTat;
private ArrayList<Patient> patientListArray;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homempleb);
Log.i("scan", " txtScanResult ");
ActionItem nextItem = new ActionItem();
final QuickAction quickAction = new QuickAction(this,
QuickAction.VERTICAL);
quickAction.addActionItem(nextItem);
quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
#Override
public void onDismiss() {
Toast.makeText(getApplicationContext(), "Dismissed",
Toast.LENGTH_SHORT).show();
}
});
search = (SearchView) findViewById(R.id.searchView1);
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
quickAction.show(v);
}
});
checkStat = (CheckBox) findViewById(R.id.checkBoxStat);
checkRoutine = (CheckBox) findViewById(R.id.checkBoxRoutine);
checkTat = (CheckBox) findViewById(R.id.checkBoxTat);
checkStat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkStat.setChecked(true);
Toast.makeText(MainActivity.this, "STAT",
Toast.LENGTH_SHORT).show();
checkRoutine.setChecked(false);
checkTat.setChecked(false);
}
}
});
checkRoutine.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkRoutine.setChecked(true);
Toast.makeText(MainActivity.this, "ROUTINE",
Toast.LENGTH_SHORT).show();
checkStat.setChecked(false);
checkTat.setChecked(false);
}
}
});
checkTat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkTat.setChecked(true);
Toast.makeText(MainActivity.this, "TAT Effeciency",
Toast.LENGTH_SHORT).show();
checkRoutine.setChecked(false);
checkStat.setChecked(false);
}
}
});
// listView = (IndexableListView) findViewById(R.id.homelistView);
listView = (ListView) findViewById(R.id.homelistView);
listView.setTextFilterEnabled(true);
listView.setFastScrollEnabled(true);
listView.setFastScrollAlwaysVisible(true);
objectAdapter = new EfficientAdapter(this);
listView.setAdapter(objectAdapter);
Button refreshButton = (Button) findViewById(R.id.refreshButton);
refreshButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// objectAdapter1 = new EfficientAdapter2(MainActivity.this);
objectAdapter = new EfficientAdapter(MainActivity.this);// adapter
// with
// new
// data
listView.setAdapter(objectAdapter);
Log.i("notifyDataSetChanged", "data updated");
// objectAdapter1.notifyDataSetChanged();
objectAdapter.notifyDataSetChanged();
}
});
}
#Override
public boolean onClose() {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
}
EfficientAdapter.JAVA
public class EfficientAdapter extends BaseAdapter implements SectionIndexer {
private String mSections = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
ArrayList<Patient> patientListArray;
private LayoutInflater mInflater;
private Context context;
ViewHolder holder;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
String patientListJson = CountriesList.jsonData;
JSONObject jssson;
try {
jssson = new JSONObject(patientListJson);
patientListJson = jssson.getString("PostPatientDetailResult");
} catch (JSONException e) {
e.printStackTrace();
}
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray Jarray = parser.parse(patientListJson).getAsJsonArray();
patientListArray = new ArrayList<Patient>();
for (JsonElement obj : Jarray) {
Patient patientList = gson.fromJson(obj, Patient.class);
patientListArray.add(patientList);
Log.i("patientList", patientListJson);
}
}
/**
* sorting the patientListArray data
*/
public void sortMyData() {
// sorting the patientListArray data
Collections.sort(patientListArray, new Comparator<Object>() {
#Override
public int compare(Object o1, Object o2) {
Patient p1 = (Patient) o1;
Patient p2 = (Patient) o2;
return p1.getName().compareToIgnoreCase(p2.getName());
}
});
}
public int getCount() {
return patientListArray.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.homemplebrowview, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView.findViewById(R.id.name);
holder.text2 = (TextView) convertView.findViewById(R.id.mrn);
holder.text3 = (TextView) convertView.findViewById(R.id.date);
holder.text4 = (TextView) convertView.findViewById(R.id.age);
holder.text5 = (TextView) convertView.findViewById(R.id.gender);
holder.text6 = (TextView) convertView.findViewById(R.id.wardno);
holder.text7 = (TextView) convertView.findViewById(R.id.roomno);
holder.text8 = (TextView) convertView.findViewById(R.id.bedno);
holder.btnList = (Button) convertView.findViewById(R.id.listbutton);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text1.setText(Util.formatN2H(patientListArray.get(position)
.getName()));
holder.text2.setText(patientListArray.get(position).getMrnNumber());
holder.text3.setText(Util.formatN2H(patientListArray.get(position)
.getRoom()));
holder.text4.setText(Util.formatN2H(patientListArray.get(position)
.getAge()));
holder.text5.setText(Util.formatN2H(patientListArray.get(position)
.getGender()));
holder.text6.setText(Util.formatN2H(patientListArray.get(position)
.getWard()));
holder.text7.setText(Util.formatN2H(patientListArray.get(position)
.getRoom()));
holder.text8.setText(Util.formatN2H(patientListArray.get(position)
.getBed()));
holder.btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "STAT", Toast.LENGTH_SHORT).show();
Intent next = new Intent(context, Home.class);
Log.i("next23", "next");
context.startActivity(next);
}
});
return convertView;
}
static class ViewHolder {
public Button btnList;
public TextView text8;
public TextView text7;
public TextView text6;
public TextView text5;
public TextView text4;
public TextView text1;
public TextView text2;
public TextView text3;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public int getPositionForSection(int section) {
// sorting the patientListArray data
sortMyData();
// If there is no item for current section, previous section will be
// selected
for (int i = section; i >= 0; i--) {
for (int j = 0; j < getCount(); j++) {
if (i == 0) {
// For numeric section
for (int k = 0; k <= 9; k++) {
if (StringMatcher.match(
String.valueOf(patientListArray.get(j)
.getName().charAt(0)),
String.valueOf(k)))
return j;
}
} else {
if (StringMatcher.match(
String.valueOf(patientListArray.get(j).getName()
.charAt(0)),
String.valueOf(mSections.charAt(i))))
return j;
}
}
}
return 0;
}
public int getSectionForPosition(int position) {
return 0;
}
public Object[] getSections() {
String[] sections = new String[mSections.length()];
for (int i = 0; i < mSections.length(); i++)
sections[i] = String.valueOf(mSections.charAt(i));
return sections;
}
}
The problem is in onInterceptTouchEvent method. You are using IndexableListView from woozzu, and this class overrides onInterceptTouchEvent to return true. This means that IndexableListView always steal touch events from your child's views so it can provide it to IndexScroller. You can change this behavior if instead of returning true you enter this condition:
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (mScroller != null && mScroller.contains(ev.getX(), ev.getY()))
return true;
return super.onInterceptTouchEvent(ev);
}
This way only events meant to interact with IndexScroller will be consumed. Other events will be propagated to children's views, and your button will be clickable.
In your Efficient adapter class declare ViewHolder holder outside getView method
and do as MoshErsan said.
Also Change your
convertView = mInflater.inflate(R.layout.homemplebrowview, null);
to
convertView = mInflater.inflate(R.layout.homemplebrowview, parent,false);
in your adapter, just move
holder.btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "STAT", Toast.LENGTH_SHORT).show();
Intent next = new Intent(context, Home.class);
Log.i("next23", "next");
context.startActivity(next);
}
});
just before return convertView;
you need to set the listener every time the adapter returns a view.
I want to select all check boxes in a listview but I'm not able to get checkbox objects from the listview. I can select a single check box but not multiple check boxes.
Your suggestion are appreciable.
Code:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bir);
mainListView = (ListView) findViewById(R.id.mainListView);
selectall = (Button) findViewById(R.id.button1);
selectall.setOnClickListener(this);
save = (Button) findViewById(R.id.button2);
save.setOnClickListener(this);
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View item,
int position, long id) {
}
});
}
}
class Amphian:
private static class Amphian
{
private String name = "" ;
private boolean checked = false ;
public Amphian( String name )
{
this.name = name ;
}
public Amphian( String name, boolean checked )
{
this.name = name ;
this.checked = checked ;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
#Override
public String toString() {
return name ;
}
public void toggleChecked()
{
checked = !checked ;
}
}
class AmphiansArrayAdapter:
public class AmphiansArrayAdapter extends ArrayAdapter<Amphian>
{
Integer name[] =
{
R.raw.ducks_landing_in_water,
R.raw.flicker_chicks_feeding,
R.raw.geese_honking_loud,
R.raw.geese_honking_distant,
R.raw.gold_finch,
R.raw.humming_bird_feeding,
R.raw.indigo_bunting,
R.raw.loons,
R.raw.little_blue_heron_fishing,
R.raw.pelican_chick,
R.raw.purple_martins,
R.raw.red_winged_blackbird,
R.raw.shorebirds_close,
R.raw.shorebirds_distant,
R.raw.shorebirds_misc,
R.raw.shoreseabirds,
R.raw.snow_geese_flock,
R.raw.terns,
R.raw.tufted_titmouse,
R.raw.tundra_swans,
R.raw.wood_stork_chicks,
R.raw.woodpecker_tapping
};
private final LayoutInflater inflater;
public AmphiansArrayAdapter(Context context, List<Amphian> amphianList)
{
super( context, R.layout.simplerow, R.id.rowTextView, amphianList );
inflater = LayoutInflater.from(context) ;
}
#Override
public View getView( final int position, View convertView , ViewGroup parent)
{
final Amphian amphian=this.getItem(position);
mp=new MediaPlayer();
if ( convertView == null )
{
convertView = inflater.inflate(R.layout.simplerow, null);
// Find the child views.
textView = (TextView) convertView.findViewById( R.id.rowTextView );
checkBox = (CheckBox) convertView.findViewById( R.id.checkBox1 );
button = (Button)convertView.findViewById(R.id.button1);
// Optimization: Tag the row with it's child views, so we don't have to
// call findViewById() later when we reuse the row.
convertView.setTag( new AmphianViewHolder(textView,checkBox,button) );
// If CheckBox is toggled, update the planet it is tagged with.
checkBox.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View v)
{
cb= (CheckBox) v;
Log.e("cb",String.valueOf(cb));
Amphian amphian = (Amphian) cb.getTag();
Log.e("cb",String.valueOf(cb.getTag()));
amphian.setChecked(cb.isChecked());
Log.e("dd", "ddd");
}
});
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Button bu=(Button)v;
Amphian amphian;
//= (Amphian) bu.getTag();
//Log.e(String.valueOf(amphian),"ddd");
Try this.
public class MainActivity extends Activity implements OnClickListener {
public class LVSample3Adapter extends BaseAdapter{
private Context context;
private List<LVSample3Item> itemList;
public LVSample3Adapter(List<LVSample3Item> lstItems,
MainActivity mainActivity) {
// TODO Auto-generated constructor stub
this.context=mainActivity;
this.itemList=lstItems;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return itemList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return itemList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Log.e("lstItems1:", String.valueOf(position));
LVSample3Item item = itemList.get(position);
convertView =LayoutInflater.from(context).inflate(R.layout.list, parent, false);
TextView t1=(TextView)convertView.findViewById(R.id.textView1);
t1.setText(item.getTitle());
CheckBox chb1=(CheckBox)convertView.findViewById(R.id.checkBox1);
chb1.setChecked(item.getstate());
return convertView;
}
}
/** Called when the activity is first created. */
private ListView lv;
private ListAdapter adapter;
private Button btn1,btn2;
private List<LVSample3Item> lstItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1=(Button)findViewById(R.id.button1);
btn2=(Button)findViewById(R.id.button2);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
lstItems = new ArrayList<LVSample3Item>();
LVSample3Item item = new LVSample3Item("drinks",false);
lstItems.add(item);
item = new LVSample3Item("chat",false);
lstItems.add(item);
item = new LVSample3Item("chat1",true);
lstItems.add(item);
item = new LVSample3Item("chat2",false);
lstItems.add(item);
adapter = new LVSample3Adapter(lstItems, this);
lv=(ListView)findViewById(R.id.listView1);
lv.setAdapter(adapter);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.button1){
Log.e("lstItems:", String.valueOf(lstItems.size()));
for(int i=0;i<lstItems.size();i++){
LVSample3Item item=lstItems.get(i);
if(!item.getstate()){
item.setpath(true);
}
}
((BaseAdapter) adapter).notifyDataSetChanged();
}else if(v.getId()==R.id.button2){
for(int i=0;i<lstItems.size();i++){
LVSample3Item item=lstItems.get(i);
if(item.getstate()){
item.setpath(false);
}
}
((BaseAdapter) adapter).notifyDataSetChanged();
}
}
}
public class LVSample3Item implements Serializable {
private String title;
private boolean state;
public LVSample3Item(String title,boolean imagepath) {
this.title = title;
this.state=imagepath;
}
public String getTitle() {
return title;
}
public boolean getstate() {
return state;
}
public void setTitle(String title) {
this.title = title;
}
public void setpath(boolean imagepath) {
this.state = imagepath;
}
}
There is too much code to read, so I give you a sample how to do that:
int count = list.getCount();
for (int i = 0; i < count; i++) {
View child = list.getItemAtPosition(i);
//check that child..
}
or
int count = list.getChildCount();
for (int i = 0; i < count; i++) {
View child = list.getChildAt(i);
//check that child..
}
selectall.setOnClickListener(new onClickListener(){
#Override
public void onClick(View v) {
for (int i = 0; i < list.size(); i++) {
list.getItem(i).setChecked(true);
}
}
});
try doing soething like this