Can not fetch contacts with synchronized gmail accounts - android

I am working on an application in which i need to fetch all the contacts from the contact book and display. i want the user to select some contacts and add them in a group which is saved in db.
i have created a custom list view- contactitem.xml-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/contactname"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:layout_marginLeft="20dp"
android:ellipsize="end"
android:singleLine="true"
android:clickable="true"/>
<TextView
android:id="#+id/contactnum"
android:layout_width="wrap_content"
android:textColor="#color/White"
android:clickable="true"
android:layout_gravity="center_vertical"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:text="#string/add_contacts"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:focusable="false"
android:focusableInTouchMode="false"/>
</LinearLayout>
i have a SelectContact class for fetching contacts from Contact book-
public class SelectContacts extends Activity implements OnClickListener{
private String groupName;
private Button back;
private Button home;
private List<Contact> list = new ArrayList<Contact>();
private ListView contactList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selectcontacts);
Bundle bundle = getIntent().getExtras();
groupName=bundle.getString("groupName");
back=(Button)findViewById(R.id.back_button);
back.setOnClickListener(this);
home=(Button)findViewById(R.id.home_button);
home.setOnClickListener(this);
contactList=(ListView)findViewById(R.id.contactsListView);
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
cur.moveToFirst();
if (cur.getCount() > 0) {
do{
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
String[] fields={ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, fields, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null);
pCur.moveToFirst();
do {
String number=pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Contact c=new Contact(name,number);
list.add(c);
}while (pCur.moveToNext());
pCur.close();
}
}while (cur.moveToNext());
ContactAdapter contactAdapter=new ContactAdapter(this, R.layout.contactitem, list, contactList,groupName);
contactList.setAdapter(contactAdapter);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent= new Intent();
if(v==back){
Bundle bundle = new Bundle();
bundle.putString("groupName", groupName);
intent.putExtras(bundle);
intent.setClass(SelectContacts.this, GroupDetails.class);
startActivity(intent);
}
if(v==home){
intent.setClass(SelectContacts.this, Welcome.class);
startActivity(intent);
}
}
}
and implemented a custom adapter- ContactAdapter-`
public class ContactAdapter extends ArrayAdapter<HashMap<String, Contact>>{
private ArrayList<HashMap<String, Contact>> items;
private LayoutInflater mInflater ;
public ContactAdapter(Context context, int textViewResourceId, ArrayList<HashMap<String, Contact>> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
mInflater = LayoutInflater.from(getContext());
ViewHolder holder;
if(convertView==null){
convertView = mInflater.inflate(R.layout.contactitem, parent, false);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.contactname);
holder.number = (TextView) convertView.findViewById(R.id.contactnum);
holder.add=(Button)convertView.findViewById(R.id.add);
convertView.setTag(holder);
}
else{
holder=(ViewHolder)convertView.getTag();
}
String name=items.get(position).get(""+position).getContactName();
String number=items.get(position).get(""+position).getContactNum();
holder.name.setText(name);
holder.number.setText(number);
return convertView;
}
static class ViewHolder{
TextView name;
TextView number;
Button add;
}
}
here Contact is a simple POJO-
public class Contact {
private String contactName;
private String contactNum;
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getContactNum() {
return contactNum;
}
public void setContactNum(String contactNum) {
this.contactNum = contactName;
}
}
i am a newbie in android..
The above code works quiet fine on emulater and fetch contact name and numbers to display in list. but when i test this code on phone which have a Gmail account syncronized, it got crashed with following error..
CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
I don't have any idea why this is happening. Please give some suggestions...

above code is given to you is android contact data not the gmail or any other contact because your phone is sync with your gmail contact or any other contact only phone contact is allow not all the gmail or skype contact.

Related

Is it possible to add different items into android listview

i have a ListView in my application, i fetch contacts from user phonebook then displays them into ListView, now what i want to do is to add different child views into ListView item based on some condition like my application check each phonebook contact for it's availability on server database and what i want to achieve is to add voice/video call buttons for that particular contact and add invite button for all other contacts that are not available in database.
My condition applies on these three child's of ListView item, voice call button, video call button and invite button and my condition is if user is available in database then i only want to display voice/video call button and hide invite button but if the user is not available then i wan to display invite button and hide audio/video call buttons
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">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/contacts_listview"/>
</RelativeLayout>
ListView Item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:minHeight="?android:attr/listPreferredItemHeight"
android:padding="16dp">
<ImageView
android:id="#+id/contact_item_icon"
android:layout_width="50dp"
android:layout_height="50dp"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:paddingLeft="16dp">
<TextView
android:id="#+id/contact_item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Feel The Light" />
<TextView
android:id="#+id/contact_item_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Home" />
</LinearLayout>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_user_audio_call_dark"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_user_video_call_dark"/>
<Button
android:layout_width="wrap_content"
android:layout_height="30dp"
android:text="Invite"
android:background="#drawable/selector_button_green_oval"
android:textColor="#color/white"/>
</LinearLayout>
ContactsFragment
public class ContactsAdapter extends ArrayAdapter<ContactItem> {
private static final String LOG_TAG = ContactsAdapter.class.getSimpleName();
public ContactsAdapter(Activity context, List<ContactItem> contactItems) {
super(context, 0, contactItems);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ContactItem contactItem = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.contact_list_item, parent, false);
}
ImageView contactImage = (ImageView) convertView.findViewById(R.id.contact_item_icon);
contactImage.setImageResource(contactItem.contactImage);
TextView contactName = (TextView) convertView.findViewById(R.id.contact_item_name);
contactName.setText(contactItem.contactName);
TextView contactNumber = (TextView) convertView.findViewById(R.id.contact_item_number);
contactNumber.setText(contactItem.contactNumber);
return convertView;
}
}
ContactsFragment
public class ContactsListFragment extends Fragment {
private ContactsAdapter contactsAdapter;
public static ContactsListFragment newInstance() {
return new ContactsListFragment();
}
public ContactsListFragment() {
}
ArrayList<String> contactName = new ArrayList<>();
ArrayList<String> contactNumber = new ArrayList<>();
ArrayList<ContactItem> contactsAvailable = new ArrayList<>();
ArrayList<ContactItem> contactsInvite = new ArrayList<>();
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cursor cursor = getActivity().getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null
);
String currentNumber = "";
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
number = number.replaceAll(" ", "");
char c = number.charAt(0);
char c1 = number.charAt(1);
String s = Character.toString(c)+Character.toString(c1);
if (s.equals("00")) {
number = number.replaceAll("00", "+");
}
if (number.length() == 12) {
number = "+" + number;
}
if (number.length() == 13) {
if (!currentNumber.equals(number)) {
contactName.add(name);
contactNumber.add(number);
}
}
currentNumber = number;
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_contacts_list, container, false);
QBPagedRequestBuilder pagedRequestBuilder = new QBPagedRequestBuilder();
pagedRequestBuilder.setPage(1);
pagedRequestBuilder.setPerPage(50);
QBUsers.getUsersByLogins(contactNumber, pagedRequestBuilder, new QBEntityCallback<ArrayList<QBUser>>() {
#Override
public void onSuccess(ArrayList<QBUser> qbUsers, Bundle bundle) {
for (int i = 0; i < qbUsers.size(); i++) {
ContactItem contactItem = new ContactItem(qbUsers.get(i).getFullName(), qbUsers.get(i).getLogin(), R.drawable.ic_launcher);
contactsAvailable.add(contactItem);
}
contactsAdapter = new ContactsAdapter(getActivity(), contactsAvailable);
ListView listView = (ListView) rootView.findViewById(R.id.contacts_listview_available);
listView.setAdapter(contactsAdapter);
}
#Override
public void onError(QBResponseException e) {
Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
}
});
return rootView;
}
}
Try this:
Add a boolean flag isAvailableInDB in your ContactItem.java class.
Get contact list from your phonebook and check one by one with your server database.
If a contactItem exist in your database just set flag isAvailableInDB as true oterwise false for that contactItem.
After that add contactItem to ArrayList
Create ContactsAdapter and set it to ListView
Finally, add a condition in your adapter's getView() method to check the contactItem flag isAvailableInDB. If true, show voice/video call button & hide invite button and if false, show invite button & hide voice/video call button.
Give an id to XML button's:
<ImageButton
android:id="#+id/button_voice_call"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_user_audio_call_dark"/>
<ImageButton
android:id="#+id/button_video_call"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_user_video_call_dark"/>
<Button
android:id="#+id/button_invite"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:text="Invite"
android:background="#drawable/selector_button_green_oval"
android:textColor="#color/white"/>
In your adapter's getView() method:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ContactItem contactItem = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.contact_list_item, parent, false);
}
ImageView contactImage = (ImageView) convertView.findViewById(R.id.contact_item_icon);
contactImage.setImageResource(contactItem.contactImage);
TextView contactName = (TextView) convertView.findViewById(R.id.contact_item_name);
contactName.setText(contactItem.contactName);
TextView contactNumber = (TextView) convertView.findViewById(R.id.contact_item_number);
contactNumber.setText(contactItem.contactNumber);
ImageButton buttonVoiceCall= (ImageButton) convertView.findViewById(R.id.button_voice_call);
ImageButton buttonVideoCall= (ImageButton) convertView.findViewById(R.id.button_video_call);
Button buttonVoiceCall= (Button) convertView.findViewById(R.id.button_invite);
if(contactItem.getIsAvailableInDB())
{
buttonVoiceCall.setVisibility(View.VISIBLE);
buttonVideoCall.setVisibility(View.VISIBLE);
buttonInvite.setVisibility(View.GONE);
}
else
{
buttonVoiceCall.setVisibility(View.GONE);
buttonVideoCall.setVisibility(View.GONE);
buttonInvite.setVisibility(View.VISIBLE);
}
return convertView;
}
Hope this will help you~
You could add a flag on the ContactItem class and set it true or false, if it is available in the Database and then set the visibility of the buttons in the adapter according to this flag.

Update custom listview from a button

I have a custom row item xml and a Activity xml which has a button, a textbox and a listview. Can anybody give me a very simple example on how this is done? I know i will need a adapter (what it extends i dont know) and update it from the button
I have tried getting the list view updated from the button with the editview text but cant get the adapter code to be hit. I am looking at base adapters now but cant help but feel this shouldn't be complicated and need so many override methods.
Activity class
public class InvitePlayers_Activity extends Activity {
ListViewAdapter emailAdapter = null;
ImageView imgView_mail;
ImageView imgView_confirm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); //remove title bar
setContentView(R.layout.activity_inviteplayers);
//Generate list View from ArrayList
displayListView();
}
private void displayListView() {
//assign controls
final ListView listView = (ListView) findViewById(R.id.listView_invitePlayers);
imgView_mail = (ImageView)findViewById(R.id.imgView_mail);
//Test data
ArrayList<String> inviteNew = new ArrayList<String>();
final ArrayList<ArrayList<String>> inviteList = new ArrayList<ArrayList<String>>();
emailAdapter = new ListViewAdapter(this,inviteList);
listView.setAdapter(emailAdapter);
// Assign adapter to ListView
listView.setTextFilterEnabled(true);
//Edit listeners
imgView_mail.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
//variables
final String enteredMail = "testListViewEntry";
final ArrayList<ArrayList<String>> inviteList = new ArrayList<ArrayList<String>>();
ArrayList<String> invite = new ArrayList<String>();
invite.add(0, enteredMail);//add first email
invite.add(1,"icon_invitestatussent.png"); //add first status icon
inviteList.add(invite);
emailAdapter.notifyDataSetChanged();
listView.setAdapter(emailAdapter);
}
});
}
}
Adapter class
public class ListViewAdapter extends BaseAdapter {
private Activity context;
ArrayList<ArrayList<String>> inviteDetails = new ArrayList<ArrayList<String>>();
public ListViewAdapter(Activity context, ArrayList<ArrayList<String>> inviteDetails ) {
this.inviteDetails = inviteDetails;
this.context = context;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
public View getView(int position, View view, ViewGroup parent){
//Inflater
LayoutInflater inflater = context.getLayoutInflater();
//get row view
if (view == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
view = mInflater.inflate(R.layout.list_item_email, null);
}
//assign controls
final TextView textView_playerEmail = (TextView) view.findViewById(R.id.textView_playerEmail);
ImageView imgView_inviteStatus = (ImageView) view.findViewById(R.id.imgView_inviteStatus);
//Assign control values that are dynamic
textView_playerEmail.setText(inviteDetails.get(position).get(0));
imgView_inviteStatus.setImageResource(R.drawable.icon_invitestatussent);
return view;
}
public ArrayList<ArrayList<String>> addInvite(ArrayList<String> inviteDetails, ArrayList<ArrayList<String>> currentInvites)
{
currentInvites.add(inviteDetails);
return currentInvites;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
Custom row xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp"
android:id="#+id/textView_playerEmail"
android:textColor="#color/white"
android:text="item1">
</TextView>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgView_inviteStatus" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgView_remove"
android:src="#drawable/btn_cancel" />
Activity layout
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="1"
android:gravity="left|center">
<ImageView
android:layout_width="45dp"
android:layout_height="34dp"
android:id="#+id/imgView_mail"
android:src="#drawable/btn_mail"
android:layout_weight="0.22"
android:padding="3dp" />
</LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView_invitePlayers"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:id="#+id/btn_confirm"
android:src="#drawable/btn_confirm"
android:clickable="false"
android:adjustViewBounds="true"
android:layout_gravity="center_horizontal"
android:padding="2dp"
android:layout_weight="1" />
</LinearLayout>
From reading the description of the question I think you need to set custom adapter to show the elements in you listview. This is how you set the custom adapter for the listview:
public class Notes_list extends BaseAdapter
{
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
public Notes_list(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname)
{
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
}
public int getCount() {
return id.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int pos, View child, ViewGroup arg2) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.custom_row, null);
mHolder = new Holder();
// mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
child.setTag(mHolder);
} else
{
mHolder = (Holder) child.getTag();
}
// mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
return child;
}
public class Holder
{
// TextView txt_id;
TextView txt_fName;
TextView txt_lName;
}
}
now in your main activity where you have to call the list enter code like this:
private ListView userList;
private ArrayList<Employee> itemsList = new ArrayList<modelName>();
userList = (ListView) findViewById(R.id.List);
UserList disadpt = new UserList(MainActivity.this, itemsList);
userList.setAdapter(disadpt);
Hope it helps...

how to display data from a database into two Textview

i'am trying develop an application which save points and date in a database but, i want to show into a list the points in green and date in white. The points and the time points are above one another. My code:
Class database
public class BaseDeDatos extends SQLiteOpenHelper{
public BaseDeDatos(Context context) {
super(context, "puntuaciones", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE puntuaciones (puntos INTEGER,fecha VARCHAR)");
}
public void save(int points,String date){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("INSERT INTO puntuaciones VALUES("+points+","+"'"+date+"')");
db.close();
}
public Vector<String> listPoints(int cantidad) {
Vector<String> result = new Vector<String>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT puntos, fecha FROM " +
"puntuaciones ORDER BY puntos DESC LIMIT " +cantidad, null);
while (cursor.moveToNext()){
result.add(cursor.getInt(0)+cursor.getString(1));
}
cursor.close();
db.close();
return result;
}
and my class with the list
ListView lista;
BaseDeDatos bd;
Vector maxRegis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maximos_registros);
lista=(ListView)findViewById(R.id.lista);
lista.setBackgroundColor(color.Aquamarine);
maxRegis= new Vector();
bd= new BaseDeDatos(this);
maxRegis=bd.listaPuntos(10);
ArrayAdapter adaptador= new ArrayAdapter(this,R.layout.elemento_lista,R.id.tv1,maxRegis);
//MyAdapter adaptador= new MyAdapter(this,bd);
lista.setAdapter(adaptador);
}
and the code of R.layout.elemento_lista
<?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="?android:attr/listPreferredItemHeight" >
<TextView
android:id="#+id/tv1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="10dp"
android:layout_marginLeft="40dp"
android:inputType="textCapCharacters"
android:textColor="#FFD700"
android:textStyle="bold"
android:text="" />
<TextView
android:id="#+id/tv2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tv1"
android:layout_alignParentBottom="true"
android:textStyle="italic"
android:text="" />
if i make a special adapter shows nothing, but with ArrayAdapter shows into the same TextView.
You should use CustomAdapter which extends BaseAdapter
Here is my sample TodoApp with CustomAdapter.
You must inflate R.layout.elemento_lista in
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = inflater.inflate(R.layout.elemento_lista, null);
}
TextView title = (TextView) convertView.findViewById(R.id.todo_title);
title.setText(getItem(position));
return convertView;
}
Then find your TextView by id, setText, and that's all :-)

Howto show data from Array list to Custom ArrayAdapter

I am working on an application in which i need to fetch all the contacts from the contact book and display. i want the user to select some contacts and add them in a group which is saved in db.
i have created a custom list view- contactitem.xml-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/contactname"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:layout_marginLeft="20dp"
android:ellipsize="end"
android:singleLine="true"
android:clickable="true"/>
<TextView
android:id="#+id/contactnum"
android:layout_width="wrap_content"
android:textColor="#color/White"
android:clickable="true"
android:layout_gravity="center_vertical"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:text="#string/add_contacts"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:focusable="false"
android:focusableInTouchMode="false"/>
</LinearLayout>
i have a SelectContact class for fetching contacts from Contact book-
public class SelectContacts extends Activity implementsOnItemClickListener {
private List<Contact> list = new ArrayList<Contact>();
private ListView contact_list;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selectcontacts);
contact_list=(ListView)findViewById(R.id.contactsListView);
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
cur.moveToFirst();
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null);
pCur.moveToFirst();
while (pCur.moveToNext()) {
String number=pCur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Contact c=new Contact();
c.setContactName(name);
c.setContactNum(number);
list.add(c);
}
pCur.close();
}
ContactAdapter contactAdapter=new ContactAdapter(this, R.layout.contactitem, list);
contact_list.setAdapter(contactAdapter);
}
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
}
and implemented a custom adapter- ContactAdapter-
public class ContactAdapter extends ArrayAdapter<Contact>{
List<Contact> items;
LayoutInflater mInflater ;
Context context;
int layoutResourceId;
public ContactAdapter(Context context, int layoutResourceId, List<Contact> items) {
super(context, layoutResourceId, items);
this.layoutResourceId=layoutResourceId;
this.items = items;
this.context=context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = new ViewHolder();
if(row==null){
mInflater = ((Activity)context).getLayoutInflater();
row = mInflater.inflate(layoutResourceId, parent, false);
holder.name = (TextView) row.findViewById(R.id.contactname);
holder.number = (TextView) row.findViewById(R.id.contactnum);
holder.add=(Button)row.findViewById(R.id.add);
row.setTag(holder);
}else{
holder=(ViewHolder)row.getTag();
}
String name=items.get(position).getContactName();
String number=items.get(position).getContactNum();
holder.name.setText(name);
holder.number.setText(number);
holder.add.setText("Add");
return row;
}
static class ViewHolder{
TextView name;
TextView number;
Button add;
}
}
here Contact is a simple POJO-
public class Contact {
private String contactName;
private String contactNum;
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getContactNum() {
return contactNum;
}
public void setContactNum(String contactNum) {
this.contactNum = contactName;
}
}
i am a newbie in android..
Here when i start SelectContact activity it cannot display contact on the UI.. please help me guys...
Thanks
I will insist you to use List<Contact> list = new ArrayList<Contact>(); instead of using ArrayList<HashMap<String, Contact>> list= new ArrayList<HashMap<String, Contact>>();
You just need to fetch the Contact details and set the values to the Contact Class and add to the ArrayList object. And then just pass the list Object to ArrayAdapter class and use it. This is the easiest way, you are making it a bit complex using HashMap in this case.

Android listView - format specific items

So I'm relatively new to android programming, and currently working on a custom listView. What I'm trying to achieve is the following:
Retrieve a list of articles from a database.
Get all unique values from the 'category' column to create a list of
categories.
Populate a listView with these categories
Add a listener for each category click which takes the user to the
first article in that category.
I've managed to do all of the above, but now want to take it further. I have a status column in the database, where the value is either 'read' or 'unread'. What I want to do is the following:
If all articles in a category are 'read', to grey-out that category
in the listview, and to ignore clicks on that particular item.
I have absolutely no idea how to format individual items within a listview...any suggestions? My code is as follows:
start.java:
public class Start extends Activity {
private ListView mainListView ;
private ArrayAdapter<String> listAdapter ;
public static final String MYDATABASE_NAME = "questions.db";
public static final String MYDATABASE_TABLE = "questions";
public static final int MYDATABASE_VERSION = 1;
public static final String KEY_ID = "_id";
public static final String KEY_CONTENT = "category";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
// Query database
SQLiteDatabase db;
db = openOrCreateDatabase(
"questions.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
ArrayList<String> categoryList = new ArrayList<String>();
Cursor cur = db.query("questions", null, null, null, null, null, null);
cur.moveToFirst();
while (cur.isAfterLast() == false) {
if (categoryList.contains(cur.getString(11))) {
// do nothing
} else {
// add to list
categoryList.add(cur.getString(11));
}
cur.moveToNext();
}
cur.close();
Collections.sort(categoryList);
categoryList.add(0, "All");
// Find the ListView resource.
mainListView = (ListView) findViewById( R.id.mainListView );
// Create ArrayAdapter using the category list.
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, categoryList);
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );
mainListView.setTextFilterEnabled(true);
mainListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
String clickedCat = (String) mainListView.getItemAtPosition(position);
finish();
Intent myIntent = new Intent(getApplicationContext(), NextClass.class);
myIntent.putExtra("passedCategory", clickedCat);
myIntent.putExtra("startTrigger", "go");
startActivity(myIntent);
}
});
}
}
start.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#android:color/black">
<TextView
android:text="#string/categories"
android:layout_width="fill_parent"
android:layout_height="#dimen/topbar_container"
android:background="#drawable/topgradient"
android:gravity="center_vertical|center_horizontal"
android:textColor="#color/primarytext"
android:textSize="#dimen/topbar_font"
android:textStyle="bold"
android:shadowColor="#000000"
android:shadowDx="1"
android:shadowDy="1"
android:shadowRadius="2"></TextView>
<ListView android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/mainListView"></ListView>
</LinearLayout>
simplerow.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rowTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" android:textStyle="bold">
</TextView>
You need to set up a ViewBinder, then call listAdapter.setViewBinder.
You need to create a custom adapter for this:
CustomAdapter.class:
public class CustomAdapter extends SimpleCursorAdapter{
Cursor dataCursor;
LayoutInflater mInflater;
Context context;
ArrayList<String[]> arrayList;
public static HashMap<Integer,String> myList=new HashMap<Integer,String>();
public CustomAdapter(Context context, int layout, Cursor dataCursor, String[] from,
int[] to) {
super(context, layout, dataCursor, from, to);
this.context=context;
this.dataCursor = dataCursor;
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView==null)
{
convertView = mInflater.inflate(R.layout.custom_listitem, null);
holder = new ViewHolder();
holder.textview=(TextView)convertView.findViewById(R.id.textview);
holder.layout=(LinearLayout)findViewById(R.id.layout);
convertView.setTag(holder);
}
else
{
holder=(ViewHolder)convertView.getTag();
}
dataCursor.moveToPosition(position);
String id=Integer.toString(dataCursor.getInt(dataCursor.getColumnIndexOrThrow("_id")));
myList.put(position, id);
holder.textview.setText(dataCursor.getString(11));
if(dataCursor.getString(dataCursor.getColumnIndex("index")).equals("read"))
{
holder.layout.setBackgroundColor(Color.GRAY);
}
// other code according to the functionality you want
return convertView;
}
static class ViewHolder
{
TextView textview;
LinearLayout layout;
}
}
custom_listitem.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF"
android:id="#+id/layout"
android:padding="5dip"
>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="17dip"
android:gravity="left"
android:padding="5dip"
android:id="#+id/textview"
/>
</LinearLayout>
Now,use it in activity like:
MainActivity.class:
...
mainListView = (ListView) findViewById( R.id.mainListView );
Cursor cursor = db.query("questions", null, null, null, null, null, null);
CustomAdapter ca=new CustomsAdapter(context,R.layout.custom_listitem,cursor,new String[]{"id","index"},new int[]{R.id.textview,R.id.textview});
mainListView.setAdapter(ca);
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
String id=CustomAdapter.myList.get(position);
Cursor findIndex=db.query("questions", null, "_id="+id, null, null, null, null);
findIndex.moveToFirst();
if(findIndex.getString(findIndex.getColumnIndex("index").equals("unread"))
{
// do something for "unread" categories
}
}
});
...
I don't know the way,you can disable click on a particular listitem but yes,you can do the stuff under certain condition to let user feel like some of the items are unclickable.

Categories

Resources