i have an issue when i try to delete multiple checked items from my listView. If i start deleting from down to up items are removed from my list, but there is a problem when i do it from up to down or if random items are checked. The problem is the checked items are not deleted, but the unchecked items are deleted.
public class MainActivity extends ActionBarActivity {
private EditText etn,etl,etd;
private Button add;
private Button rmv;
private ListView listView;
private ArrayList<Data> list;
private MyCustomAdapter dataAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
listView = (ListView) findViewById(R.id.listView1);
list = new ArrayList<Data>();
add = (Button) findViewById(R.id.btn_add);
etn = (EditText) findViewById(R.id.edit_name);
eta = (EditText) findViewById(R.id.edit_lastname);
etd = (EditText) findViewById(R.id.edit_document);
rmv = (Button) findViewById(R.id.btn_delete);
displayView();
}
public class Data {
long document;
String name;
String lastname;
boolean selected = false;
public Data(long document, String name, String lastname, boolean selected){
this.document=document;
this.name=nom;
this.lastname=lastname;
this.selected = selected;
}
public String getName(){
return name;
}
public String getLastName(){
return lastname;
}
public long getDocument(){
return document;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
public void displayView(){
String name = etn.getText().toString();
String lastname= eta.getText().toString();
long document = Integer.valueOf(etd.getText().toString());
Data edata = new Data(document,name,lastname,false);
list.add(edata);
dataAdapter = new MyCustomAdapter(this,
R.layout.list_info, list);
listView.setAdapter(dataAdapter);
}
public void delete(View view){
deleteListItem();
}
private void deleteListItem(){
if(list.isEmpty()){
Toast.makeText(getApplicationContext(),
"No items to delete.",
Toast.LENGTH_LONG).show();
return;
}
int itemCount = listView.getCount();
for(int i=itemCount - 1 ; i>=0; i--){
Data aux = list.get(i);
if(aux.isSelected()){
dataAdapter.remove(aux);
}
}
dataAdapter.notifyDataSetChanged();
}
private class MyCustomAdapter extends ArrayAdapter<Data> {
private ArrayList<Data> list;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Data> list) {
super(context, textViewResourceId, list);
this.list = new ArrayList<Data>();
this.list.addAll(list);
}
private class ViewHolder {
TextView name;
TextView lname;
TextView doc;
CheckBox ck;
}
#Override
public View getView(int position, View convertView, ViewGroupparent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_info, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.ck = (CheckBox) convertView.findViewById(R.id.checkBox1);
holder.lname = (TextViewconvertView.findViewById(R.id.lastname);
holder.doc = (TextView)convertView.findViewById(R.id.document);
convertView.setTag(holder);
holder.ck.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
Data edata = (Data) cb.getTag();
Toast.makeText(getApplicationContext(),
"Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
edata.setSelected(cb.isChecked());
}
});
}
else {
holder = (ViewHolder) convertView.getTag();
}
Data aux = list.get(position);
long document = aux.getDocument();
holder.doc.setText("Doc:" + Long.toString(document));
holder.name.setText (" " + "Name:" + aux.getName()+ " ");
holder.lname.setText("Last name:" + aux.getLastName());
holder.ck.setTag(aux);
holder.ck.setChecked(aux.isSelected());
return convertView;
}
}
I think problem resides in this block :
int itemCount = listView.getCount();
for(int i=itemCount - 1 ; i>=0; i--){
Data aux = list.get(i);
if(aux.isSelected()){
dataAdapter.remove(aux);
}
}
Try like this :
int itemCount = listView.getCount();
for(int i=itemCount - 1 ; i>=0; i--){
Data aux = dataAdapter.getItem(i);
if(aux.isSelected()){
dataAdapter.remove(aux);
}
}
Note : I am not sure, Please try and let me know the result .:)
Related
setContentView(R.layout.activity_violation);
db = new DatabaseHelper(this);
sqLiteDatabase = db.getReadableDatabase();
spinner = (Spinner) findViewById(R.id.spinner1);
loadspinnerdata();
txtTexts = (TextView) findViewById(R.id.texts);
btnBack = (Button) findViewById(R.id.btnBack);
btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listviewData();
}
});
strSelectedItem = spinner.getSelectedItem().toString();
listview = (ListView) findViewById(R.id.listView);
LayoutInflater inflater = getLayoutInflater();
ViewGroup header = (ViewGroup) inflater.inflate(R.layout.list_header, listview, false);
listview.addHeaderView(header, null, false);
listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list_query = "select _id,section,offence,fine from tblSection";
Cursor clistview = sqLiteDatabase.rawQuery(list_query, null);
listadapter = new ListAdapter(this, clistview, 0);
listview.setAdapter(listadapter);private void listviewData() {
int cntChoice = listview.getCount();
String checked = "";
String unchecked = "";
SparseBooleanArray sparseBooleanArray = listview.getCheckedItemPositions();
for(int i = 0; i < cntChoice; i++)
{
if(sparseBooleanArray.get(i))
{
checked += listview.getItemAtPosition(i).toString() + "\n";
}
else if(!sparseBooleanArray.get(i))
{
unchecked+= listview.getItemAtPosition(i).toString() + "\n";
}
}
I am using cursorAdapter in order to populate listview from database?so I am not getting position as i get from getView method in arrayAdapter
public class ListAdapter extends CursorAdapter{
TextView tvSection,tvOffence,tvId,tvFine;
CheckBox chkBox;
ArrayAdapter<String> objects;
private boolean chkItem;
CompoundButton.OnCheckedChangeListener myCheckChangList;
public ListAdapter(Context context, Cursor c, int _id) {
super(context, c,_id);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
return LayoutInflater.from(context).inflate(R.layout.listview_item,viewGroup,false);
}
public class ViewHolder{
TextView tvSection,tvOffence,tvId,tvFine;
CheckBox chkBox;
boolean chkItem;
boolean selected = false;
public ViewHolder(boolean chkItem){
super();
this.chkItem=chkItem;
}
public ViewHolder() {
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder=null;
holder = new ViewHolder();
holder.tvSection = (TextView) view.findViewById(R.id.txtSection);
holder.tvOffence = (TextView) view.findViewById(R.id.txtOffence);
holder.tvId = (TextView) view.findViewById(R.id.txtId);
holder.tvFine = (TextView) view.findViewById(R.id.txtFine);
holder.chkBox = (CheckBox) view.findViewById(R.id.checkBox);
holder.chkBox.setOnCheckedChangeListener(myCheckChangList);
view.setTag(holder);
strFine=cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
String strSection = cursor.getString(cursor.getColumnIndexOrThrow("section"));
String strOffence = cursor.getString(cursor.getColumnIndexOrThrow("offence"));
int strFine = cursor.getInt(cursor.getColumnIndexOrThrow("fine"));
holder.tvSection.setText(strSection);
holder.tvOffence.setText(strOffence);
holder.tvFine.setText(String.valueOf(strFine));
final ViewHolder finalHolder = holder;
}
I tried this but this isn't working.I tried checkbox.setOnclicklistener which gives me the checked row value single item but not multiple checked item.I tried sparseboolean array also.
If you are trying to get selected values from listing using checkbox,try this way it will work
public class CardViewActivity extends AppCompatActivity {
private Toolbar toolbar;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<Student> studentList;
private Button btnSelection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
btnSelection = (Button) findViewById(R.id.btnShow);
studentList = new ArrayList<Student>();
for (int i = 1; i <= 15; i++) {
Student st = new Student("Student " + i, "androidstudent" + i
+ "#gmail.com", false);
studentList.add(st);
}
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Android Students");
}
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
// create an Object for Adapter
mAdapter = new CardViewDataAdapter(studentList);
// set the adapter object to the Recyclerview
mRecyclerView.setAdapter(mAdapter);
btnSelection.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String data = "";
List<Student> stList = ((CardViewDataAdapter) mAdapter)
.getStudentist();
for (int i = 0; i < stList.size(); i++) {
Student singleStudent = stList.get(i);
if (singleStudent.isSelected() == true) {
data = data + "\n" + singleStudent.getName().toString();
/*
* Toast.makeText( CardViewActivity.this, " " +
* singleStudent.getName() + " " +
* singleStudent.getEmailId() + " " +
* singleStudent.isSelected(),
* Toast.LENGTH_SHORT).show();
*/
}
}
Toast.makeText(CardViewActivity.this,
"Selected Students: \n" + data, Toast.LENGTH_LONG)
.show();
}
});
}
}
http://android-pratap.blogspot.in/2015/01/recyclerview-with-checkbox-example.html
On clicking outside the adapter, use the following code. "ListAdapter" should be the Adapter class name.
ListAdapter.unCheck((ViewGroup)view.getParent());
If your on clicking is inside the adapter, then ignore the above code and use the below one.
unCheck((ViewGroup)view.getParent());
make the following function in Adapter.
public static void unCheck(ViewGroup vg) {
for (int i = 0; i < vg.getChildCount(); i++) {
View v = vg.getChildAt(i);
if (v instanceof CheckBox) {
((CheckBox) v).setChecked(true);
} else if (v instanceof ViewGroup) {
unCheck((ViewGroup) v);
}
}
}
The above function will checked all the checkBox of the list view. Have Fun. Take Care.
I'm developing an android app which has a custom listview with a checkbox. I want to pass all the checked items from one activity to another. how should I pass them? and where should I manage the checkbox (to get all the checked items) in the custom adapter or the activity?
Note: I retrieve all the data from my server using json response.
Here's my Model :
public class Groups {
public String name;
public boolean selected= false;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public Groups() {
}
}
My Adapter:
public class AdapterMainActivity extends BaseAdapter{
Activity activity;
private LayoutInflater inflater;
List<Groups> groupsList;
public AdapterMainActivity(Activity activity, List<Groups> groupses) {
this.activity = activity;
this.groupsList = groupses;
}
#Override
public int getCount() {
return groupsList.size();
}
#Override
public Object getItem(int position) {
return groupsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_list, null);
TextView name = (TextView) convertView.findViewById(R.id.textViewName);
final CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
final Groups groups = groupsList.get(position);
name.setText(groupsList.get(position).getName());
checkBox.setChecked(groups.selected);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
groups.selected = isChecked;
MainActivity.getInstance().updateArrayList(groupsList);
}
});
}
return convertView;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
ListView listViewGroups;
Button buttonSentToActivity;
List<Groups> groupsList;
List<Groups> resultGroupList;
ArrayList<Boolean> areChecked;
List<String> finalArray;
private AdapterMainActivity adapterMainActivity;
static MainActivity yourActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourActivity = this;
groupsList= new ArrayList<Groups>();
resultGroupList= new ArrayList<Groups>();
ReadGroup(37);
adapterMainActivity = new AdapterMainActivity(this, groupsList);
listViewGroups = (ListView) findViewById(R.id.listViewGroups);
listViewGroups.setAdapter(adapterMainActivity);
buttonSentToActivity = (Button) findViewById(R.id.buttonSendTo2Activity);
buttonSentToActivity.setOnClickListener(buttonSentToActivityListener);
Log.e("Group list size ", String.valueOf(groupsList.size()));
finalArray = new ArrayList<>();
for (int i = 0; i < resultGroupList.size(); i++) {
if (resultGroupList.get(i).selected) {
finalArray.add(resultGroupList.get(i).getName());
Log.e("final array size", String.valueOf(finalArray.size()));
}
}
}
public void ReadGroup(long cid) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONArray readArray = jsonObject.getJSONArray("groups");
for (int i = 0; i < readArray.length(); i++) {
Log.e("i is: ", String.valueOf(i));
JSONObject jssonRow = readArray.getJSONObject(i);
String groupName = jssonRow.getString("name");
Groups groups = new Groups();
groups.setName(groupName);
Log.e("NAME is: ", groupName);
groupsList.add(groups);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapterMainActivity.notifyDataSetChanged();
}
};
Log.e("Client id is: ", String.valueOf(cid));
ReadGroupRequesr readGroupRequest = new ReadGroupRequesr(cid, responseListener);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(readGroupRequest);
Log.e("out of the loop", "");
}
public static MainActivity getInstance() {
return yourActivity;
}
public void updateArrayList(List<Groups> arrayList) {
this.resultGroupList = arrayList;
}
View.OnClickListener buttonSentToActivityListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
//Bundle b= new Bundle();
//b.putStringArrayList("arrayList", (ArrayList<String>) finalArray);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putStringArrayListExtra("arrayList", (ArrayList<String>) finalArray);
//intent.putExtras(b);
Log.e("final array size", String.valueOf(finalArray.size()));
startActivity(intent);
}
};
}
At the very first, manage your checkboxes :
In your activity class add a boolean array or arraylist having size same as your list array size and initialize it with all value as false initially :
String[] titlesArray;
ArrayList<Boolean> arrChecked;
// initialize arrChecked boolean array and add checkbox value as false initially for each item of listview
arrChecked = new ArrayList<Boolean>();
for (int i = 0; i < titles.size(); i++) {
arrChecked.add(false);
}
Now replace your adapter class with this :
class VivzAdapter extends ArrayAdapter<String> implements OnCheckedChangeListener {
Context context;
int[] images;
String[] titlesArray, descrptionArray;
List<Integer> positions = new ArrayList<Integer>();
ArrayList<Boolean> arrChecked;
VivzAdapter(Context context, String[] titles, int[] images, String[] description, ArrayList<Boolean> arrChecked) {
super(context, R.layout.single_row, R.id.textView1, titles);
this.context = context;
this.images = images;
this.titlesArray = titles;
this.descrptionArray = description;
this.arrChecked = arrChecked;
}
class MyViewHolder {
ImageView myImage;
TextView myTitle;
TextView myDescription;
CheckBox box;
MyViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.imageView1);
myTitle = (TextView) v.findViewById(R.id.textView1);
myDescription = (TextView) v.findViewById(R.id.textView2);
box = (CheckBox) v.findViewById(R.id.checkBox1);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder holder = null;
if (row == null) {
// 1.Âștime
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//row contem RelativeLayout(root) em single_row.xml
row = inflater.inflate(R.layout.single_row, parent, false);
holder = new MyViewHolder(row);
row.setTag(holder);
//Log.d("VIVZ", "Creating a new Row");
} else {
//reciclamos aqui, qeremos usar antigo objecto holder
holder = (MyViewHolder) row.getTag();
//Log.d("VIVZ", "Recycling stuff");
}
holder.myImage.setImageResource(images[position]);
holder.myTitle.setText(titlesArray[position]);
holder.myDescription.setText(descrptionArray[position]);
//set position as id
holder.box.setId(position);
//set onClickListener of checkbox rather than onCheckedChangeListener
holder.box.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
if (arrChecked.get(id)) {
//if checked, make it unchecked
arrChecked.set(id, false);
} else {
//if unchecked, make it checked
arrChecked.set(id, true);
}
}
});
//set the value of each checkbox from arrChecked boolean array
holder.box.setChecked(arrChecked.get(position));
return row;
}
}
After that, implement click listener of send button say btnSend button (I am considering that you are sending your data from one activity to another activity on click of send button) :
btnSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<String> arrTempList = new ArrayList();
for(int i=0; i<titles.size(); i++){
if(arrChecked.get(i) == true){
arrTempList.add(titles[i]);
}
}
// here you can send your arrTempList which is having checked items only
}
});
Here's the solution for this Question:
My adapter:
public class ChooseContactsAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
public ArrayList<Contacts> contactsList;
public CheckBox checkBoxAdapter;
public ChooseContactsAdapter(Activity activity, ArrayList<Contacts> group) {
this.activity = activity;
this.contactsList = group;
}
#Override
public int getCount() {
return contactsList.size();
}
#Override
public Object getItem(int position) {
return contactsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_choose_contacts_sms,
null);
final TextView fNAme = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactFName);
TextView LName = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactLName);
checkBoxAdapter = (CheckBox) convertView.findViewById(R.id.checkBoxSelectContact);
checkBoxAdapter.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
CheckBox cb = (CheckBox) view;
Contacts contacts = (Contacts) cb.getTag();
contacts.setSelected(cb.isChecked());
Toast.makeText(activity.getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
}
});
final Contacts contacts = contactsList.get(position);
fNAme.setText(contacts.getContactFName());
LName.setText(contacts.getContactLName());
checkBoxAdapter.setChecked(contacts.isSelected());
checkBoxAdapter.setTag(contacts);
}
return convertView;
}
}
In my activity I have button to go from 1 activity to the 2 activity:
private View.OnClickListener buttonSubmitGroupListener =new View.OnClickListener() {
#Override
public void onClick(View view) {
List <Integer> contactsIDArray= new ArrayList<Integer>();
List<Contacts> arrayOfContacts= chooseContactsAdapter.contactsList;
for(int i=0; i< arrayOfContacts.size(); i++){
Contacts contacts= arrayOfContacts.get(i);
if(contacts.isSelected()==true){
contactsIDArray.add(contacts.getContactID());
}
}
for (int i = 0; i < contactsIDArray.size(); i++) {
Log.e("Id Array size ", String.valueOf(contactsIDArray.size()));
Log.e("Selected id ", String.valueOf(contactsIDArray.get(i)));
}
intent = new Intent(getApplicationContext(), SendSMSActivity.class);
Bundle b = new Bundle();
b.putIntegerArrayList("checkedContacts", (ArrayList<Integer>) contactsIDArray);
intent.putExtras(b);
startActivity(intent);
}
};
Second Activity add this code:
Bundle b = getIntent().getExtras();
List<Integer> result = new ArrayList<Integer>();
result = b.getIntegerArrayList("checkedContacts");
I made a listview from db and I added onitemclicklistener. When I click on the item it will take me to the next activity and show full detail of the item. I also added a checkbox on the listview which checks the item. The problem is that when I click on the checkbox it wont work, but when I click on the item, it starts the next activity and after it, when I go back to the listview and try again to click on the checkbox, then this item checkbox works and the other one doesn't work. Also when I select a second item from the listview and go back then the checkbox works. Checkbox only works on that item with at least one time click. Does someone have an idea of what could be causing this problem? Here's my Java:
public class DataListActivity extends Activity {
ListView listView;
SQLiteDatabase sqLiteDatabase;
FoodDbHelper foodDbHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
ListDataAdapter dataAdapter = null;
Button button;
DataProvider dataProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.data_list_layout);
checkButtonClick();
listView = (ListView)findViewById(R.id.list_View);
listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.row_layout);
listView.setAdapter(listDataAdapter);
foodDbHelper = new FoodDbHelper(getApplicationContext());
sqLiteDatabase = foodDbHelper.getReadableDatabase();
cursor = foodDbHelper.getInformations(sqLiteDatabase);
if (cursor.moveToFirst())
{
do {
String name,quantity,calorie,fat,protein,sugar,vitamins;
boolean selected = false;
String names = null;
name = cursor.getString(0);
quantity = cursor.getString(1);
calorie = cursor.getString(2);
fat = cursor.getString(3);
protein = cursor.getString(4);
sugar = cursor.getString(5);
vitamins = cursor.getString(6);
DataProvider dataProvider = new DataProvider(name,quantity,calorie,fat,protein,sugar,vitamins,names,selected);
listDataAdapter.add(dataProvider);
}while (cursor.moveToNext());
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,View view,int position, long id) {
String name = (String) ((TextView) view.findViewById(R.id.text_dish_name)).getText();
String quantity = (String) ((TextView) view.findViewById(R.id.text_dish_quantity)).getText();
String calorie = (String) ((TextView) view.findViewById(R.id.text_dish_calorie)).getText();
String fat = (String) ((TextView) view.findViewById(R.id.text_dish_fat)).getText();
String protein = (String) ((TextView) view.findViewById(R.id.text_dish_protein)).getText();
String sugar = (String) ((TextView) view.findViewById(R.id.text_dish_sugar)).getText();
String vitamins = (String) ((TextView) view.findViewById(R.id.text_dish_vitamins)).getText();
String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(getApplicationContext(),
"dish name is : " + name,
Toast.LENGTH_SHORT).show();
CheckBox names = (CheckBox) view.findViewById(R.id.checkBox1);
listView.setOnItemClickListener(this);
names.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox checkBox = (CheckBox) v;
DataProvider dataProvider = (DataProvider) checkBox.getTag();
Toast.makeText(getApplicationContext(),
"Clicked on Checkbox: " + dataProvider.getName() + checkBox.getText() +
" is " + checkBox.isChecked(),
Toast.LENGTH_SHORT).show();
dataProvider.setSelected(checkBox.isChecked());
}
});
Intent intent=new Intent(getApplicationContext(),Detail.class);
intent.putExtra("Dish name",name);
intent.putExtra("Dish quantity",quantity);
intent.putExtra("Dish calorie",calorie);
intent.putExtra("Dish fat",fat);
intent.putExtra("Dish protein",protein);
intent.putExtra("Dish sugar",sugar);
intent.putExtra("Dish vitamins",vitamins);
startActivity(intent);
}
});}
private void checkButtonClick() {
List list = new ArrayList();
listDataAdapter = new ListDataAdapter(this,
R.layout.row_layout,list);
Button myButton = (Button) findViewById(R.id.findSelected);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
responseText.append("The following dishes were selected...\n");
ArrayList<DataProvider> list = (ArrayList<DataProvider>) listDataAdapter.list;
for(int i=0;i<list.size();i++) {
DataProvider dataProvider = list.get(i);
if (dataProvider.isSelected()) {
responseText.append("\n" + dataProvider.getName()+" : " + dataProvider.getCalorie()+" kcal");
}
}
Toast.makeText(getApplicationContext(),
responseText, Toast.LENGTH_LONG).show();
}
});
}
}
public class DataProvider {
private String name = null;
private String quantity;
private String calorie;
private String fat;
private String protein;
private String sugar;
private String vitamins;
private String names = null;
boolean selected = false;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getQuantity(){
return quantity;
}
public void setQuantity(String quantity){
this.quantity = quantity;
}
public String getCalorie(){
return calorie;
}
public void setCalorie(String calorie){
this.calorie = calorie;
}
public String getFat(){
return fat;
}
public void setFat(String fat){
this.fat = fat;
}
public String getProtein(){
return protein;
}
public void setProtein(String protein){
this.protein = protein;
}
public String getSugar() {return sugar; }
public void setSugar(String sugar) {this.sugar = sugar ;}
public String getVitamins() {return vitamins; }
public void setVitamins(String vitamins) {this.vitamins = vitamins ;}
public String getNames() {return names; }
public void setNames(String names) {this.names = names ;}
public boolean isSelected()
{return selected;}
public void setSelected(boolean selected) {this.selected = selected;}
public DataProvider(String name,String quantity,String calorie, String fat,String protein,String sugar,String vitamins,String names, boolean selected){
this.name = name;
this.quantity = quantity;
this.calorie = calorie;
this.fat = fat;
this.protein = protein;
this.sugar = sugar;
this.vitamins = vitamins;
this.names = names;
this.selected = selected;
}
public void add(List list) {
}
}
public class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();
public ListDataAdapter(Context context, int resource) {
super(context, resource);
}
public ListDataAdapter(DataListActivity dataListActivity, int row_layout, List list) {
super(dataListActivity, row_layout, list);
}
static class LayoutHandler{
TextView name,quantity,calorie,fat,protein,sugar,vitamins;
CheckBox names;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null)
{
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.name = (TextView)row.findViewById(R.id.text_dish_name);
layoutHandler.quantity = (TextView)row.findViewById(R.id.text_dish_quantity);
layoutHandler.calorie = (TextView)row.findViewById(R.id.text_dish_calorie);
layoutHandler.fat = (TextView)row.findViewById(R.id.text_dish_fat);
layoutHandler.protein = (TextView)row.findViewById(R.id.text_dish_protein);
layoutHandler.sugar = (TextView)row.findViewById(R.id.text_dish_sugar);
layoutHandler.vitamins = (TextView)row.findViewById(R.id.text_dish_vitamins);
layoutHandler.names = (CheckBox) row.findViewById(R.id.checkBox1);
row.setTag(layoutHandler);
}
else
{
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider)this.getItem(position);
layoutHandler.name.setText(dataProvider.getName());
layoutHandler.quantity.setText(dataProvider.getQuantity());
layoutHandler.calorie.setText(dataProvider.getCalorie());
layoutHandler.fat.setText(dataProvider.getFat());
layoutHandler.protein.setText(dataProvider.getProtein());
layoutHandler.sugar.setText(dataProvider.getSugar());
layoutHandler.vitamins.setText(dataProvider.getVitamins());
layoutHandler.names.setChecked(dataProvider.isSelected());
layoutHandler.names.setTag(dataProvider);
return row;
}
}
Thanks in advance
You need to do some of the things:
Step 1:
Need to modify getView..
Here only you need to add the action for checkbox
example :
layoutHandler.names.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox checkBox = (CheckBox) v;
DataProvider dataProvider = (DataProvider) checkBox.getTag();
Toast.makeText(getApplicationContext(),
"Clicked on Checkbox: " + dataProvider.getName() + checkBox.getText() +
" is " + checkBox.isChecked(),
Toast.LENGTH_SHORT).show();
dataProvider.setSelected(checkBox.isChecked());
}
});
Step 2:
Once you are add checkBox in a listView row then click action causing issues.
You can solve this that is you need to trigger itemclick action from getView method
example:
//I am adding an extra widget
layoutHandler.layout = (LinearLayout)row.findViewById(R.id.linear_layout);
then click action
layoutHandler.layout.setOnclick.....
Under this trigger item click action using performItemClick
layoutHandler.layout.performItemClick(...
Hello I am new in android
I have some dificulty to add element in daynamic listview.
When I click on TextView(tv) it should be add element at the end of the ArrayList but when i scroll down to the listview it crashed with indexoutofbound exception.
public class PosterList extends Activity
{
MyCustomAdapter dataAdapter = null;
ArrayList<Country> countryList = new ArrayList<Country>();
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.posterlist);
//Click on textview to add element in contrylist
tv = (TextView) findViewById(R.id.myFilter);
tv.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Country country = new Country("df","df","df","m");
countryList.add(country);
dataAdapter.notifyDataSetChanged();
}
});
displayListView();
}
private void displayListView()
{
//Parse my JSON and store it in to different arrays
for(int k=0;k<len;k++)
{
Country country = new Country(subcategory[k],caseid[k],time[k],newpost[k]);
countryList.add(country);
}
dataAdapter = new MyCustomAdapter(this,R.layout.country_info, countryList);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
Country country = (Country) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
country.getContinent(), Toast.LENGTH_SHORT).show();
}
});
}
private class MyCustomAdapter extends ArrayAdapter<Country>
{
private ArrayList<Country> originalList;
private ArrayList<Country> countryList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Country> countryList) {
super(context, textViewResourceId, countryList);
this.countryList = new ArrayList<Country>();
this.countryList.addAll(countryList);
this.originalList = new ArrayList<Country>();
this.originalList.addAll(countryList);
}
private class ViewHolder
{
TextView code;
TextView name;
TextView continent;
TextView region;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.country_info, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.continent = (TextView) convertView.findViewById(R.id.continent);
holder.region = (TextView) convertView.findViewById(R.id.region);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
Country country = countryList.get(position);
holder.code.setText(country.getCode());
holder.name.setText(country.getName());
holder.continent.setText(country.getContinent());
holder.region.setText(country.getRegion());
return convertView;
}
}
}
Here is my Country class,can anybody help me out what is wrong with this code?
`enter code here`public class Country {
String code = null;
String name = null;
String continent = null;
String region = null;
public Country(String code, String name, String continent, String region) {
super();
this.code = code;
this.name = name;
this.continent = continent;
this.region = region;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContinent() {
return continent;
}
public void setContinent(String continent) {
this.continent = continent;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
#Override
public String toString() {
return code + " " + name + " "
+ continent + " " + region;
}
Get rid of these fields in your adapter
private ArrayList<Country> originalList;
private ArrayList<Country> countryList;
You are modifying the countryList that is being passed to the super call in your adapter but you are reading from the countryList that is stored as a field inside of your adapter which never gets modified when you add a new country!
You are creating a copy of your original countrylist.. but you never modify the copy after creating it
I'm having problem with coding how to count all numbers that user inserted in TextView in ListView...
Here is my app... All I need to now is how to get the sum from rows in list view and show them in another text view:
This is my Main Activity:
public class MainActivity extends Activity {
private Adapter adapter;
private ArrayList<Ruka> fetch = new ArrayList<Ruka>();
Button bt;
EditText et;
TextView tv;
TextView mi;
TextView vi;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Inflate the menu; this adds items to the action bar if it is present.
bt = (Button) findViewById(R.id.button1);
et = (EditText) findViewById(R.id.editText1);
tv = (TextView) findViewById(R.id.textView1);
mi = (TextView) findViewById(R.id.textViewMi);
vi = (TextView) findViewById(R.id.textViewVi);
lv = (ListView) findViewById(R.id.lista);
// final String input = et.getText().toString();
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (et.getText().length() == 0) {
Toast.makeText(this, "test",
Toast.LENGTH_SHORT).show();
return;
}
if (Float.valueOf(et.getText().toString()) >= 12) {
Toast.makeText(this,
"test2", Toast.LENGTH_SHORT)
.show();
return;
}
String input = et.getText().toString();
if (null != input && input.length() > 0) {
String maxpunti = "11";
int a = Integer.parseInt(maxpunti);
int b = Integer.parseInt(input);
int c = a - b;
String input2 = String.valueOf(c);
Ruka one = new Ruka(input, input2);
fetch.add(one);
et.setText("");
adapter = new Adapter(MainActivity.this, R.id.lista, fetch);
lv.setAdapter(adapter);
}
}
});
}
}
This is my Adapter:
public class Adapter extends ArrayAdapter<Ruka>{
private ArrayList<Ruka> entries;
private Activity activity;
public Adapter(Activity a, int textViewResourceId, ArrayList<Ruka> entries) {
super(a, textViewResourceId, entries);
this.entries = entries;
this.activity = a;
}
public static class ViewHolder{
public TextView item1;
public TextView item2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.item1 = (TextView) v.findViewById(R.id.textView1);
holder.item2 = (TextView) v.findViewById(R.id.textView2);
v.setTag(holder);
}
else
holder=(ViewHolder)v.getTag();
final Ruka custom = entries.get(position);
if (custom != null) {
holder.item1.setText(custom.getFirst());
holder.item2.setText(custom.getSecond());
}
return v;
}
}
UPDATE
Here is Ruka.java:
public class Ruka {
private String customBig;
private String customSmall;
public Ruka(String string, String string2) {
this.customBig = string;
this.customSmall = string2;
}
public String getFirst() { return customBig; }
public void setcustomBig(String getFirst) { this.customBig = getFirst; }
public String getSecond() { return customSmall; }
public void setcustomSmall(String getSecond) { this.customSmall = getSecond; }
}
If someone can find solution... Please... Anyone :)
I would say add a method to your adapter that does this:
public int getSum(){
int sum;
for(Ruka ruka: entries){
sum += ruka.getFirst();
}
}
Assuming ruka.getFirst() is a numeric value.