Android cursor return empty contacts - android

I need to get all contacts that have at least a phone number. Android contacts may be picked from many accounts like gmail,skype,vibe etc. I made the classes i need to get the contacts i need. My problem that it gets anyway contacts that don't have at least 1 phone number and shows just their name and avatar. Can any1 say what I am doing wrong in my code? My code source is shared below.
ContactsActivity.class
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
selectionString = edtSearch.getText().toString();
String[] selectionArgs = {"%" + selectionString + "%", selectionString + "%", "%" + selectionString};
String selection = ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? OR "
+ ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? OR "
+ ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? AND "
+ ContactsContract.Contacts.HAS_PHONE_NUMBER + "=='1'";
return new CursorLoader(this,
ContactsContract.Contacts.CONTENT_URI, // URI
null, // projection fields
selection, // the selection criteria
selectionArgs, // the selection args
ContactsContract.Contacts.DISPLAY_NAME + " ASC" // the sort order
);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
ContactsAdapter.createCheckedContacts(data.getCount());
contactsAdapter.setCursor(data);
contactsAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
contactsAdapter.swapCursor(null);
}
ContactsAdapter.class
public class ContactsAdapter extends CursorAdapter {
static boolean status = true;
private static boolean[] checkedContacts;
private static Context context;
private static Cursor cursor;
public ContactsAdapter(Context context, Cursor c) {
super(context, c, 0);
this.context = context;
}
public static void setCursor(Cursor cursor) {
ContactsAdapter.cursor = cursor;
}
public static void createCheckedContacts(int count) {
checkedContacts = new boolean[count];
}
public static void saveSelectedContacts(ClientDao contactDao) {
for (int i = 0; i < checkedContacts.length; i++) {
if (checkedContacts[i]) {
cursor.moveToPosition(i);
DatabaseHelper.getInstance().saveClient(ContactUtils.cursorToContact(cursor, context), status);
status = !status;
}
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View convertView = ((Activity) context).getLayoutInflater().inflate(R.layout.contact_item, parent, false);
ViewHolder holder = new ViewHolder(convertView);
convertView.setTag(holder);
return convertView;
}
#Override
public void bindView(View convertView, final Context context, final Cursor cursor) {
final ViewHolder holder = (ViewHolder) convertView.getTag();
final Contact contact = ContactUtils.cursorToContact(cursor, context);
holder.tvName.setText(contact.getDisplayName());
if (isFirst(cursor)) {
holder.tvLetter.setVisibility(View.VISIBLE);
String letter = String.valueOf(Character.toUpperCase(contact.getDisplayName().charAt(0)));
holder.tvLetter.setText(letter);
} else {
holder.tvLetter.setVisibility(View.INVISIBLE);
}
convertView.setTag(convertView.getId(), contact);
if (!TextUtils.isEmpty(contact.getPhotoUri())) {
new ImageLoaderUtils.ContactImage(contact, convertView, holder.ivUserImage, context).execute();
} else {
holder.ivUserImage.setImageResource(R.drawable.ic_profile);
}
holder.inviteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ContactInvitationActivity_.class);
intent.putExtra("contact", contact);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
}
});
}
private boolean isFirst(Cursor cursor) {
Contact c1 = ContactUtils.cursorToContact(cursor, context);
if (cursor.getPosition() == 0)
return true;
cursor.moveToPrevious();
Contact c2 = ContactUtils.cursorToContact(cursor, context);
if (c1.getDisplayName() == null || c2.getDisplayName() == null)
return false;
if (Character.toUpperCase(c1.getDisplayName().charAt(0)) != Character.toUpperCase(c2.getDisplayName().charAt(0)))
return true;
return false;
}
private static class ViewHolder {
TextView tvName;
TextView tvLetter;
ImageView ivUserImage;
Button inviteBtn;
RelativeLayout rlContact;
private ViewHolder(View convertView) {
tvName = (TextView) convertView.findViewById(R.id.tvContactsName);
tvLetter = (TextView) convertView.findViewById(R.id.tvLetter);
ivUserImage = (ImageView) convertView.findViewById(R.id.ivUserIcon);
inviteBtn = (Button) convertView.findViewById(R.id.inviteBtn);
rlContact = (RelativeLayout) convertView.findViewById(R.id.rlContact);
}
}
}
ContactUtil.class
public class ContactUtils {
public static Contact cursorToContact(Cursor c, Context context) {
if (c == null || c.getPosition() < 0) return null;
Contact contactObj = new Contact();
try {
contactObj.setID(c.getString(c.getColumnIndex(ContactsContract.Contacts._ID)));
contactObj.setDisplayName(c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
contactObj.setPhotoUri(c.getString(c.getColumnIndex(ContactsContract.Contacts.PHOTO_URI)));
contactObj.setPhoneNumber("");
contactObj.setEmail("");
setPhoneNumber(c, contactObj, context);
setEmail(contactObj, context);
} catch (Exception e) {
e.printStackTrace();
}
return contactObj;
}
public static void setPhoneNumber(Cursor c, Contact contactObj, Context context) {
if (Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// Query phone here. Covered next
Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactObj.getID(), null, null);
phones.moveToFirst();
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i("Number", phoneNumber);
contactObj.setPhoneNumber(phoneNumber);
phones.close();
}
}
public static void setEmail(Contact contactObj, Context context) {
Cursor emailCur = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{contactObj.getID()}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
contactObj.setEmail(email);
}
emailCur.close();
}
}

Related

How to load albumArt using AsyncTask in cursor adapter

I have a problem with retrieving albumArt and setting that art to ImageView using AsyncTask in cursor adapter.
When I open my app it looks like this:
Then I scroll down the list and everything is fine(but also if I scroll list not very fast):
Then I scroll list back to the very beggining(not fast) and it looks fine as well:
Probably I do something wrong, I think, so I have question:
Is it possible somehow to solve that problem, I already tried a lot of different ways on how to implement AsyncTask and make it works fine, but in the end of the day it looks always the same.
Below is code for cursor adapter:
public class AllSongsCursorAdapter extends CursorAdapter {
public AllSongsCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
public boolean isCheckBoxVisible;
private AddToFavouritesArray favouritesArray = AddToFavouritesArray.getInstance();
private static class ViewHolder {
CheckBox checkBox;
TextView title;
TextView artist;
ImageView albumArt;
private ViewHolder(View view) {
checkBox = (CheckBox) view.findViewById(R.id.favouritesCheckBox);
title = (TextView) view.findViewById(R.id.title);
artist = (TextView) view.findViewById(R.id.artist);
albumArt = (ImageView) view.findViewById(R.id.albumArt);
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
View view = LayoutInflater.from(context).inflate(R.layout.song_item, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
return view;
}
#Override
public void bindView(View view, Context context, final Cursor cursor) {
final ViewHolder viewHolder = (ViewHolder) view.getTag();
if (isCheckBoxVisible) {
viewHolder.checkBox.setVisibility(View.VISIBLE);
} else {
viewHolder.checkBox.setVisibility(View.GONE);
}
final int position = cursor.getPosition();
viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
favouritesArray.integerArray.add(position);
} else {
favouritesArray.integerArray.remove(Integer.valueOf(position));
}
}
});
int songTitle = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
int songArtist = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
String currentTitle = cursor.getString(songTitle);
String currentArtist = cursor.getString(songArtist);
viewHolder.title.setText(currentTitle);
viewHolder.artist.setText(currentArtist);
//__________________________ALBUM_ART_______________________________________________________
viewHolder.albumArt.setTag(cursor.getPosition());
new AsyncTask<ViewHolder, Void, Bitmap>(){
private ViewHolder viewHolder;
#Override
protected Bitmap doInBackground(ViewHolder... viewHolders) {
viewHolder = viewHolders[0];
int id = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
long songId = cursor.getLong(id);
Bitmap albumArt = getAlbumId(context, songId);
return albumArt;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if(bitmap != null) {
viewHolder.albumArt.setImageBitmap(bitmap);
}else{
viewHolder.albumArt.setImageResource(R.drawable.placeholder);
}
}
}.execute(viewHolder);
}
private Bitmap getAlbumId(Context context, long id) {
Bitmap albumArt = null;
String selection = MediaStore.Audio.Media._ID + " = " + id + "";
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{
MediaStore.Audio.Media._ID, MediaStore.Audio.Media.ALBUM_ID},
selection, null, null);
if (cursor.moveToFirst()) {
long albumId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
albumArt = getAlbumArt(context, albumId);
}
cursor.close();
return albumArt;
}
private Bitmap getAlbumArt(Context context, long albumId) {
Bitmap albumArt = null;
String selection = MediaStore.Audio.Albums._ID + " = " + albumId + "";
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, null, selection, null, null);
if (cursor.moveToFirst()) {
int art = cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART);
String currentArt = cursor.getString(art);
albumArt = BitmapFactory.decodeFile(currentArt);
}
cursor.close();
return albumArt;
}
}
And yes, sure, without AsyncTask everything works fine except scrolling is very slow.
Thank you in advance!
EDIT
In the end of the day, that's how it works. Thank you very much # Orest Savchak, my up-vote and acceptance for your answer. Thanks a lot.
//__________________________ALBUM_ART_______________________________________________________
int id = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
long songId = cursor.getLong(id);
String string = getAlbumArtPath(context, songId);
if(string!=null) {
Picasso.with(context)
.load(new File(string))
.into(viewHolder.albumArt);
}else{
viewHolder.albumArt.setImageResource(R.drawable.placeholder);
}
}
private String getAlbumArtPath(Context context, long id) {
String selection = MediaStore.Audio.Media._ID + " = " + id + "";
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{
MediaStore.Audio.Media._ID, MediaStore.Audio.Media.ALBUM_ID},
selection, null, null);
if (cursor.moveToFirst()) {
long albumId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
return getAlbumArt(context, albumId);
}
cursor.close();
return null;
}
private String getAlbumArt(Context context, long albumId) {
String selection = MediaStore.Audio.Albums._ID + " = " + albumId + "";
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, null, selection, null, null);
if (cursor.moveToFirst()) {
int art = cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART);
return cursor.getString(art);
}
cursor.close();
return null;
}
You should manage your tasks by yourself. Your views are recycled, so, you have one view for different rows, it causes a problem. Most of project use some libraries, that do it automatically for you - much easier, e.g Picasso
Picasso.with(context).load(new File(getAlbumArtPath(context, songId))).into(viewHolder.albumArt);
private String getAlbumArtPath(Context context, long id) {
String selection = MediaStore.Audio.Media._ID + " = " + id + "";
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{
MediaStore.Audio.Media._ID, MediaStore.Audio.Media.ALBUM_ID},
selection, null, null);
if (cursor.moveToFirst()) {
long albumId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
return getAlbumArt(context, albumId);
}
cursor.close();
return null;
}
private String getAlbumArt(Context context, long albumId) {
String selection = MediaStore.Audio.Albums._ID + " = " + albumId + "";
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, null, selection, null, null);
if (cursor.moveToFirst()) {
int art = cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART);
return cursor.getString(art);
}
cursor.close();
return null;
}

How do I get the ID item in the database?

I am new to android development and must take the value of the id in the clicked item database.
Already searched several posts but not found the answer .
Below is my code Listview :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seleciona_jogador_act);
final BancoController bc = new BancoController(this);
final ArrayList<JogadorEntidade> jogadorEntidade = bc.arrayJogador(this);
listView = (ListView) findViewById(R.id.lvSelecionar);
final SelecionaAdapter adapter = new SelecionaAdapter(this, R.layout.adapter_seleciona, jogadorEntidade);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setBackgroundTintList(ColorStateList.valueOf(background));
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertInserirJogador(SelecionaJogadorAct.this);
}
});
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//I NEED THIS CODE
Context context = getApplicationContext();
CharSequence text = "ID: " + ", Posicao: " + position;
int duration = Toast.LENGTH_SHORT;
Toast.makeText(context, text, duration).show();
//bc.deletaRegistro(id_player);
Intent intent = getIntent();
SelecionaJogadorAct.this.finish();
startActivity(intent);
}
});
}
My Adapter:
public class SelecionaAdapter extends ArrayAdapter<JogadorEntidade> {
Context context;
int layoutID;
ArrayList<JogadorEntidade> alJogador;
public SelecionaAdapter(Context context, int layoutID, ArrayList<JogadorEntidade> alJogador){
super(context, layoutID, alJogador);
this.context = context;
this.alJogador = alJogador;
this.layoutID = layoutID;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View row = convertView;
PlayerHolder holder = null;
if (row == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutID, parent, false);
holder = new PlayerHolder();
holder.txtNome = (TextView)row.findViewById(R.id.txtNomeSelecionar);
holder.txtVitorias = (TextView)row.findViewById(R.id.txtVitóriasSelecionar);
holder.txtDerrotas = (TextView)row.findViewById(R.id.txtDerrotasSelecionar);
row.setTag(holder);
}else {
holder = (PlayerHolder)row.getTag();
}
JogadorEntidade jogadorEntidade = alJogador.get(position);
holder.txtNome.setText(jogadorEntidade.getNome());
holder.txtVitorias.setText("V: " + jogadorEntidade.vitórias);
holder.txtDerrotas.setText("D: " + jogadorEntidade.derrotas);
return row;
}
static class PlayerHolder{
TextView txtNome;
TextView txtVitorias;
TextView txtDerrotas;
}
JogadorEntidade:
public class JogadorEntidade {
public String nome;
public Integer id_jogador;
public String vitórias;
public String derrotas;
public Integer getId_jogador() {
return id_jogador;
}
public void setId_player(int id_player) {
this.id_jogador = id_player;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getVitórias() {
return vitórias;
}
public void setVitórias(String vitórias) {
this.vitórias = vitórias;
}
public String getDerrotas() {
return derrotas;
}
public void setDerrotas(String derrotas) {
this.derrotas = derrotas;
}
public JogadorEntidade(String nome, String vitórias, String derrotas){
super();
this.nome = nome;
this.vitórias = vitórias;
this.derrotas = derrotas;
}
public JogadorEntidade(){}
public void insereJogador(JogadorEntidade jogadorEntidade) {
db = banco.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(banco.NOME_JOGADOR, jogadorEntidade.getNome());
values.put(banco.VITORIAS, jogadorEntidade.getVitórias());
values.put(banco.DERROTAS, jogadorEntidade.getDerrotas());
db.insert(CriaBanco.TABELA_JOGADOR, null, values);
db.close();
}
public Cursor carregaJogador() {
Cursor cursor;
String[] campos = {banco.NOME_JOGADOR, banco.VITORIAS, banco.DERROTAS};
db = banco.getReadableDatabase();
cursor = db.query(banco.TABELA_JOGADOR, campos, null, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
db.close();
return cursor;
}
public void deletaRegistro(int id){
String where = CriaBanco.ID_JOGADOR + "=" + id;
db = banco.getReadableDatabase();
db.delete(CriaBanco.TABELA_JOGADOR, where, null);
db.close();
}
public ArrayList<JogadorEntidade> arrayJogador(Context context) {
ArrayList<JogadorEntidade> al = new ArrayList<JogadorEntidade>();
BancoController bancoController = new BancoController(context);
Cursor cursor;
cursor = bancoController.carregaJogador();
if (cursor != null) {
if (cursor.moveToFirst()) {
String nome = cursor.getString(cursor.getColumnIndex(banco.NOME_JOGADOR));
String vitorias = cursor.getString(cursor.getColumnIndex(banco.VITORIAS));
String derrotas = cursor.getString(cursor.getColumnIndex(banco.DERROTAS));
JogadorEntidade jogadorEntidade = new JogadorEntidade(nome, vitorias, derrotas);
al.add(jogadorEntidade);
while (cursor.moveToNext()) {
nome = cursor.getString(cursor.getColumnIndex(banco.NOME_JOGADOR));
vitorias = cursor.getString(cursor.getColumnIndex(banco.VITORIAS));
derrotas = cursor.getString(cursor.getColumnIndex(banco.DERROTAS));
jogadorEntidade = new JogadorEntidade(nome, vitorias, derrotas);
al.add(jogadorEntidade);
}
}
}
return al;
}
First you need to request the id when making the query (if the id is the one created in the database the column mame is _id or you can use tablename._id or whatever you need):
String[] campos = {"_id", banco.NOME_JOGADOR, banco.VITORIAS, banco.DERROTAS};
Then you need to add the id to the object when you read the cursor:
public ArrayList<JogadorEntidade> arrayJogador(Context context) {
ArrayList<JogadorEntidade> al = new ArrayList<JogadorEntidade>();
BancoController bancoController = new BancoController(context);
Cursor cursor;
cursor = bancoController.carregaJogador();
if (cursor != null) {
if (cursor.moveToFirst()) {
String nome = cursor.getString(cursor.getColumnIndex(banco.NOME_JOGADOR));
String vitorias = cursor.getString(cursor.getColumnIndex(banco.VITORIAS));
String derrotas = cursor.getString(cursor.getColumnIndex(banco.DERROTAS));
long id = cursor.getLong(cursor.getColumnIndex("_id",0));
JogadorEntidade jogadorEntidade = new JogadorEntidade(id, nome, vitorias, derrotas);
al.add(jogadorEntidade);
while (cursor.moveToNext()) {
nome = cursor.getString(cursor.getColumnIndex(banco.NOME_JOGADOR));
vitorias = cursor.getString(cursor.getColumnIndex(banco.VITORIAS));
derrotas = cursor.getString(cursor.getColumnIndex(banco.DERROTAS));
long id = cursor.getLong(cursor.getColumnIndex("_id",0));
jogadorEntidade = new JogadorEntidade(id, nome, vitorias, derrotas);
al.add(jogadorEntidade);
}
}
}
return al;
}
Anyway this is not the way to go in android. You should read all the list and then show it. You should use the viewholder pattern and only load the player when you are going to show it. Also instead of using a list you should move to recyclerviews. Listviews can be consider deprecated at this point. See the tutorial: http://developer.android.com/training/material/lists-cards.html

CursorAdapter with search string as either contact name or number

Hi I am developing an app to search a contact. The search string can be either a number or the contact name. I am able to search the list based on the contact name. Not sure how to search the same if the user enters the number of a contact. This is the code I am using
Cursor contacts = getContacts2(null);
startManagingCursor(contacts);
TestForCursorAdapter adapter = new TestForCursorAdapter(this, contacts);
mTxtPhoneNo.setAdapter(adapter);
mTxtPhoneNo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Cursor cursor = (Cursor) arg0.getItemAtPosition(arg2);
String number = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
mTxtPhoneNo.setText(number);
}
});
public Cursor getContacts2(String where)
{
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor people = this.getContentResolver().query(uri, projection, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
return people;
}
public class TestForCursorAdapter extends CursorAdapter implements Filterable
{
ImageView imageAvatar;
ContentResolver contentResolver;
LayoutInflater layoutInflater;
ArrayList<String> arrofnumberfrominbuiltsms = new ArrayList<String>();
ArrayList<String> arrofnumbettocomapreandbold = new ArrayList<String>();
String recipient_ids;
String r_address;
String contactName;
String contactID;
String bold= "false";
private String snippet;
private long timestamp;
private String dateString;
private String timeString;
String threadid;
private String phoneNumber;
private String numberType;
private ContentResolver mContext;
#SuppressWarnings("deprecation")
public TestForCursorAdapter(Context context, Cursor people)
{
super(context, people);
layoutInflater = LayoutInflater.from(context);
mContext = context.getContentResolver();
}
#Override
public View newView(Context context, Cursor people, ViewGroup parent)
{
final LayoutInflater mInflater = LayoutInflater.from(context);
final View ret = mInflater.inflate(R.layout.custcontview, null);
return ret;
}
#SuppressLint("SimpleDateFormat")
#Override
public void bindView(View vi, Context context, Cursor cursor)
{
TextView cname = (TextView)vi.findViewById(R.id.ccontName);
TextView cnumber = (TextView)vi.findViewById(R.id.ccontNo);
TextView ctype = (TextView)vi.findViewById(R.id.ccontType);
int nameIdx = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int typeIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
int numberIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String name = cursor.getString(nameIdx);
int type = cursor.getInt(typeIdx);
String number = cursor.getString(numberIdx);
cname.setText(name);
if (type == 1)
{
ctype.setText("Home");
}
else if (type == 2)
{
ctype.setText("Mobile");
}
else if (type == 3)
{
ctype.setText("Work");
}
else
{
ctype.setText("Other");
}
cnumber.setText(number);
}
#Override
public String convertToString(Cursor cursor)
{
int nameCol = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
String name = cursor.getString(nameCol);
return name;
}
#Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint)
{
// this is how you query for suggestions
// notice it is just a StringBuilder building the WHERE clause of a cursor which is the used to query for results
if (getFilterQueryProvider() != null)
{
return getFilterQueryProvider().runQuery(constraint);
}
String[] projection = new String[] {
ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.NUMBER};
if (( constraint).toString().matches("[0-9]+") && constraint.length() > 2)
{//This is what I want to try
return mContext.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection,
"UPPER(" + ContactsContract.CommonDataKinds.Phone.NUMBER + ") LIKE '" + constraint.toString().toUpperCase() + "%'", null,
ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
}
else
{
return mContext.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection,
"UPPER(" + ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + ") LIKE '" + constraint.toString().toUpperCase() + "%'", null,
ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
}
}
}
Please Help. Thanks
You just need to use
Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, searchString);
Android does a good job with lookup urls like this

android get all contacts

How can I get all the names of the contacts in my Android and put them into array of strings?
Try this too,
private void getContactList() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if ((cur != null ? cur.getCount() : 0) > 0) {
while (cur != null && cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
if (cur.getInt(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);
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i(TAG, "Name: " + name);
Log.i(TAG, "Phone Number: " + phoneNo);
}
pCur.close();
}
}
}
if(cur!=null){
cur.close();
}
}
If you need more reference means refer this link Read ContactList
Get contacts info , photo contacts , photo uri and convert to Class model
1). Sample for Class model :
public class ContactModel {
public String id;
public String name;
public String mobileNumber;
public Bitmap photo;
public Uri photoURI;
}
2). get Contacts and convert to Model
public List<ContactModel> getContacts(Context ctx) {
List<ContactModel> list = new ArrayList<>();
ContentResolver contentResolver = ctx.getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
if (cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor cursorInfo = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(ctx.getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id)));
Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id));
Uri pURI = Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
Bitmap photo = null;
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
}
while (cursorInfo.moveToNext()) {
ContactModel info = new ContactModel();
info.id = id;
info.name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
info.mobileNumber = cursorInfo.getString(cursorInfo.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
info.photo = photo;
info.photoURI= pURI;
list.add(info);
}
cursorInfo.close();
}
}
cursor.close();
}
return list;
}
public class MyActivity extends Activity
implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int CONTACTS_LOADER_ID = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(CONTACTS_LOADER_ID,
null,
this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// This is called when a new Loader needs to be created.
if (id == CONTACTS_LOADER_ID) {
return contactsLoader();
}
return null;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
//The framework will take care of closing the
// old cursor once we return.
List<String> contacts = contactsFromCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
}
private Loader<Cursor> contactsLoader() {
Uri contactsUri = ContactsContract.Contacts.CONTENT_URI; // The content URI of the phone contacts
String[] projection = { // The columns to return for each row
ContactsContract.Contacts.DISPLAY_NAME
} ;
String selection = null; //Selection criteria
String[] selectionArgs = {}; //Selection criteria
String sortOrder = null; //The sort order for the returned rows
return new CursorLoader(
getApplicationContext(),
contactsUri,
projection,
selection,
selectionArgs,
sortOrder);
}
private List<String> contactsFromCursor(Cursor cursor) {
List<String> contacts = new ArrayList<String>();
if (cursor.getCount() > 0) {
cursor.moveToFirst();
do {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
contacts.add(name);
} while (cursor.moveToNext());
}
return contacts;
}
}
and do not forget
<uses-permission android:name="android.permission.READ_CONTACTS" />
Get all contacts in less than a second and without any load in your activity.
Follow my steps works like a charm.
ArrayList<Contact> contactList = new ArrayList<>();
private static final String[] PROJECTION = new String[]{
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
private void getContactList() {
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor != null) {
HashSet<String> mobileNoSet = new HashSet<String>();
try {
final int nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
final int numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String name, number;
while (cursor.moveToNext()) {
name = cursor.getString(nameIndex);
number = cursor.getString(numberIndex);
number = number.replace(" ", "");
if (!mobileNoSet.contains(number)) {
contactList.add(new Contact(name, number));
mobileNoSet.add(number);
Log.d("hvy", "onCreaterrView Phone Number: name = " + name
+ " No = " + number);
}
}
} finally {
cursor.close();
}
}
}
Contacts
public class Contact {
public String name;
public String phoneNumber;
public Contact() {
}
public Contact(String name, String phoneNumber ) {
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
Benefits
less than a second
without load
ascending order
without duplicate contacts
Improving on the answer of #Adiii - It Will Cleanup The Phone Number and Remove All Duplicates
Declare a Global Variable
// Hash Maps
Map<String, String> namePhoneMap = new HashMap<String, String>();
Then Use The Function Below
private void getPhoneNumbers() {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
// Loop Through All The Numbers
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Cleanup the phone number
phoneNumber = phoneNumber.replaceAll("[()\\s-]+", "");
// Enter Into Hash Map
namePhoneMap.put(phoneNumber, name);
}
// Get The Contents of Hash Map in Log
for (Map.Entry<String, String> entry : namePhoneMap.entrySet()) {
String key = entry.getKey();
Log.d(TAG, "Phone :" + key);
String value = entry.getValue();
Log.d(TAG, "Name :" + value);
}
phones.close();
}
Remember in the above example the key is phone number and value is a name so read your contents like 998xxxxx282->Mahatma Gandhi instead of Mahatma Gandhi->998xxxxx282
Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
String aNameFromContacts[] = new String[contacts.getCount()];
String aNumberFromContacts[] = new String[contacts.getCount()];
int i = 0;
int nameFieldColumnIndex = contacts.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int numberFieldColumnIndex = contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
while(contacts.moveToNext()) {
String contactName = contacts.getString(nameFieldColumnIndex);
aNameFromContacts[i] = contactName ;
String number = contacts.getString(numberFieldColumnIndex);
aNumberFromContacts[i] = number ;
i++;
}
contacts.close();
The result will be aNameFromContacts array full of contacts. Also ensure that you have added
<uses-permission android:name="android.permission.READ_CONTACTS" />
in main.xml
This is the Method to get contact list Name and Number
private void getAllContacts() {
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id},
null);
if (phoneCursor != null) {
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//At here You can add phoneNUmber and Name to you listView ,ModelClass,Recyclerview
phoneCursor.close();
}
}
}
}
}
}
//GET CONTACTLIST WITH ALL FIELD...
public ArrayList < ContactItem > getReadContacts() {
ArrayList < ContactItem > contactList = new ArrayList < > ();
ContentResolver cr = getContentResolver();
Cursor mainCursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (mainCursor != null) {
while (mainCursor.moveToNext()) {
ContactItem contactItem = new ContactItem();
String id = mainCursor.getString(mainCursor.getColumnIndex(ContactsContract.Contacts._ID));
String displayName = mainCursor.getString(mainCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(id));
Uri displayPhotoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
//ADD NAME AND CONTACT PHOTO DATA...
contactItem.setDisplayName(displayName);
contactItem.setPhotoUrl(displayPhotoUri.toString());
if (Integer.parseInt(mainCursor.getString(mainCursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//ADD PHONE DATA...
ArrayList < PhoneContact > arrayListPhone = new ArrayList < > ();
Cursor phoneCursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] {
id
}, null);
if (phoneCursor != null) {
while (phoneCursor.moveToNext()) {
PhoneContact phoneContact = new PhoneContact();
String phone = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneContact.setPhone(phone);
arrayListPhone.add(phoneContact);
}
}
if (phoneCursor != null) {
phoneCursor.close();
}
contactItem.setArrayListPhone(arrayListPhone);
//ADD E-MAIL DATA...
ArrayList < EmailContact > arrayListEmail = new ArrayList < > ();
Cursor emailCursor = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] {
id
}, null);
if (emailCursor != null) {
while (emailCursor.moveToNext()) {
EmailContact emailContact = new EmailContact();
String email = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
emailContact.setEmail(email);
arrayListEmail.add(emailContact);
}
}
if (emailCursor != null) {
emailCursor.close();
}
contactItem.setArrayListEmail(arrayListEmail);
//ADD ADDRESS DATA...
ArrayList < PostalAddress > arrayListAddress = new ArrayList < > ();
Cursor addrCursor = getContentResolver().query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, null, ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = ?", new String[] {
id
}, null);
if (addrCursor != null) {
while (addrCursor.moveToNext()) {
PostalAddress postalAddress = new PostalAddress();
String city = addrCursor.getString(addrCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
String state = addrCursor.getString(addrCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
String country = addrCursor.getString(addrCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
postalAddress.setCity(city);
postalAddress.setState(state);
postalAddress.setCountry(country);
arrayListAddress.add(postalAddress);
}
}
if (addrCursor != null) {
addrCursor.close();
}
contactItem.setArrayListAddress(arrayListAddress);
}
contactList.add(contactItem);
}
}
if (mainCursor != null) {
mainCursor.close();
}
return contactList;
}
//MODEL...
public class ContactItem {
private String displayName;
private String photoUrl;
private ArrayList<PhoneContact> arrayListPhone = new ArrayList<>();
private ArrayList<EmailContact> arrayListEmail = new ArrayList<>();
private ArrayList<PostalAddress> arrayListAddress = new ArrayList<>();
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
public ArrayList<PhoneContact> getArrayListPhone() {
return arrayListPhone;
}
public void setArrayListPhone(ArrayList<PhoneContact> arrayListPhone) {
this.arrayListPhone = arrayListPhone;
}
public ArrayList<EmailContact> getArrayListEmail() {
return arrayListEmail;
}
public void setArrayListEmail(ArrayList<EmailContact> arrayListEmail) {
this.arrayListEmail = arrayListEmail;
}
public ArrayList<PostalAddress> getArrayListAddress() {
return arrayListAddress;
}
public void setArrayListAddress(ArrayList<PostalAddress> arrayListAddress) {
this.arrayListAddress = arrayListAddress;
}
}
public class EmailContact
{
private String email = "";
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
public class PhoneContact
{
private String phone="";
public String getPhone()
{
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
public class PostalAddress
{
private String city="";
private String state="";
private String country="";
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
//In Kotlin
private fun showContacts() {
// Check the SDK version and whether the permission is already granted or not.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(
requireContext(),
Manifest.permission.READ_CONTACTS
) != PackageManager.PERMISSION_GRANTED
) {
requestPermissions(
arrayOf(Manifest.permission.READ_CONTACTS),
1001
)
//After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method
} else {
// Android version is lesser than 6.0 or the permission is already granted.
getContactList()
}
}
private fun getContactList() {
val cr: ContentResolver = requireActivity().contentResolver
val cur: Cursor? = cr.query(
ContactsContract.Contacts.CONTENT_URI,
null, null, null, null
)
if ((if (cur != null) cur.getCount() else 0) > 0) {
while (cur != null && cur.moveToNext()) {
val id: String = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID)
)
val name: String = cur.getString(
cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME
)
)
if (cur.getInt(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
val pCur: Cursor? = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
arrayOf(id),
null
)
pCur?.let {
while (pCur.moveToNext()) {
val phoneNo: String = pCur.getString(
pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER
)
)
Timber.i("Name: $name")
Timber.i("Phone Number: $phoneNo")
}
pCur.close()
}
}
}
}
if (cur != null) {
cur.close()
}
}
I am using this method, and it is working perfectly.
It gets fav, picture, name, number etc. (All the details of the contact). And also it is not repetitive.
List
private static List<FavContact> contactList = new ArrayList<>();
Method to get contacts
#SuppressLint("Range")
public static void readContacts(Context context) {
if (context == null)
return;
ContentResolver contentResolver = context.getContentResolver();
if (contentResolver == null)
return;
String[] fieldListProjection = {
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
ContactsContract.Contacts.PHOTO_URI
,ContactsContract.Contacts.STARRED
};
String sort = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY + " ASC";
Cursor phones = contentResolver
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI
, fieldListProjection, null, null, sort);
HashSet<String> normalizedNumbersAlreadyFound = new HashSet<>();
if (phones != null && phones.getCount() > 0) {
while (phones.moveToNext()) {
String normalizedNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if (Integer.parseInt(phones.getString(phones.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
if (normalizedNumbersAlreadyFound.add(normalizedNumber)) {
int id = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
int fav = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.STARRED));
boolean isFav;
isFav= fav == 1;
String uri = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
if(uri!=null){
contactList.add(new FavContact(id,isFav,uri,name,phoneNumber));
}
else{
contactList.add(new FavContact(id,isFav,name,phoneNumber));
}
}
}
}
phones.close();
}
}
Model Class
public class FavContact{
private int id;
private boolean isFavorite;
private String image;
private String name;
private String number;
public FavContact(int id,boolean isFavorite, String image, String name, String number){
this.id=id;
this.isFavorite = isFavorite;
this.image = image;
this.name = name;
this.number = number;
}
public FavContact(int id,boolean isFavorite, String name, String number){
this.id=id;
this.isFavorite = isFavorite;
this.name = name;
this.number = number;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isFavorite() {
return isFavorite;
}
public void setFavorite(boolean favorite) {
isFavorite = favorite;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
Adapter
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.MyViewHolder> implements Filterable {
private final Context context;
private final List<FavContact> contactList;
private final List<FavContact> filterList;
private final OnMyOwnClickListener onMyOwnClickListener;
private final FavContactRepo favContactRepo;
public ContactAdapter(Application application,Context context, List<FavContact> contactList, OnMyOwnClickListener onMyOwnClickListener) {
this.context = context;
this.contactList = contactList;
this.onMyOwnClickListener = onMyOwnClickListener;
filterList = new ArrayList<>(contactList);
favContactRepo = new FavContactRepo(application);
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
final LayoutInflater inflater = LayoutInflater.from(context);
#SuppressLint("InflateParams") final View view = inflater.inflate(R.layout.design_fav_contact, null, false);
return new MyViewHolder(view,onMyOwnClickListener);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
final FavContact obj = contactList.get(position);
holder.tv_contact_name.setText(obj.getName());
holder.tv_contact_number.setText(obj.getNumber());
if(obj.getImage()==null){
Picasso.get().load(R.drawable.ic_circle_fav_no_dp).fit().into(holder.img_contact);
}
else{
Bitmap bp;
try {
bp = MediaStore.Images.Media
.getBitmap(context.getContentResolver(),
Uri.parse(obj.getImage()));
Glide.with(context).load(bp).centerInside().into(holder.img_contact);
} catch (IOException e) {
e.printStackTrace();
Picasso.get().load(R.drawable.ic_circle_fav_no_dp).fit().into(holder.img_contact);
}
}
obj.setFavorite(favContactRepo.checkIfFavourite(obj.getId()));
if(obj.isFavorite()){
Picasso.get().load(R.drawable.ic_menu_favorite_true).into(holder.img_fav_true_or_not);
}
else{
Picasso.get().load(R.drawable.ic_menu_favorite_false).into(holder.img_fav_true_or_not);
}
}
#Override
public int getItemCount() {
return contactList.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CircleImageView img_contact;
TextView tv_contact_name,tv_contact_number;
ImageView img_fav_true_or_not;
ImageView img_call;
RecyclerView fav_contact_rv;
OnMyOwnClickListener onMyOwnClickListener;
public MyViewHolder(#NonNull View itemView, OnMyOwnClickListener onMyOwnClickListener) {
super(itemView);
img_contact = itemView.findViewById(R.id.img_contact);
tv_contact_name = itemView.findViewById(R.id.tv_contact_name);
img_fav_true_or_not = itemView.findViewById(R.id.img_fav_true_or_not);
tv_contact_number = itemView.findViewById(R.id.tv_contact_number);
img_call = itemView.findViewById(R.id.img_call);
fav_contact_rv = itemView.findViewById(R.id.fav_contact_rv);
this.onMyOwnClickListener = onMyOwnClickListener;
img_call.setOnClickListener(this);
img_fav_true_or_not.setOnClickListener(this);
img_contact.setOnClickListener(this);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
onMyOwnClickListener.onMyOwnClick(getAbsoluteAdapterPosition(),view);
}
}
public interface OnMyOwnClickListener{
void onMyOwnClick(int position,View view);
}
#Override
public Filter getFilter() {
return filteredList;
}
public Filter filteredList = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<FavContact> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList=filterList;
} else {
String filterText = constraint.toString().toLowerCase().trim();
for (FavContact item : filterList) {
if (item.getName().toLowerCase().contains(filterText)
||item.getNumber().toLowerCase().contains(filterText)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#SuppressLint("NotifyDataSetChanged")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
contactList.clear();
contactList.addAll((ArrayList)results.values);
notifyDataSetChanged();
}
};

Show Contacts on ListView Android

I want to get conctacts on a listView and I want too reutilitzate one code of SocialAuth.
In this code i can get ContactList on the LogCat but not in the listView and I don't know how to do this. This listView is on other XML.
I'm goggling and more but I don't Know how to adapt the code
public void Events(String provider) {
setContentView(R.layout.contact_list);
List < Contact > contactsList = adapter.getContactList();
if (contactsList != null && contactsList.size() > 0) {
for (Contact p: contactsList) {
if (TextUtils.isEmpty(p.getFirstName()) && TextUtils.isEmpty(p.getLastName())) {
p.setFirstName(p.getDisplayName());
}
Log.d("Custom-UI", "Display Name = " + p.getDisplayName());
String ContactNAme = p.getDisplayName();
//ContactName = new String[] {p.getDisplayName()};
//mapTo = new int[] {android.R.id.text1};
Log.d("Custom-UI", "First Name = " + p.getFirstName());
String ContactFisrtName = p.getFirstName();
Log.d("Custom-UI", "Last Name = " + p.getLastName());
String ContactLastName = p.getLastName();
Log.d("Custom-UI", "Contact ID = " + p.getId());
String ContactId = p.getId();
Log.d("Custom-UI", "Profile URL = " + p.getProfileUrl());
String ContactProfileUrl = p.getProfileUrl();
}
// Log.d("ContactList",mAdapter.toString());
}
Toast.makeText(CustomUI.this, "View Logcat for Contacts Information", Toast.LENGTH_SHORT).show();
}
I think that the problem is the cursor because I don't have anyone, I have this function that I think that works likes cursor
public List<Contact> getContactList()
{
try
{
contactsList = new contactTask().execute().get();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (ExecutionException e)
{
e.printStackTrace();
}
return contactsList;
}
So if someone can help me please, Thanks so much.
Please have a look at the below link
http://developer.android.com/tools/samples/index.html
This is having the sample example in Android SDK. where you can get the desired result.
You need to write a custom adapter for you list view.
here is a good example
http://android.vexedlogic.com/2011/04/02/android-lists-listactivity-and-listview-ii-%E2%80%93-custom-adapter-and-list-item-view/
// Call contact thread
contact_thread = new Contact_thread();
contact_thread.start();
private Cursor getContacts() {
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, null, selectionArgs, sortOrder);
}
class Contact_thread extends Thread {
#Override
public void run() {
// TODO Auto-generated method stub
// Build adapter with contact entries
Cursor cursor = getContacts();
cursor.moveToFirst();
contactName = new String[cursor.getCount()];
contactNo = new String[cursor.getCount()];
checkedPosition = new boolean[cursor.getCount()];
ContentResolver contect_resolver = getContentResolver();
int i = 0;
if (cursor.getCount() > 0) {
do {
String id = cursor
.getString(cursor
.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
Cursor phoneCur = contect_resolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
if (phoneCur.moveToFirst()) {
contactName[i] = phoneCur
.getString(phoneCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
contactNo[i] = phoneCur
.getString(phoneCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (contactName[i] == null) {
contactName[i] = "Unknown";
}
} else {
contactName[i] = "Unknown";
contactNo[i] = "";
}
db.AddContact(contactName[i], contactNo[i]);
i++;
phoneCur.close();
} while (cursor.moveToNext());
}
cursor.close();
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// mContactList.setAdapter(cursorAdapter);
mContactList.setAdapter(new ContactAdapter(
ContactManager.this, R.layout.contact_entry));
}
});
}
}
private class ContactAdapter extends ArrayAdapter<String> implements
Filterable {
public ContactAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}
public int getCount() {
return contactName.length;
}
public String getItem(int position) {
return contactName[position];
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v;
if (convertView == null) {
LayoutInflater li = getLayoutInflater();
v = li.inflate(R.layout.contact_entry, null);
} else {
v = convertView;
}
CheckedTextView text = (CheckedTextView) v.findViewById(R.id.text1);
text.setText(contactName[position] + " (" + contactNo[position]
+ ") ");
text.setChecked(checkedPosition[position]);
return v;
}
}
contact_entry.xml
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/text1"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:background="#AA0114"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:gravity="center_vertical"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />

Categories

Resources