I'm working on showing list of contacts with checkbox. I tried implementing my own cursor adapter and it is checkable. But once I check that value I want the contacts to be stored in ContactPerson object. But when I tried it is showing null pointer exception(That's why I commented out that code). My CursorAdapter code goes like this.
ContactListAcitivity.java
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
public class ContactListActivity extends Activity {
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
list = (ListView) findViewById(R.id.ListView2);
Cursor cur= getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,null,null,null);
startManagingCursor(cur);
String[] result=new String[cur.getCount()];
for (boolean hasData = cur.moveToFirst(); hasData; hasData = cur.moveToNext())
{
ContactPerson contact = new ContactPerson(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)), String.valueOf(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
stopManagingCursor(cur);
list.setAdapter(new contactAdapter(getApplicationContext(), cur));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.contact_list, menu);
return true;
}
private class ViewHolder{
TextView ContactName;
CheckBox contactCheck;
}
class contactAdapter extends CursorAdapter{
private Cursor cursor;
private Context ccontext;
private LayoutInflater inflater;
public contactAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
cursor = c;
ccontext = context;
inflater = LayoutInflater.from(context);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public void bindView(View view, Context arg1, Cursor arg2) {
// TODO Auto-generated method stub
ViewHolder holder = (ViewHolder) view.getTag();
if (holder == null) {
holder = new ViewHolder();
holder.ContactName = (TextView) view.findViewById(R.id.contact_name);
holder.contactCheck = (CheckBox) view.findViewById(R.id.contact_check);
view.setTag(holder);
holder.contactCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) v;
cb.setSelected(true);
// ContactPerson contact = (ContactPerson) cb.getTag(); this is the place where it is showing null pointer exception
// Log.i("clicked users", contact.getName());
// contact.setSelected(true);
}
});
}else{
holder = (ViewHolder) view.getTag();
}
// ContactPerson contacts = contactList.get(position);
holder.ContactName.setText(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
// holder.contactCheck.setChecked(contacts.isSelected());
// holder.contactCheck.setTag(contacts);
// holder.ContactName.setText(contacts.getName());
}
#Override
public View newView(Context arg0, Cursor arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.checkbox_item, arg2, false);
}
}
}
activity_contact_list.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000">
<ListView
android:id="#+id/ListView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".GroupContactsActivity"
android:layout_alignParentTop="true"
/>
<Button
android:id="#+id/selected_done_1"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:textColor="#FFFFFF"
android:text="Done" />
</RelativeLayout>
checkbox_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip"
android:background="#000000">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/contact_name"
android:layout_alignParentLeft="true"
android:text="textview"
android:textSize="15sp"
android:textColor="#FFFFFF"
android:gravity="center_horizontal"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_alignParentRight="true"
android:layout_weight="1"
android:id="#+id/contact_check"/>
</RelativeLayout>
Can anyone please suggest me how to use that Contact person class in this adapter.
public class ContactPerson {
String name= null, number = null;
boolean Selected = false;
public ContactPerson(String PersonName, String PhoneNumber){
this.name = PersonName;
this.number= PhoneNumber;
}
public String getName(){
return name;
}
public boolean isSelected(){
return Selected;
}
public void setSelected(boolean selected){
this.Selected = selected;
}
public String getPhoneNumber(){
return number;
}
}
Check this code. It worked for me. Best of luck.
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeSet;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ContactListActivity extends Activity {
ListView list;
ArrayList<ContactPerson> selectedList;
Set<String> phoneID= new TreeSet<String>();;
Button doneButton;
CheckBox cb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
selectedList = new ArrayList<ContactPerson>();
list = (ListView) findViewById(R.id.ListView2);
doneButton = (Button) findViewById(R.id.selected_done_1);
Cursor cur= getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null,null);
list.setAdapter(new contactAdapter(getApplicationContext(), cur));
doneButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for (String ids : phoneID) {
Log.d("PhoneIds", ids);
Cursor cursorPhoneNumber = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{ids},
null);
Log.d("Number cursor", String.valueOf(cursorPhoneNumber.getCount()));
if (cursorPhoneNumber.moveToFirst()) {
// phoneNumber = cursorPhoneNumber.getString(cursorPhoneNumber.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.d("Phone number", cursorPhoneNumber.getString(cursorPhoneNumber.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
cursorPhoneNumber.close();
Cursor cursorName = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{ids},
null);
Log.d("Name cursor", String.valueOf(cursorName.getCount()));
if (cursorName.moveToFirst()) {
Log.d("Phone number", cursorName.getString(cursorName.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY)));
// Name = cursorName.getString(cursorName.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY));
}
cursorName.close();
// selectedList.add(new ContactPerson(Name,phoneNumber));
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.contact_list, menu);
return true;
}
private class ViewHolder{
TextView ContactName;
CheckBox contactCheck;
}
class contactAdapter extends CursorAdapter{
String Name, phoneNumber;
private Cursor cursor;
private Context ccontext;
private LayoutInflater inflater;
public contactAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
cursor = c;
ccontext = context;
inflater = LayoutInflater.from(context);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public void bindView(View view, Context arg1, Cursor arg2) {
// TODO Auto-generated method stub
ViewHolder holder = (ViewHolder) view.getTag();
if (holder == null) {
holder = new ViewHolder();
holder.ContactName = (TextView) view.findViewById(R.id.contact_name);
holder.contactCheck = (CheckBox) view.findViewById(R.id.contact_check);
view.setTag(holder);
holder.contactCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
cb = (CheckBox) v;
cb.setChecked(cb.isChecked());
// ContactPerson selected = (ContactPerson)cb.getTag();
Log.d("selcted", cb.getTag().toString());
if(cb.isChecked()){
phoneID.add(cb.getTag().toString());
}
}
});
}else{
holder = (ViewHolder) view.getTag();
}
holder.ContactName.setText(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
holder.contactCheck.setTag(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID)));
holder.contactCheck.setChecked(false);
}
#Override
public View newView(Context arg0, Cursor arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.checkbox_item, arg2, false);
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
// Log.d("don't know", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
return super.getView(arg0, arg1, arg2);
}
}
}
Here i changed little bit code of your adapter and activity. just look at it:
public class MainActivity extends Activity {
private ArrayList<ContactPerson> arr;
private Context context;
private ListView list;
private ContactArrayAdapter adapter;
private String strName,strNumber;
private View view;
public static boolean[] arrBoolean = null;
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.activity_main);
ProgressDialog pd = new ProgressDialog(this);
list = (ListView)findViewById(R.id.ListView2);
arr = new ArrayList<ContactPerson>();
context = MainActivity.this;
arr = displayContacts();
adapter = new ContactArrayAdapter(this, R.layout.checkbox_item, arr);
list.setAdapter(adapter);
}
public ArrayList<ContactPerson> displayContacts() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
ContactPerson contact;
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
contact = new ContactPerson();
String id = cur.getString(cur.getColumnIndex(People._ID));
String name = cur.getString(cur.getColumnIndex(People.DISPLAY_NAME));
ContactPerson cp = new ContactPerson();
cp.setName(name);
cp.setNumber(id);
cp.setSelected(false);
arr.add(cp);
}
}
return arr;
}
//********* Adapter *****
public class ContactArrayAdapter extends ArrayAdapter<ContactPerson> {
// private final List<Contact> list;
private Context context;
private LayoutInflater mInflater;
private List<ContactPerson> list;
public ContactArrayAdapter(Context context, int textViewResourceId,
ArrayList<ContactPerson> stateList) {
super(context, textViewResourceId, stateList);
this.list = new ArrayList<ContactPerson>();
this.list.addAll(stateList);
}
class ViewHolder {
TextView text;
CheckBox checkbox;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder viewHolder = null;
if (view == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.checkbox_item, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.contact_name);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.contact_check);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
final int pos = position;
ContactPerson cp = list.get(position);
viewHolder.text.setText(cp.getName());
viewHolder.checkbox.setChecked(cp.isSelected());
viewHolder.checkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) arg0 ;
list.get(pos).setSelected(cb.isChecked());
System.out.println(cb.isChecked());
System.out.println(list.get(pos).getName());
}
});
//viewHolder.text.setTag(cp);
return view;
}
}
}
Related
I want to add / remove the item into wishlist. I am getting one response from Api, so in that i have one tag is_wishlist=true/false, when I am launching an application based on that value I am showing its in wishlist by changing an icon, but now issue is if am changing that wishlist status like from adding to remobing to adding, in Api i am getting response sucessfully, but i am unable to change the icons. This is my code. can any one help me how to remove or add items into wishlist
package com.example.user.smgapp;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
import java.util.List;
public class Prd_grid_adapter extends BaseAdapter {
List<HashMap<String, String>> Category_listData;
HashMap<String, String> map;
Context context;
Typeface face;
String wishList_url, remove_wishList_url;
Cursor cursor;
NavigationDrawer nav = new NavigationDrawer();
private static LayoutInflater inflater = null;
public Prd_grid_adapter(Activity context, List<HashMap<String, String>> aList) {
// TODO Auto-generated constructor stub
Category_listData = aList;
/*/for(int i=1;i<aList.size();i++)
{
Category_listData.add(aList.get(i));
}*/
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return Category_listData.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 position;
}
public class Holder {
TextView name, price, original_price;
ImageView img, wish_list;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder = new Holder();
final View rowView;
this.face = Typeface.createFromAsset(context.getAssets(), "fonts/OpenSans-Regular.ttf");
rowView = inflater.inflate(R.layout.grid_item_view, null);
holder.name = (TextView) rowView.findViewById(R.id.p_name);
holder.img = (ImageView) rowView.findViewById(R.id.p_img);
holder.wish_list = (ImageView) rowView.findViewById(R.id.wish_list);
holder.price = (TextView) rowView.findViewById(R.id.p_price);
holder.original_price = (TextView) rowView.findViewById(R.id.orginal_p);
map = Category_listData.get(position);
holder.name.setTypeface(face);
holder.name.setText(map.get("product_name"));
Log.e("wish list staus..", "wishlist status.." + map.get("is_wishlist"));
if (map.get("is_wishlist").equals("0")) {
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
} else {
holder.wish_list.setImageResource(R.drawable.wishlist);
}
holder.wish_list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (SingletonActivity.custidstr.isEmpty()) {
Toast.makeText(context, "Ur not logged in,Please Login", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Alert!");
builder.setMessage("Ur not logged in")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(context, Login.class);
context.startActivity(intent);
}
});
// Create the AlertDialog object and return it
builder.show();
} else {
wishList_url = SingletonActivity.API_URL + "api/add_wishlist.php?customer_id=" + SingletonActivity.custidstr + "&product_id=" + Category_listData.get(position).get("product_id");
remove_wishList_url = SingletonActivity.API_URL + "api/remove_item_wishlist.php?customerid=" + SingletonActivity.custidstr + "&productid=" + Category_listData.get(position).get("product_id");
Log.e("wishlist api..", "wish list api.." + wishList_url);
Log.e("remove wishlist api..", "remove wish list api.." + remove_wishList_url);
v.setActivated(!v.isActivated());
String wish_status = map.get("is_wishlist");
Log.e("wish status..", "wish status.." + wish_status);
int stat = Integer.parseInt(wish_status);
// notifyDataSetChanged();
/*if (wish_status=="Product already exists in wishlist"){
Toast.makeText(context,"removed....",Toast.LENGTH_SHORT).show();
nav.removeFromwishList(remove_wishList_url);
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
}
else
{
nav.addTowishList(wishList_url);
Toast.makeText(context,"addedd..",Toast.LENGTH_SHORT).show();
holder.wish_list.setImageResource(R.drawable.wishlist);
}*/
if (stat == 0) {
nav.addTowishList(wishList_url);
Toast.makeText(context, "addedd..", Toast.LENGTH_SHORT).show();
holder.wish_list.setImageResource(R.drawable.wishlist);
// notifyDataSetChanged();
/* ((Activity)context).finish();
Intent i= ((Activity) context).getIntent();
context.startActivity(i);*/
//
} else {
nav.removeFromwishList(remove_wishList_url);
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
Toast.makeText(context, "removed....", Toast.LENGTH_SHORT).show();
/* ((Activity)context).finish();
Intent i= ((Activity) context).getIntent();
context.startActivity(i);*/
// notifyDataSetChanged();
}
/* v.setActivated(!v.isActivated());
if (v.isActivated()){
Toast.makeText(context,"addedd..",Toast.LENGTH_SHORT).show();
holder.wish_list.setImageResource(R.drawable.wishlist);
nav.addTowishList(wishList_url);
}
else {
Toast.makeText(context,"removed....",Toast.LENGTH_SHORT).show();
nav.removeFromwishList(remove_wishList_url);
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
}*/
}
}
});
if (map.get("special_price").equals("0.00")) {
holder.price.setVisibility(View.INVISIBLE);
// holder.o_price.setVisibility(View.INVISIBLE);
holder.original_price.setText("Rs." + map.get("product_price"));
holder.original_price.setTextAppearance(context, R.style.product_price_txt);
} else {
holder.price.setText("Rs." + map.get("special_price"));
holder.original_price.setText("Rs." + map.get("product_price"));
holder.original_price.setPaintFlags(holder.original_price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
/* holder.price.setText("Rs." + map.get("special_price"));
holder.original_price.setText("Rs."+map.get("product_price"));
holder.original_price.setPaintFlags(holder.original_price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);*/
Picasso.with(context).load(map.get("product_image")).placeholder(R.drawable.loading)
.fit().into(holder.img);
return rowView;
}
}
Change this line
holder.wish_list.setImageResource(R.drawable.wishlist);
to this
Resources resources = getResources();
holder.wish_list.setImageDrawable(resources.getDrawable(R.drawable.wishlist));
and do the same in else part and check the output..
Note :
getResources().getDrawable is deprecated.
You can try ContextCompat.getDrawable:
holder.wish_list.setImageDrawable(ContextCompat.getDrawable(context,
R.drawable.wishlist));
UpDate :
check this way.
if(state == true){
// here is default icon and set api value and send it
}else{
// here is click wishlist icon and set api value and send it
}
UpDate 2 :
public class FragmentOne_Adapter extends CursorAdapter {
FragmentOne_DbAdapter dbHelper;
public FragmentOne_Adapter(Context context, Cursor c, int flags) {
super(context, c, flags);
// TODO Auto-generated constructor stub
dbHelper = new FragmentOne_DbAdapter(context);
dbHelper.open();
}
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
// TODO Auto-generated method stub
final ViewHolder holder = (ViewHolder) view.getTag();
final int _id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
String title = cursor.getString(cursor.getColumnIndexOrThrow("title"));
String artist = cursor.getString(cursor.getColumnIndexOrThrow("artist"));
String volume = cursor.getString(cursor.getColumnIndexOrThrow("volume"));
final String favorite = cursor.getString(cursor.getColumnIndexOrThrow("favorite"));
String number = cursor.getString(cursor.getColumnIndexOrThrow("number"));
// Populate fields with extracted properties
holder.txtTitle.setText(title);
holder.txtArtist.setText(artist);
holder.txtVolume.setText(volume);
holder.txtNumber.setText(number);
if (favorite.matches("0")) {
holder.buttonHeart.setImageResource(R.drawable.heart);
} else {
if (favorite.matches("1")) {
holder.buttonHeart.setImageResource(R.drawable.heartred);
} else {
holder.buttonHeart.setImageResource(R.drawable.heart);
}
}
holder.buttonHeart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (arg0 != null) {
FragmentOne_DbAdapter database = new FragmentOne_DbAdapter(context);
database.open();
if (favorite.matches("0")) {
database.updateItemFavorite(_id, "1");
holder.buttonHeart.setImageResource(R.drawable.heartred);
} else if (favorite.matches("1")) {
database.updateItemFavorite(_id, "0");
holder.buttonHeart.setImageResource(R.drawable.heart);
}
}
FragmentOne_Adapter.this.changeCursor(dbHelper.fetchAllPlayer1());
}
});
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
// View rowView = ((LayoutInflater) context
// .getSystemService("layout_inflater")).inflate(
// R.layout.fragment_fragment_one_slview, parent, false);
View rowView = LayoutInflater.from(context).inflate(R.layout.fragment_fragment_one_slview, parent, false);
ViewHolder holder = new ViewHolder();
holder.txtTitle = (TextView) rowView.findViewById(R.id.title);
holder.txtArtist = (TextView) rowView.findViewById(R.id.artist);
holder.txtVolume = (TextView) rowView.findViewById(R.id.volume);
holder.txtNumber = (TextView) rowView.findViewById(R.id.number);
holder.buttonHeart = (ImageButton) rowView.findViewById(R.id.heart);
rowView.setTag(holder);
return rowView;
}
class ViewHolder {
TextView txtTitle;
TextView txtArtist;
TextView txtVolume;
TextView txtNumber;
ImageButton buttonHeart;
}
}
contact on list view with select all option and search option on android
i have tried a lot of ways but no matter to find a list view with name,phone no and check box for everyone and also a select all button and search option
public void onTextChanged(CharSequence s,int start, int before, int count)
{
textlength = et.getText().length();
// et.setText(textlength);
if(et.getText().toString().equalsIgnoreCase("helloo")){
// Toast.makeText(getApplicationContext(),"jd",1000).show();
for (int i = 0; i < name1.size(); i++)
{
if (textlength <= name1.size())
{
Toast.makeText(getApplicationContext(),"searching.....inside",1000).show();
if(et.getText().toString().equalsIgnoreCase((String)((CharSequence) name1).subSequence(0,textlength)))
{
// array_sort.addAll(name1);
}
}
if(et.getText().toString().equalsIgnoreCase(
(String)(CharSequence) name1)){
Toast.makeText(getApplicationContext(),"searching.....",1000).show();
}
}
lv.setAdapter(new ArrayAdapter<String>
(contact_fetch.this,
android.R.layout.simple_list_item_1, array_sort));
}
}
});
I had the same problem.Finally I solved with this code. Hope It will help you :)
//layout function
public void lay_out(List<String> exp1,int k){
LayoutInflater layoutInflater =
(LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
container.removeAllViews();
for(int i=0;i<exp1.size();i++){
final View addView = layoutInflater.inflate(R.layout.row, null);
TextView tv=(TextView)addView.findViewById(R.id.textView1);
final CheckBox cb=(CheckBox) addView.findViewById(R.id.checkbox1);
if(k==0)
{
cb.setChecked(false);
}
else
{
cb.setChecked(true);
}
tv.setText(name1.get(i));
cb.setText(phno1.get(i));
container.addView(addView);
cb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(getApplicationContext(),cb.getText().toString(),10).show();
if(cb.isChecked()==true){
if(checkedcontacts.length()<0)
{
for(int i=0;i<=checkedcontacts.length();i++)
{
if(!checkedcontacts.equals(cb.getText().toString()))
{
// insertion
checkedcontacts.append(cb.getText().toString());
checkedcontacts.append("\n");
}
}
}
else{
checkedcontacts.append(cb.getText().toString());
checkedcontacts.append("\n");
}
}
else if(cb.isChecked()==false){
s_all.setChecked(false);
try{
Toast.makeText(getApplicationContext(),cb.getText().toString(),10).show();
//Pattern.compile(cb.getText().toString()).matcher(checkedcontacts).replaceAll("");
checkedcontacts.delete(checkedcontacts.indexOf(cb.getText().toString()),
cb.getText().toString().length());
}
catch(Exception e){
System.out.println("error on array"+e);
}
}
}
});
container.setVisibility(View.VISIBLE);
}
}
Try this code to get all contacts with checkboxex:
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
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();
System.out.println(".............." + ma.mCheckStates.size());
for (int i = 0; i < name1.size(); i++)
{
if (ma.mCheckStates.get(i) == true) {
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
} else {
System.out.println("Not Checked......"
+ name1.get(i).toString());
}
}
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));
System.out.println(".................." + phoneNumber);
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) {
// 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.row, null);
TextView tv = (TextView) vi.findViewById(R.id.contact_name);
tv1 = (TextView) vi.findViewById(R.id.phone_number);
cb = (CheckBox) vi.findViewById(R.id.checkBox_id);
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);
System.out.println("hello...........");
notifyDataSetChanged();
}
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);
}
}
}
dispay.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"
android:id="#+id/lv"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Select" />
</RelativeLayout>
Row.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/contact_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="John Doe"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/phone_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/contact_name"
android:text="(999)999-9999"
android:textAppearance="?android:attr/textAppearanceMedium" />
<CheckBox
android:id="#+id/checkBox_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
first i'm fetching all messages to my app to be store in listview then I'm selecting messages from listview using checkboxes and wish to send these selected sms to a single number that is predefined and wish to use the selected sms as body of message to be send to single no. but the problem is that the message sent contains complete listview messages not the selected one. So please someone correct me where i'm wrong in code as i wish to send only selected messages not the complete listview items(messages)
public class MainActivity extends Activity implements OnItemClickListener, OnClickListener{
Button send;
ListView listViewSMS;
Cursor cursor;
SMSListAdapter smsListAdapter;
Context context;
SharedPreferences prefs=null;
ArrayAdapter<SMSListModel> adapter;
List<SMSListModel> list = new ArrayList<SMSListModel>();
TextView textViewSMSSender, textViewSMSBody;
int i;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
listViewSMS=(ListView)findViewById(R.id.lvSMS);
send = (Button)findViewById(R.id.btnproperty);
send.setOnClickListener(this);
textViewSMSSender=(TextView)findViewById(R.id.tvSMSSend);
textViewSMSBody=(TextView)findViewById(R.id.tvSMSBody);
cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
smsListAdapter = new SMSListAdapter(this,getModel());
listViewSMS.setAdapter(smsListAdapter);
listViewSMS.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
TextView label = (TextView) v.getTag(R.id.tvSMSSend);
CheckBox checkbox = (CheckBox) v.getTag(R.id.cbSelect);
Toast.makeText(v.getContext(), label.getText().toString()+" "+isCheckedOrNot(checkbox), Toast.LENGTH_LONG).show();
}
private String isCheckedOrNot(CheckBox checkbox) {
if(checkbox.isChecked())
return "is checked";
else
return "is not checked";
}
private List<SMSListModel> getModel() {
if(cursor.getCount()>0){
for(i=0;i<cursor.getCount();i++){
if(cursor.moveToPosition(i)){
list.add(new SMSListModel(cursor.getString(cursor.getColumnIndex("address")),cursor.getString(cursor.getColumnIndex("body"))));
}
}
}
return list;
}
#Override
public void onClick(View v) {
if( v == send){
mDialog();
}
public void mDialog(){
// Show The Dialog with Selected SMS
AlertDialog dialog = new AlertDialog.Builder(context).create();
dialog.setTitle("Message App");
dialog.setIcon(android.R.drawable.ic_dialog_info);
dialog.setMessage("Count : ");
dialog.setButton(DialogInterface.BUTTON_POSITIVE, "ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
String phoneNo = "111";
if(list.size()>0){
for(i=0;i<list.size();i++){
if(list.get(i).isSelected()){
try{
SmsManager smsManager = SmsManager.getDefault();
StringBuilder builder = new StringBuilder();
for(SMSListModel p: list){
builder.append(p.toString());
builder.append('\n');
}
String sms = builder.toString();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",Toast.LENGTH_LONG).show();
}
catch (Exception e){
Toast.makeText(getApplicationContext(),"SMS faild, please try again later!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
dialog.dismiss();
}
}
}
}
});
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "SMS not Sent",Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
dialog.show();
}
public class SMSListAdapter extends ArrayAdapter<SMSListModel> {
private final List<SMSListModel> list;
private final Activity mContext;
boolean checkAll_flag = false;
boolean checkItem_flag = false;
public SMSListAdapter(Activity context,List<SMSListModel> list)
{
super(context, R.layout.listview_each_item, list);
mContext = context;
this.list = list;
}
static class ViewHolder {
protected TextView textAddress;
protected TextView textBody;
protected CheckBox checkbox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = mContext.getLayoutInflater();
convertView = inflator.inflate(R.layout.listview_each_item, null);
viewHolder = new ViewHolder();
viewHolder.textAddress = (TextView) convertView.findViewById(R.id.tvSMSSend);
viewHolder.textBody = (TextView) convertView.findViewById(R.id.tvSMSBody);
viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.cbSelect);
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
list.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.tvSMSSend, viewHolder.textAddress);
convertView.setTag(R.id.tvSMSBody, viewHolder.textBody);
convertView.setTag(R.id.cbSelect, viewHolder.checkbox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkbox.setTag(position); // This line is important.
viewHolder.textAddress.setText(list.get(position).getAddress());
viewHolder.textBody.setText(list.get(position).getBody());
viewHolder.checkbox.setChecked(list.get(position).isSelected());
return convertView;
}
public class SMSListModel {
private String address;
String body;
private boolean selected;
public SMSListModel(String address, String body) {
this.address = address;
this.body = body;
}
public String getAddress() {
return address;
}
public String getBody() {
return body;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public String toString(){
return body;
}}
May I know why you want to select multiple rows. I mean what exact action you want to perform by selecting multiple rows?
Here is the updated code for you. Please let me know in case you didn't get any code:
---------------
package com.example.multiselectlist;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnItemClickListener, OnClickListener{
Button btnDelete;
ListView listViewSMS;
Cursor cursor;
SMSListAdapter smsListAdapter;
Context context;
ArrayAdapter<SMSListModel> adapter;
List<SMSListModel> list = new ArrayList<SMSListModel>();
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
listViewSMS=(ListView)findViewById(R.id.lvSMS);
btnDelete = (Button)findViewById(R.id.buttonDelete);
cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
smsListAdapter = new SMSListAdapter(this,getModel());
listViewSMS.setAdapter(smsListAdapter);
listViewSMS.setOnItemClickListener(this);
btnDelete.setOnClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
TextView label = (TextView) v.getTag(R.id.tvSMSSend);
CheckBox checkbox = (CheckBox) v.getTag(R.id.cbSelect);
Toast.makeText(v.getContext(), label.getText().toString()+" "+isCheckedOrNot(checkbox), Toast.LENGTH_LONG).show();
}
private String isCheckedOrNot(CheckBox checkbox) {
if(checkbox.isChecked())
return "is checked";
else
return "is not checked";
}
private List<SMSListModel> getModel() {
if(cursor.getCount()>0){
for(int i=0;i<cursor.getCount();i++){
if(cursor.moveToPosition(i)){
list.add(new SMSListModel(cursor.getString(cursor.getColumnIndex("address")),cursor.getString(cursor.getColumnIndex("body"))));
}
}
}
return list;
}
#Override
public void onClick(View v) {
int id = v.getId();
switch(id){
case R.id.buttonDelete:
if(list.size()>0){
for(int i=0;i<list.size();i++){
if(list.get(i).isSelected()){
list.remove(i);
}
}
smsListAdapter = new SMSListAdapter(this,list);
smsListAdapter.notifyDataSetChanged();
listViewSMS.setAdapter(smsListAdapter);
}
break;
case R.id.buttonSend:
String contactNum = "+123456789";
String messageList = "";
if(list.size()>0){
for(int i=0;i<list.size();i++){
if(list.get(i).isSelected()){
if(messageList.equals(""))
messageList = list.get(i).getBody();
else
messageList = messageList+";"+list.get(i).getBody();
}
}
Log.v("messageList",""+messageList);
Uri sendSmsTo = Uri.parse("smsto:" + contactNum);
Log.d("sendSmsTo",""+sendSmsTo);
Intent intent = new Intent(android.content.Intent.ACTION_SENDTO, sendSmsTo);
intent.putExtra("sms_body", messageList);
startActivityForResult(intent, 100);
}
}
}
}
SMSListModel class:
package com.example.multiselectlist;
public class SMSListModel {
private String address;
String body;
private boolean selected;
public SMSListModel(String address, String body) {
this.address = address;
this.body = body;
}
public String getAddress() {
return address;
}
public String getBody() {
return body;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
SMSListAdapter class:
package com.example.multiselectlist;
import java.util.List;
import android.app.Activity;
import android.util.Log;
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 SMSListAdapter extends ArrayAdapter<SMSListModel> {
private final List<SMSListModel> list;
private final Activity mContext;
boolean checkAll_flag = false;
boolean checkItem_flag = false;
public SMSListAdapter(Activity context,List<SMSListModel> list)
{
super(context, R.layout.listview_each_item, list);
mContext = context;
this.list = list;
}
static class ViewHolder {
protected TextView textAddress;
protected TextView textBody;
protected CheckBox checkbox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = mContext.getLayoutInflater();
convertView = inflator.inflate(R.layout.listview_each_item, null);
viewHolder = new ViewHolder();
viewHolder.textAddress = (TextView) convertView.findViewById(R.id.tvSMSSend);
viewHolder.textBody = (TextView) convertView.findViewById(R.id.tvSMSBody);
viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.cbSelect);
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
list.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.tvSMSSend, viewHolder.textAddress);
convertView.setTag(R.id.tvSMSBody, viewHolder.textBody);
convertView.setTag(R.id.cbSelect, viewHolder.checkbox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkbox.setTag(position); // This line is important.
viewHolder.textAddress.setText(list.get(position).getAddress());
viewHolder.textBody.setText(list.get(position).getBody());
viewHolder.checkbox.setChecked(list.get(position).isSelected());
return convertView;
}
}
xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/buttonDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Delete" />
<ListView
android:id="#+id/lvSMS"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/buttonDelete" >
</ListView>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<CheckBox
android:id="#+id/cbSelect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" />
<TextView
android:id="#+id/tvSMSSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/cbSelect"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/cbSelect"
android:text="9998698700" />
<TextView
android:id="#+id/tvSMSBody"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/tvSMSSend"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/tvSMSSend"
android:text="body" />
</RelativeLayout>
You can always use:
yourListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
To choose multiple items, remember that its interface depend on you creating it.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:drawable="#color/white" />
<item
android:state_selected="true"
android:drawable="#drawable/list_item_bg_selected" />
<item
android:drawable="#color/list_bg" />
</selector>
I am using ListActivity to display simple text with SimpleCursorAdapter to get the texts from my database. I have tried to debug the problem and found that the cursor is successfully fetching the result but the text is not displayed in the ListView.
Following is the ListActivity code I am using.
public class MyListActivity extends ListActivity{
Cursor myCursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
myCursor = getData();
startManagingCursor(myCursor);
ListAdapter myAdapter = new SimpleCursorAdapter(this, R.layout.display_details, myCursor, new String[]{MyDbHelper.ID_FIELD, MyDbHelper.NAME_FIELD}, new int[]{R.id.row_id, R.id.row_name});
setListAdapter(myAdapter);
}
private Cursor getData() {
return MyDBHelper.getRoutes();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
routesCursor.close();
}
}
and following is my xml file for each row in ListView
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/row_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/row_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/row_id"
android:layout_toRightOf="#+id/row_id"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
and my layout for ListActivity is as following
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView android:id="#+id/list" android:layout_width="fill_parent" android:layout_height="fill_parent">
</ListView>
</RelativeLayout>
Please provide me the solution. Thanks in advance.
This code can help your problem.
package com.example.getkontakdata;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnItemClickListener {
List<String> name1 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
MyAdapter ma;
Button select;
CheckBox cb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getAllCallLogs(this.getContentResolver());
final ListView lv= (ListView) findViewById(R.id.lv);
cb = (CheckBox) findViewById(R.id.checkBox1);
ma = new MyAdapter();
lv.setAdapter((ListAdapter) 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 arg0) {
// TODO Auto-generated method stub
StringBuilder checkedcontacts= new StringBuilder();
System.out.println(".............." + ma.mCheckStates.size());
for(int i = 0; i < phno1.size(); i++) {
if(ma.mCheckStates.get(i) == true) {
checkedcontacts.append(phno1.get(i).toString());
checkedcontacts.append(";");
} else {
System.out.println(".. Not Checked ......" + phno1.get(i).toString());
}
}
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllCallLogs(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));
//System.out.println(".................." + phoneNumber);
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener {
private SparseBooleanArray mCheckStates;
//private SparseBooleanArray nCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
MyAdapter() {
mCheckStates = new SparseBooleanArray(name1.size());
mCheckStates = new SparseBooleanArray(phno1.size());
mInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public String get(int position) {
// TODO Auto-generated method stub
return null;
}
#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.row, null);
TextView tv= (TextView) vi.findViewById(R.id.textView1);
tv1= (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Nama : "+ name1.get(position));
tv1.setText("Nomor Kontak : "+ phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener((OnCheckedChangeListener) this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
System.out.println("hello...........");
notifyDataSetChanged();
}
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);
}
}
}
Is there a way to create a search filter over my custom list view which created using BaseAdapter rather than ArrayAdapter, because I have only come across methods that are using ArrayAdapters in there Custom List Views. Follwing is what I have come acrossMaking a filter using Array Adapter
If you're using List collection then extend ArrayAdapter - it's subclass of BaseAdapter.
Override getView method (In your case just copy your old getView code with little modifications).
Override toString of object that is in your collection and set:
listView.setTextFilterEnabled(true);
Here is an example for list view created using base adapter.
I searched a lot but didn't get any satisfactorily solution.Hence I thought to put it up so that in future it might help others.
Here is the code of history_container.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical">
<EditText android:layout_width="fill_parent" android:layout_height="wrap_content"
android:id="#+id/filter_text" />
<FrameLayout android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="#+id/historyContainerLayout" />
</LinearLayout>
Here is the code of history_list_view.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" android:gravity="left|center"
android:layout_width="wrap_content" android:paddingBottom="5px"
android:paddingTop="5px" android:paddingLeft="5px">
<TextView android:text="#+id/historytext" android:id="#+id/historytext"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginLeft="10px" android:textColor="#0099CC"/>
</LinearLayout>
Here is the code of history_schedule.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ScrollView android:id="#+id/scrollItemInfo"
android:layout_width="fill_parent" android:layout_height="1000dip">
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<ListView android:id="#+id/historylist" android:layout_height="1000dip"
android:layout_width="fill_parent"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
Sorry, I am not being able to put the code in correct format.Seems something has changed as there is no tag anymore which was nice.But for user convenience this is also a good idea to have tab.
Maybe it is my fault that I'm not being able to post in correct format.And seems like we cannot post xml file content..So, think how the layout would have designed.
The activity code is :-
package com.testfilter;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
public class TestFilterListView extends Activity {
FrameLayout historyContainer;
ViewStub viewStub;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.history_container);
historyContainer = (FrameLayout) findViewById(R.id.historyContainerLayout);
EditText filterEditText = (EditText) findViewById(R.id.filter_text);
filterEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
historyContainer.removeAllViews();
final List<String> tempHistoryList = new ArrayList<String>();
tempHistoryList.addAll(historyList);
for(String data : historyList) {
if(data.indexOf((s.toString())) == -1) {
tempHistoryList.remove(data);
}
}
viewStub = new ViewStub(TestFilterListView.this, R.layout.history_schedule);
viewStub.setOnInflateListener(new ViewStub.OnInflateListener()
{
public void onInflate(ViewStub stub, View inflated)
{
setUIElements(inflated, tempHistoryList);
}
});
historyContainer.addView(viewStub);
viewStub.inflate();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
setViewStub();
}
/********************************************************************************************************/
private void setViewStub()
{
historyList.add("first");
historyList.add("second");
historyList.add("third");
historyList.add("fourth");
historyList.add("fifth");
historyList.add("sixth");
historyList.add("seventh");
viewStub = new ViewStub(TestFilterListView.this, R.layout.history_schedule);
viewStub.setOnInflateListener(new ViewStub.OnInflateListener()
{
public void onInflate(ViewStub stub, View inflated)
{
setUIElements(inflated, historyList);
}
});
historyContainer.addView(viewStub);
viewStub.inflate();
}
/********************************************************************************************************/
final List<String> historyList = new ArrayList<String>();
String displayName = "";
ListView historyListView;
private void setUIElements(View v, List<String> historyLists)
{
if (v != null)
{
historyScheduleData.clear();
//historyList.clear();
historyScheduleData.addAll(historyLists);
historyListView = (ListView) findViewById(R.id.historylist);
historyListView.setAdapter(new BeatListAdapter(this));
registerForContextMenu(historyListView);
}
}
/********************************************************************************************************/
private static class BeatListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public BeatListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return historyScheduleData.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.history_list_view, null);
holder = new ViewHolder();
holder.historyData = (TextView) convertView
.findViewById(R.id.historytext);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.historyData.setText(historyScheduleData.get(position));
return convertView;
}
static class ViewHolder {
TextView historyData;
}
}
private static final List<String> historyScheduleData = new ArrayList<String>();
}
ArrayAdapter is a child class of BaseAdapter.
Source code for ArrayAdapter is here. Take a look at it..
This should solve your problem.
Here is an example . Edit and use what you need.
public class CustomListAdapter extends BaseAdapter {
private ArrayList<String> countryStringList;
private ArrayList<Integer> countryImageList;
private LayoutInflater mInFlater;
// private Bitmap mIcon1;
// private Bitmap mIcon2;
private int layoutID;
private Context context;
// private LayoutInflater mInflater;
public CustomListAdapter(Context context, int textViewResourceId,
ArrayList<String> stringObjects, ArrayList<Integer> imgObjects) {
super();
this.context = context;
countryStringList = stringObjects;
countryImageList = imgObjects;
layoutID = textViewResourceId;
mInFlater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
// return countryStringList.size();
return countryStringList.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 position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null) {
convertView = mInFlater.inflate(layoutID, null);
holder = new ViewHolder();
holder.textCountryName = (TextView) convertView
.findViewById(R.id.txtSelectedCountryName);
holder.icon = (ImageView) convertView
.findViewById(R.id.imgSelectedCountryImage);
holder.textCountryPosition = (TextView) convertView
.findViewById(R.id.txtSelectedCountryPosition);
// holder.checkBoxListView=(CheckBox)convertView.findViewById(R.id.CheckBoxListView);
holder.relativeLayoutList = (RelativeLayout) convertView
.findViewById(R.id.relativeLayoutListItem);
holder.checkBoxListView = (CheckBox) convertView
.findViewById(R.id.checkBoxSelectedCountry);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
// holder=(ViewHolder)convertView.findViewById(R.id.TextViewIcon1)
}
holder.checkBoxListView.setTag(position);
holder.textCountryName.setText(countryStringList.get(position));
holder.textCountryPosition.setText(position + 1 + "/"
+ countryStringList.size());
holder.icon.setImageResource((countryImageList.get(position)));
if (ListViewController.checkStatusList.get(position).equalsIgnoreCase("present")) {
holder.checkBoxListView.setVisibility(View.VISIBLE);
} else {
holder.checkBoxListView.setVisibility(View.GONE);
}
/*
* holder.checkBoxListView.setOnCheckedChangeListener(new
* OnCheckedChangeListener(){
*
* #Override public void onCheckedChanged(CompoundButton buttonView,
* boolean isChecked) { // TODO Auto-generated method stub
*
* ListActivityImplementation listActivityImplementation = new
* ListActivityImplementation(); //show("Checkbox");
* ListActivityImplementation.countryStringList.remove(position);
* ListActivityImplementation.countryImageList.remove(position);
* ListActivityImplementation.lv.invalidateViews();
*
* //ListActivityImplementation.show("Checkbox"); }
*
* }) ;
*/
holder.textCountryName.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
holder.textCountryPosition.setText(position + 1 + "/"
+ countryStringList.size() + "clicked");
}
});
holder.checkBoxListView
.setOnCheckedChangeListener(new android.widget.CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
MathHelper.showToast(context, buttonView.getTag()
+ " clicked");
}
});
return convertView;
}
}
class ViewHolder {
TextView textCountryName;
ImageView icon;
TextView textCountryPosition;
RelativeLayout relativeLayoutList;
CheckBox checkBoxListView;
}