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());
}
}
}
});
}
}
Related
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?
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(...
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 .:)
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 have a listview in my application.I want to set the value of textview in that particular row when I click one of the textview in that row itself.so,I tried like below
likes.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView t=(TextView)v;
TextView likesnumber1 = (TextView) findViewById(R.id.likesnumber);
int i= Integer.parseInt(likescount.get(position));
if(like_or_ulike.get(position).equals("Like")){
Log.e("inlike","like");
like_or_ulike.set(position, "Unlike");
t.setText(like_or_ulike.get(position));
UrltoValue.getValuefromUrl("https://graph.facebook.com/"+objectid.get(position)+"/likes?access_token="+accesstoken+"&method="+"post");
j=i+1;
String s=Integer.toString(j);
likescount.set(position, s);
likesnumber1.setText(likescount.get(position));
}
else{
Log.e("unlike","unlike");
like_or_ulike.set(position, "Like");
t.setText(like_or_ulike.get(position));
UrltoValue.getValuefromUrl("https://graph.facebook.com/"+objectid.get(position)+"/likes?access_token="+accesstoken+"&method="+"DELETE");
j=i-1;
String s=Integer.toString(j);
likescount.set(position, s);
likesnumber1.setText(likescount.get(position));
}
}
});
the "likes" reference which I used is textview and I want to set the textview by getting the id of that particular row.
TextView likesnumber1 = (TextView) findViewById(R.id.likesnumber);
when I use this I am getting the id of the first visible row of the screen.
How can I get the id of textview of that particular row,on a textview click.
Thanks
I'm not sure how you are populating your list with data, however here is a method I use that works very well.
Data Models
public class Publication {
public String string1;
public String string2;
public Publication() {
}
public Publication(String string1, String string2) {
this.string1= string1;
this.string2= string2;
}
}
Create an array adapter
public class ContactArrayAdapter extends ArrayAdapter<ContactModel> {
private static final String tag = "ContactArrayAdapter";
private static final String ASSETS_DIR = "images/";
private Context context;
//private ImageView _emotionIcon;
private TextView _name;
private TextView _email;
private CheckBox _checkBox;
private List<ContactModel> contactModelList = new ArrayList<ContactModel>();
public ContactArrayAdapter(Context context, int textViewResourceId,
List<ContactModel> objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.contactModelList = objects;
}
public int getCount() {
return this.contactModelList.size();
}
public ContactModel getItem(int index) {
return this.contactModelList.get(index);
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
// ROW INFLATION
Log.d(tag, "Starting XML Row Inflation ... ");
LayoutInflater inflater = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.contact_list_entry, parent, false);
Log.d(tag, "Successfully completed XML Row Inflation!");
}
// Get item
final ContactModel contactModel = getItem(position);
Resources res = this.getContext().getResources();
//Here are some samples so I don't forget...
//
//_titleCount = (TextView) row.findViewById(R.id.category_count);
// _category.setText(categories1.Category);
//
//if (categories1.Category.equals("Angry")) {
//Drawable angry = res.getDrawable(R.drawable.angry);
//_emotionIcon.setImageDrawable(angry);
//}
_checkBox = (CheckBox) row.findViewById(R.id.contact_chk);
_email = (TextView) row.findViewById(R.id.contact_Email);
_name = (TextView)row.findViewById(R.id.contact_Name);
//Set the values
_checkBox.setChecked(contactModel.IsChecked);
_email.setText(contactModel.Email);
_name.setText(contactModel.Name);
_checkBox.setOnClickListener(new CompoundButton.OnClickListener() {
#Override
public void onClick(View view) {
if (contactModel.IsChecked) {
contactModel.IsChecked = false;
notifyDataSetChanged();
}
else {
contactModel.IsChecked = true;
notifyDataSetChanged();
}
}
});
return row;
}
}
Use the array adapter to fill your list
ContactArrayAdapter contactArrayAdapter;
//
List<ContactModel> contactModelList;
//Fill list with your method
contactModelList = getAllPhoneContacts();
//
contactArrayAdapter = new ContactArrayAdapter(getApplicationContext(), R.layout.contact_list_entry, contactModelList);
//
setListAdapter(contactArrayAdapter);
A sample method to fill data:
public List<ContactModel> getAllPhoneContacts() {
Log.d("START","Getting all Contacts");
List<ContactModel> arrContacts = new Stack<ContactModel>();
Uri uri = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
Cursor cursor = getContentResolver().query(uri, new String[] {ContactsContract.CommonDataKinds.Email.DATA1
,ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
,ContactsContract.CommonDataKinds.Phone._ID}, null , null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
cursor.moveToFirst();
while (cursor.isAfterLast() == false)
{
String email= cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
int phoneContactID = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
if (email != null)
{
ContactModel contactModel = new ContactModel();
contactModel.Name = name;
contactModel.Email = email;
contactModel.IsChecked = false;
arrContacts.add(contactModel);
}
cursor.moveToNext();
}
cursor.close();
cursor = null;
Log.d("END","Got all Contacts");
return arrContacts;
}
Accessing the data on click
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
//Click handler for listview
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View view, int position, long id) {
ContactModel contact= getItem(position);//This gets the data you want to change
//
some method here tochange set data
contact.email = "new#email.com"
//send notification
contactArrayAdapter.notifyDataSetChanged();
}
});