Checkbox not working properly on listview - android

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(...

Related

I want to store the multiple spinner checked value insert into sqlite database

My project is attendance based. When I select the checkbox to mark attendance of students, on button click it will save on my sqlite database. but here only save one value that is last value on spinner.
How can I store multiple checkbox value of spinner into database on button click with other values?
This is my attendancetakerclass:
attendancetakerclass
public class AttendanceTracker extends Activity {
// ArrayList<String> NameList;
DataBaseHelper dbHelper;
String classcode;
SQLiteDatabase db;
Button save_attendance;
String type2="student";
//String type1="student";
//RadioGroup rg;
TextView date,time;
static String class1;
String type;
String slot;
String datetime1;
String subject, bioid,datevalue,timevalue;
List<Model> bioid1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.attendancetaker);
dbHelper=new DataBaseHelper(AttendanceTracker.this);
this.db=dbHelper.getReadableDatabase();
date=(TextView)findViewById(R.id.tvdatetime);
datevalue=date.getText().toString();
time=(TextView)findViewById(R.id.tvtime);
timevalue=time.getText().toString();
String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
// textView is the TextView view that should display it
date.setText(currentDateTimeString);
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
time.setText(today.format("%k:%M:%S"));
//bioid=dbHelper.getbioid();
Bundle extras = this.getIntent().getExtras();
String inputfname1=extras.getString("firstn1");
String inputlname1=extras.getString("lastn1");
String inputclass=extras.getString("class");
String inputsub=extras.getString("sub");
String inputslot=extras.getString("type");
String inputprctslot=extras.getString("slot");
TextView viewfname = (TextView) findViewById(R.id.tvname);
viewfname.setText(inputfname1);
TextView viewlname = (TextView) findViewById(R.id.tvsurnamevalue);
viewlname.setText(inputlname1);
TextView viewclass = (TextView) findViewById(R.id.tvclassvalue);
viewclass.setText(inputclass);
classcode = viewclass.getText().toString();
TextView viewsub = (TextView) findViewById(R.id.tvsubjectname);
viewsub.setText(inputsub);
subject = viewsub.getText().toString();
TextView viewslot = (TextView) findViewById(R.id.tvslotvalue);
viewslot.setText(inputslot);
type = viewslot.getText().toString();
TextView viewprcts = (TextView) findViewById(R.id.tvprctsvalue);
viewprcts.setText(inputprctslot);
slot = viewprcts.getText().toString();
ListView studentList=(ListView)findViewById(R.id.take_attend_list);
bioid1=this.getbioid();
ArrayAdapter<Model> adapter = new MyAdapter(this,getdata(),getdatalname(),getbioid());
studentList.setAdapter(adapter);
}
public List<Model> getdata()
{
List<Model> list = new ArrayList<Model>();
Cursor cursor =db.rawQuery("SELECT firstname FROM users WHERE type='"+type2+"' AND class_code='"+classcode+"'", null);
//Cursor cursor = db.rawQuery("SELECT firstname,lastname FROM attndrecords", null);
if(cursor.moveToFirst())
{
do
{
list.add(get(cursor.getString(cursor.getColumnIndex("firstname"))));
//list.add(get(cursor.getString(cursor.getColumnIndex("lastname"))));
// bioid= cursor.getString(cursor.getColumnIndex("bioid"));
//list.add(get(cursor.getString(cursor.getColumnIndex("bioid"))));
}while(cursor.moveToNext());
}
return list;
}
public List<Model> getbioid()
{
List<Model> list = new ArrayList<Model>();
Cursor cursor =db.rawQuery("SELECT bioid FROM users WHERE type='"+type2+"' AND class_code='"+classcode+"'", null);
//Cursor cursor = db.rawQuery("SELECT firstname,lastname FROM attndrecords", null);
if(cursor.moveToFirst())
{
do
{
//list.add(get(cursor.getString(cursor.getColumnIndex("firstname"))));
//list.add(get(cursor.getString(cursor.getColumnIndex("lastname"))));
// bioid= cursor.getString(cursor.getColumnIndex("bioid"));
list.add(get(cursor.getString(cursor.getColumnIndex("bioid"))));
}while(cursor.moveToNext());
}
return list;
}
private Model get(String string) {
// TODO Auto-generated method stub
return new Model(string, string, string);
}
public List<Model> getdatalname()
{
List<Model> listlname = new ArrayList<Model>();
Cursor cursor =db.rawQuery("SELECT lastname FROM users WHERE type='"+type2+"' AND class_code='"+classcode+"'", null);
//Cursor cursor = db.rawQuery("SELECT firstname,lastname FROM attndrecords", null);
if(cursor.moveToFirst())
{
do
{
//list.add(cursor.getString(cursor.getColumnIndex("firstname")));
listlname.add(get(cursor.getString(cursor.getColumnIndex("lastname"))));
}while(cursor.moveToNext());
}
return listlname;
}
/*public String getbioid()
{
String query = "SELECT bioid FROM users WHERE type='" +type2+"' AND class_code='"+classcode+"'";
Cursor cursor=db.rawQuery(query, null);
if(cursor.getCount()<0) // UserName Not Exist
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String bioid= cursor.getString(cursor.getColumnIndex("bioid"));
cursor.close();
return bioid;
}*/
public void insertdata()
{
StringBuffer sb = new StringBuffer();
// Retrive Data from list
for (Model bean : bioid1) {
if (bean.isSelected()) {
sb.append(bean.getBioid());
//sb.append(",");
Toast.makeText(this, sb.toString().trim(), 1000);
}
}
String query = "INSERT INTO '"+classcode+"'(bioid,date,time,subject,slot) VALUES('"+sb+"','"+datevalue+"','"+timevalue+"','"+subject+"','"+slot+"')";
Cursor cursor=db.rawQuery(query, null);
if(cursor.getCount()<0) // UserName Not Exist
{
cursor.close();
return;
}
cursor.moveToFirst();
cursor.close();
}
/*public void savedata(String bioid,String datevalue,String timevalue,String subject,String slot) {
// TODO Auto-generated method stub
ContentValues values = new ContentValues();
values.put("bioid", bioid);
values.put("date", datevalue);
values.put("time", timevalue);
values.put("subject", subject);
values.put("slot", slot);
db.insert(classcode, null, values);
db.close();
}*/
public void submit_details(View v)
{
//savedata(bioid, datevalue, timevalue, subject, slot);
insertdata();
Toast.makeText(AttendanceTracker.this, "Saved", Toast.LENGTH_LONG).show();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Attendance Submitted Successfully. Please Connect the Device to WiFi");
alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
Intent i = new Intent(AttendanceTracker.this, Attendance.class);
startActivity(i);
}
});
alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish(); }
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
My AttendancePOJO
package com.edbeans.attendance;
public class AttendancePOJO {
String bioid;
String date;
String time;
String subject;
String slot;
public AttendancePOJO()
{
}
public AttendancePOJO(String bioid, String date, String time,String subject, String slot)
{
this.bioid=bioid;
this.date=date;
this.time=time;
this.subject=subject;
this.slot=slot;
}
public String getBioid() {
return bioid;
}
public void setBioid(String bioid) {
this.bioid = bioid;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getSlot() {
return slot;
}
public void setSlot(String slot) {
this.slot = slot;
}
}
--------------------------------------------------------------------------------
## My custom adapter ##
<pre><code>package com.edbeans.attendance;
import java.util.List;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
public class MyAdapter extends ArrayAdapter<Model> {
private final List<Model> list;
private final List<Model> list2;
private final List<Model> list3;
private final Activity context;
public MyAdapter(Activity context, List<Model> list, List<Model> list2, List<Model> list3) {
super(context, R.layout.attend_layout, list);
this.context = context;
this.list = list;
this.list2=list2;
this.list3=list3;
}
static class ViewHolder {
protected TextView text;
protected CheckBox checkbox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.attend_layout, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.tvstudentfname);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.checkBox1);
viewHolder.checkbox
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) viewHolder.checkbox
.getTag();
element.setSelected(buttonView.isChecked());
}
});
view.setTag(viewHolder);
viewHolder.checkbox.setTag(list.get(position));
} else {
view = convertView;
((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName()+ " " + list2.get(position).getLname()+" " + list3.get(position).getBioid());
// holder.text(list3.get(position));
holder.checkbox.setChecked(list.get(position).isSelected());
return view;
}
}
How can I store all checked value means bioid of all students and date time class? How can U store multiple values at a time on single button click?

android listview item filter with edittext issue

i have a listview which show list of item .item come from database.i used custom adapter.which work fine now i add edittext on the top of my listview i want to filter my list.for exmple when i type word "A" in edittext list filter and show me the only name which start from A.i try to do this but i fail.i am new in android development so please help me to solve my problem.
this is my datalist code
public class DataListActivity extends Activity {
ListView listView;
SQLiteDatabase sqLiteDatabase;
FoodDbHelper foodDbHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
private Button button1;
ListDataAdapter dataAdapter = null;
Button button;
DataProvider dataProvider;
ArrayList<HashMap<String, String>> namessList;
EditText inputSearch;
String search_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.data_list_layout);
inputSearch = (EditText)findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changes the Text
listDataAdapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
listView = (ListView) findViewById(R.id.list_View);
listDataAdapter = new ListDataAdapter(getApplicationContext(),
R.layout.row_layout) {
#Override
protected void showCheckedButton(int position, boolean value) {
// TODO Auto-generated method stub
DataProvider item = (DataProvider) listDataAdapter
.getItem(position);
Log.i("", "");
item.setSelected(value);
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 = listDataAdapter
.getSelectedIndexes();
int sum = 0;
for (int i = 0; i < list.size(); i++) {
DataProvider dataProvider = list.get(i);
sum = sum + dataProvider.getCalorie();
responseText.append("\n" + dataProvider.getName()
+ " : " + dataProvider.getCalorie()
+ " kcal"
);
}
Toast.makeText(getApplicationContext(), ""+responseText+"\n"+"................................."
+"\n"+"Total Calories In Your Menu Is : " +sum,
Toast.LENGTH_LONG).show();
}
});
}
};
listView.setAdapter(listDataAdapter);
foodDbHelper = new FoodDbHelper(getApplicationContext());
sqLiteDatabase = foodDbHelper.getReadableDatabase();
cursor = foodDbHelper.getInformations(sqLiteDatabase);
if (cursor.moveToFirst()) {
do {
String name, quantity, fat, protein, sugar, carbohydrates;
boolean selected = false;
String names = null;
Integer calorie;
name = cursor.getString(0);
quantity = cursor.getString(1);
calorie = Integer.valueOf(cursor.getString(2));
fat = cursor.getString(3);
protein = cursor.getString(4);
sugar = cursor.getString(5);
carbohydrates = cursor.getString(6);
DataProvider dataProvider = new DataProvider(name, quantity,
calorie, fat, protein, sugar, carbohydrates, 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) {
Toast.makeText(getApplicationContext(),
"dish name is : " + dataprovider.getName(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),
Detail.class);
startActivity(intent);
}
});
}
public void gobackk(View view) {
Intent intent = new Intent(this, MainMenu.class);
startActivity(intent);
}
}
this is my custom adapter code
public abstract class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();
boolean index[];
public ListDataAdapter(Context context, int resource) {
super(context, resource);
index = new boolean[list.size()];
}
static class LayoutHandler {
TextView name, quantity, calorie, fat, protein, sugar, carbohydrates;
CheckBox names;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
index = new boolean[list.size()];
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(final 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.carbohydrates = (TextView) row
.findViewById(R.id.text_dish_carbohydrates);
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(String.valueOf(dataProvider.getCalorie()));
layoutHandler.fat.setText(dataProvider.getFat());
layoutHandler.protein.setText(dataProvider.getProtein());
layoutHandler.sugar.setText(dataProvider.getSugar());
layoutHandler.carbohydrates.setText(dataProvider.getCarbohydrates());
//layoutHandler.names.setChecked(dataProvider.isSelected());
layoutHandler.names.setTag(position);
layoutHandler.names.setChecked(index[position]);
layoutHandler.names
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
int pos = (Integer) buttonView.getTag();
index[pos] = isChecked;
showCheckedButton(position, isChecked);
}
});
return row;
}
public ArrayList<DataProvider> getSelectedIndexes() {
int size = list.size();
ArrayList<DataProvider> selectedItems = new ArrayList<DataProvider>();
for (int i = 0; i < size; i++) {
DataProvider cItem = (DataProvider) list.get(i);
if (index[i]) {
selectedItems.add(cItem);
}
}
return selectedItems;
}
protected abstract void showCheckedButton(int position, boolean value);
}

Android - How to delete multiple items from listView with checkBox ?

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 .:)

Android load contacts code optimization

I've written an activity which loads all contacts of the phone and displays it at once in a ListView. The thing is, it takes time to load 400+ contacts and this is not very user friendly. Can anyone point me how can i make this activity run in the background\run faster, I've tried to use AsyncTask but apparently it uses a class rather and not an activity. Any advice is greatly appreciated.
Im adding the code so it will be easier to understand how things work for now:
This is the Contacts class:
public class CustomContact
{
private String contactName;
private String contactPhoneNumber;
private boolean selected = false;
public CustomContact()
{
}
public CustomContact(String contactName, String contactPhoneNumber, boolean selected)
{
super();
this.contactName = contactName;
this.contactPhoneNumber = contactPhoneNumber;
this.selected = selected;
}
public String getContactName()
{
return contactName;
}
public void setContactName(String contactName)
{
this.contactName = contactName;
}
public String getContactPhoneNumber()
{
return contactPhoneNumber;
}
public void setContactPhoneNumber(String contactPhoneNumber)
{
this.contactPhoneNumber = contactPhoneNumber;
}
public boolean isSelected()
{
return selected;
}
public void setSelected(boolean selected)
{
this.selected = selected;
}
#Override
public String toString()
{
return contactPhoneNumber + " " + "\u200e" + contactName;
}
}
Now the code of the activity which uses the CustomContacts class:
public class ContactSelectActivity extends Activity
{
MyCustomAdapter dataAdapter = null;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_select);
//Generate list View from ArrayList
displayListView();
checkButtonClick();
}
private void displayListView()
{
//Array list of countries
ArrayList<CustomContact> contactsList = new ArrayList<CustomContact>();
String[] projection = new String[] {ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
ContactsContract.Contacts.LOOKUP_KEY
};
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME ;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, projection,
ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"+ ("1") + "'",
null, sortOrder
);
if (cursor.getCount() > 0)
{
while (cursor.moveToNext())
{
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
// Query phone here. Covered next
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null, null);
while (phones.moveToNext())
{
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
CustomContact customContact = new CustomContact(name, phoneNumber, false);
contactsList.add(customContact);
}
phones.close();
}
}
}
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(this,R.layout.custom_contact_info, contactsList);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
CustomContact contact = (CustomContact) parent.getItemAtPosition(position);
}
});
}
private class MyCustomAdapter extends ArrayAdapter<CustomContact>
{
private ArrayList<CustomContact> contactList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<CustomContact> stateList)
{
super(context, textViewResourceId, stateList);
this.contactList = new ArrayList<CustomContact>();
this.contactList.addAll(stateList);
}
private class ViewHolder
{
TextView code;
CheckBox name;
}
#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.custom_contact_info, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
holder.name.setOnClickListener( new View.OnClickListener()
{
public void onClick(View v)
{
CheckBox cb = (CheckBox) v;
CustomContact _contact = (CustomContact) cb.getTag();
_contact.setSelected(cb.isChecked());
}
});
}
else
{
holder = (ViewHolder) convertView.getTag();
}
CustomContact contact = contactList.get(position);
holder.code.setText(" (" + contact.getContactName() + ")");
holder.name.setText(contact.getContactPhoneNumber());
holder.name.setChecked(contact.isSelected());
holder.name.setTag(contact);
return convertView;
}
}
private void checkButtonClick()
{
Button myButton = (Button) findViewById(R.id.findSelected);
myButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
StringBuffer responseText = new StringBuffer();
responseText.append("The following were selected...\n");
ArrayList<CustomContact> contactList = dataAdapter.contactList;
for(int i=0;i<contactList.size();i++)
{
CustomContact contact = contactList.get(i);
if(contact.isSelected())
{
responseText.append("\n" + contact.getContactPhoneNumber());
}
}
}
});
}
}

indexoutofbound exception while adding item in listview android

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

Categories

Resources