I want to have a listview with textview + check box. I was able to create the listview. I can capture listview item select. However when I try to capture check box select, unselect I get a null pointer exception. How to write the setOnCheckedChangeListener() for the check box..
public class LocationActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.locationmain);
ListView listview = (ListView) findViewById(R.id.listView1);
String selectQuery = "SELECT * FROM " + DatabaseHandler.TABLE_LOCATIONLABLES;
SQLiteDatabase db = new DatabaseHandler(this).getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
final List<String> locLables = new ArrayList<String>();
if(cursor != null){
if (cursor.moveToFirst()) {
do {
locLables.add(cursor.getString(1));
} while (cursor.moveToNext());
}
}
//String[] locLables = new String[] {"Home","University","Office"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.locationmain_entry,R.id.textView12, locLables);
//cb gives a null pointer exception
CheckBox cb = (CheckBox) listview.findViewById(R.id.checkBox12);
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
System.out.println("selected");
}else if(!isChecked){
System.out.println("not selected");
}
}
});
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), locLables.get(arg2), Toast.LENGTH_SHORT).show();
}
});
}
You can maintain seperate adpater class so that you can achive this easily....
public class bsAdapter extends BaseAdapter
{
Activity cntx;
public bsAdapter(Activity context)
{
// TODO Auto-generated constructor stub
this.cntx=context;
}
public int getCount()
{
// TODO Auto-generated method stub
return listview_arr.length;
}
public Object getItem(int position)
{
// TODO Auto-generated method stub
return listview_arr[position];
}
public long getItemId(int position)
{
// TODO Auto-generated method stub
return listview_array.length;
}
public View getView(final int position, View convertView, ViewGroup parent)
{
View row=null;
LayoutInflater inflater=cntx.getLayoutInflater();
row=inflater.inflate(R.layout.search_list_item, null);
TextView tv=(TextView)row.findViewById(R.id.title);
CheckBox cb=(CheckBox)row.findViewById(R.id.cb01);
tv.setText(listview_arr[position]);
cb.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
if(cb.ischecked)
{
//ur code
}
else //ur code
}
});
return row;
}
}
Do not use listview.findViewById(), just use findViewById() like you did for your list.
Unless the checkbox is part of each of the list items, in which case you would have to access the checkbox from within the getView() of your ListAdapter.
Related
I create a listview get all contact from address book of Android. I try to update listview by onResume() but It's not working.
Here is my code:
public class Display extends Activity implements OnItemClickListener{
List<String> name1 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
List<String> email1 = new ArrayList<String>();
MyAdapter ma ;
ListView lv;
int countContact;
TextView textViewManyCount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
getAllContacts(this.getContentResolver());
lv= (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
textViewManyCount = (TextView) findViewById(R.id.textViewManyCount);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
public void getAllContacts(ContentResolver cr) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
countContact = phones.getCount();
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String email = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
System.out.println(".................."+phoneNumber);
name1.add(name);
phno1.add(phoneNumber);
email1.add(email);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView textViewName,textViewPhone,textViewEmail;
MyAdapter()
{
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)Display.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.list_user, null);
textViewName = (TextView) vi.findViewById(R.id.textViewName);
textViewPhone = (TextView) vi.findViewById(R.id.textViewPhone);
textViewEmail = (TextView) vi.findViewById(R.id.textViewEmail);
textViewName.setText("Name :"+ name1.get(position));
textViewPhone.setText("Phone No :"+ phno1.get(position));
textViewEmail.setText("Email :"+ email1.get(position));
textViewManyCount.setText("Contacts: "+countContact);
return vi;
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
}
}
When I running app, It's load all contact but when I click button Home and change some information in Address book then click icon app to open app again. And onResume() method not working.
Here my onResume()
#Override
protected void onResume()
{
super.onResume();
if (lv != null)
{
updateData();
}
}
private void updateData()
{
getAllContacts(this.getContentResolver());
ma = new MyAdapter();
lv.setAdapter(ma);
ma.notifyDataSetChanged();
}
So some body help me! Plz!
Try by Replacing your updateData():
private void updateData()
{
getAllContacts(this.getContentResolver());
ma.notifyDataSetChanged();
}
You may be referencing an old ListView (lv) that is not the new ListView you see when you resume your Activity. Try getting the reference to lv again using Activity.findViewById(R.id.xxxx) in onResume().
You could also try reusing the old adapter instead of creating a brand new one (by clearing it and updating it's content). If you're reusing the old adapter, just make sure you give the old adapter to the new ListView using ListView.setAdapter(ma).
You should also have MyAdapter.getItemId(int position) return position instead of 0.
I have a custom listview that contains an edittext,checkbox and two text views.Now i am hving a problem with the edittext values in my code.I am not able to get the correct value from the edittext.And also if i set the value of an edit text at one position in the list,that value is also set to edittexts at random positions in the listview.And i have the common problem of the values changing on scroll.Following is the code:
Activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_assess_list);
prev = getIntent();
final ListView listview = (ListView) findViewById(R.id.studentsListView);
listview.setAdapter(new AssessmentAdapter(this, R.layout.assessment,
StudentNames.student_name, StudentNames.studentRollNo));
}
Adapter:
public class AssessmentAdapter extends ArrayAdapter<String> {
Context context;
ViewHolder holder;
CheckBox present;
EditText marks;
int pos;
public static ArrayList<String> studentNames,studentRollNo,studentsPresent,marksObtainedList;
public AssessmentAdapter(Context context, int textViewResourceId,ArrayList<String> studentNames,ArrayList<String> studentRollNo) {
super(context, textViewResourceId,studentNames);
// TODO Auto-generated constructor stub
this.context=context;
AssessmentAdapter.studentNames=studentNames;
AssessmentAdapter.studentRollNo=studentRollNo;
studentsPresent=new ArrayList<String>();
marksObtainedList=new ArrayList<String>();
Log.d("No. of students",""+studentRollNo.size());
for(int i=0;i<studentNames.size();i++)
{
studentsPresent.add("1");
marksObtainedList.add("0");
}
}
static class ViewHolder {
CheckBox presentCB;
TextView name,Rno;
EditText marksObtained;
Button save;
}
public View getView(final int pos,View convertview,ViewGroup parent)
{
try
{
holder=null;
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertview==null)
{
//rowView=inflater.inflate(org.example.attendance.R.layout.list_radio,parent,false);
convertview=inflater.inflate(R.layout.assessment,null);
holder=new ViewHolder();
holder.presentCB=(CheckBox)convertview.findViewById(org.example.attendance2.R.id.presentCB);
holder.name=(TextView)convertview.findViewById(org.example.attendance2.R.id.studNameTV);
holder.Rno=(TextView)convertview.findViewById(org.example.attendance2.R.id.studRollNoTV);
holder.marksObtained=(EditText)convertview.findViewById(org.example.attendance2.R.id.marksET);
holder.save=(Button)convertview.findViewById(org.example.attendance2.R.id.saveButton);
convertview.setTag(holder);
}
else
{
holder=(ViewHolder) convertview.getTag();
}
holder.name.setText(studentNames.get(pos));
holder.Rno.setText(studentRollNo.get(pos));
holder.save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
holder.marksObtained.addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
marksObtainedList.set(pos, arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
holder.presentCB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(studentsPresent.get(pos).equals("1"))
{
studentsPresent.set(pos, "0");
}
else
{
studentsPresent.set(pos, "1");
}
}
});
//if(RadioChecked[pos])
if(studentsPresent.get(pos).equals("1"))
{
holder.presentCB.setChecked(true);
}
// else if(!RadioChecked[pos])
else if(studentsPresent.get(pos).equals("0"))
{
holder.presentCB.setChecked(false);
}
if(holder.marksObtained.getText().toString().equals(""))
{
marksObtainedList.set(pos,"0");
}
else
{
String marks=holder.marksObtained.getText().toString();
marksObtainedList.set(pos,marks);
Log.d(""+pos,marksObtainedList.get(pos));
}
holder.marksObtained.setText(marksObtainedList.get(pos));
}catch(Exception e)
{
}
return convertview;
}
public boolean areAllItemsEnabled()
{
return true;
}
#Override
public boolean isEnabled(int arg0)
{
return true;
}
}
the problem is all about relate to focus . see here , it may help you.
Focusable EditText inside ListView
I'm implementing functions of notifications like default messages application in android. Now I'm doing the multiple message deletion by adding checkbox in which I'm using one common checkbox to select all messages in the list. But I can not check the listview checkbox which is in getview of CustomAdpter.
class customListAdpter extends BaseAdapter {
private Context ctx;
CheckBox checkBox;
TextView sender, message;
customListAdpter(Context context) {
this.ctx = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return new NotifiCation().senderlist.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int pos, View v, ViewGroup arg2) {
// TODO Auto-generated method stub
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.checkboxlist, null);
checkBox = (CheckBox) v.findViewById(R.id.btn_chck);
sender = (TextView) v.findViewById(R.id.text_senderno);
message = (TextView) v.findViewById(R.id.text_msg);
}
sender.setText("" + new NotifiCation().senderlist.toArray()[pos]);
message.setText("" + new NotifiCation().msglist.toArray()[pos]);
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if (buttonView.isChecked()) {
}
}
});
return v;
}
}
And this is my main activity. Here I have the main checkbox.
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.delete_notifications);
db = new DB(NotificationsDelete.this);
notifications = (ListView) findViewById(R.id.list_with_ckbox);
selectAll = (CheckBox) findViewById(R.id.btn_checkall);
done = (Button) findViewById(R.id.done_notification_delete);
notifications.setAdapter(new customListAdpter(con));
selectAll.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton chkbox, boolean arg1) {
if (chkbox.isChecked() == true) {
for (int i = 0; i < new NotifiCation().senderlist.size(); i++) {
//notifications.setItemChecked(i, true);
customListAdpter adpter=new customListAdpter(con);
adpter.checkBox.setChecked(true);
}
} else {
// new customListAdpter(con).checkBox.setChecked(true);
}
}
});
done.setOnClickListener(this);
}
Try calling notifyDataSetChanged() after you handle onCheckedChanged() of selectAll checkbox field.
I am trying to create a application for android. in which at one point i need to open a activity i need to display all the contacts on user's phone in a listview with checkbox, so that multiple contacts can be selected. I have written a code which currently shows the list of all the contacts but without checkbox as you can see in the image attached. Next, when the user selects the required contacts using checkbox and clicks on DONE button the result should be derived in main activity and all the contacts which the user selected should be displayed in the EditText like this Frank <+911234567890>, John <+913456789012>, Ashley <+911237890456>,. How can i achieve what i want? And also the dashes(-) which are currently getting displayed should also disappear.
Use the following to add checkboxes on all the items:
listView.setChoiceMode(CHOICE_MODE_MULTIPLE);
Not only will this add checkboxes to all the items, but it will handle all the check states for you. You have several methods you can use to get the state of the items:
getCheckedItemCount()
getCheckedItemIds()
getCheckedItemPositions()
And you can use setItemChecked() to set any item's checked state programmatically. Take a look at this tutorial for a guide how to make a multiple selection list.
split the string on each '-' using function split("-") and then concatenate it.
use the code snippet below to retrieve all contacts from the phonebook,append them in a ListView containing checkboxes to enable multiple selection,,it is clear and straight to the point.
public class Display extends Activity implements OnItemClickListener{
List<String> name1 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
MyAdapter ma ;
Button select;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
getAllContacts(this.getContentResolver());
ListView lv= (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
// adding
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
StringBuilder checkedcontacts= new StringBuilder();
for(int i = 0; i < name1.size(); i++)
{
if(ma.mCheckStates.get(i)==true)
{
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
}
else
{
}
}
Toast.makeText(Display.this, checkedcontacts,1000).show();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllContacts(ContentResolver cr) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
MyAdapter()
{
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)Display.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
tv= (TextView) vi.findViewById(R.id.textView1);
tv1= (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :"+ name1.get(position));
tv1.setText("Phone No :"+ phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
I have a listview with textview and checkbox. The text values are stored in a HashMap. Data is retrieved from a DB. Map key is the ID and Map value is a Location. When I pass the HashMap to the adapter, it starts printing from position 0 (zero). Because of this I get a null text(with no value) and miss one value(the last one) in the HashMap. Can't I use a HashMap as the data source?
EDIT: Here is the code
public class LocationActivity extends Activity{
myAdapter myA;
Map<Integer,String> locLables;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.locationmain);
ListView listview = (ListView) findViewById(R.id.listView1);
String selectQuery = "SELECT * FROM " + DatabaseHandler.TABLE_LOCATIONLABLES;
SQLiteDatabase db = new DatabaseHandler(this).getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
locLables = new HashMap<Integer, String>();
if(cursor != null){
if (cursor.moveToFirst()) {
do {
locLables.put(new Integer(cursor.getString(0)),cursor.getString(1));
System.out.println(cursor.getString(0)+" "+ cursor.getString(1));
} while (cursor.moveToNext());
}
}
cursor.close();db.close();
//System.out.println(locLables);
myA = new myAdapter(this, locLables, listview);
listview.setAdapter(myA);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if(arg2 == 0 )
arg2 = arg2+1;
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), locLables.get(arg2), Toast.LENGTH_SHORT).show();
}
});
}
Here is the Adapter class
class myAdapter extends BaseAdapter{
ListView listView;
Activity cntx;
Map<Integer,String> locations;
List<Integer> locids = new LinkedList<Integer>();
public myAdapter(Activity context,Map<Integer,String> locLables, ListView lv){
cntx = context;
locations = locLables;
listView = lv;
System.out.println(locations);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return locations.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row=null;
final int posi = position;
LayoutInflater inflater=cntx.getLayoutInflater();
row=inflater.inflate(R.layout.locationmain_entry, null);
TextView tv = (TextView)row.findViewById(R.id.textView12);
final CheckBox cb = (CheckBox)row.findViewById(R.id.checkBox12);
if(locids.contains(posi))
cb.setChecked(true);
//here I get a null value as the first element and misses the last value..
tv.setText(locations.get(position));
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
System.out.println("Chedked" + posi+ locations.get(posi));
//cb.setChecked(true);
if(!locids.contains(posi))
locids.add(posi);
//System.out.println(locids.get(posi));
}else if(!isChecked){
//cb.setChecked(false);
if(locids.contains(posi))
locids.remove(new Integer(posi));
System.out.println("NOt checked" +posi + locations.get(posi));
}
}
});
return row;
}
It runs for the number of elements in the Map. As it is using a 0 (by position variable) it misses the last value as well.
What you can do is
ArrayList<Hashmap<Integer,String>> myList = new ArrayList<Hashmap<Integer,String>>();
if(cursor != null){
if (cursor.moveToFirst()) {
do {
locLables = new HashMap<Integer, String>();
locLables.put(new Integer(cursor.getString(0)),cursor.getString(1));
myList.add(locLables);
} while (cursor.moveToNext());
}
}
cursor.close();db.close();
myA = new myAdapter(this, myList, listview);
listview.setAdapter(myA);
You will have to change your "myAdapter" Adapter's constructor to hold "ArrayList> myList" instead of "Map locLables"..
This will help... Let me know if the problem still persists..