Android multiple contacts from groups and images

596 views Asked by At

I want to do the following. Pick up three to five contacts out of a special group of contacts or all contacts. In the list it would be nice to show the contact image. The selected contacts should have the following information (contact-id, first name, the small version of the contact image to save it as a blob in the database)

I found solutions for the different aspects. -select multiple contacts: How to obtain the checked rows in a custom view list -show contacts from one group getting contacts from a specified group in android - photo problem Getting a Photo from a Contact

But I dont know how to put those together. It would be great if someone could help me putting it together.

Thank you very much! Frank J.

Solved it, but cant post the answer for some hours.

1

There are 1 answers

0
Frank J. On BEST ANSWER

Solution (not prettyfied yet)

    package com.pinkpony.frankj.contactpicker2;


import android.app.Activity;
import android.content.ClipData;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
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.ViewGroup;
import android.widget.AdapterView;
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;

import java.util.List;

import java.util.ArrayList;
import java.util.Map;


/**
 * Created by Frank on 28.07.2014.
 */
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {


    List<String> name1 = new ArrayList<String>();
    List<String> name2 = new ArrayList<String>();
    List<String> phno1 = new ArrayList<String>();
    List<String> img1 = new ArrayList<String>();
    MyAdapter ma ;
    Button select;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_main);
        loadGroups();

        //Toast.makeText(MainActivity.this, toString(), Toast.LENGTH_LONG).show();
        Log.d("LongValue", toString());
        getAllCallLogs(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 View.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(getApplicationContext(), checkedcontacts, 1000).show();

                Toast.makeText(MainActivity.this, checkedcontacts, Toast.LENGTH_SHORT).show();
            }
        });



    }


    @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) {

       /* Uri uri = ContactsContract.Contacts.CONTENT_URI;
        String[] projection = new String[] { ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME };
        String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
                + ("1") + "'";
        String[] selectionArgs = null;
        String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
                + " COLLATE LOCALIZED ASC";

        Cursor phones = cr.query(uri, projection, selection, selectionArgs,
                sortOrder);
*/
      //  long groupId = id;
        String[] cProjection = { ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID };

        Cursor groupCursor = getContentResolver().query(
                ContactsContract.Data.CONTENT_URI,
                cProjection,
                ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "= ?" + " AND "
                        + ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE + "='"
                        + ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'",
                new String[] { String.valueOf(6) }, null);
        if (groupCursor != null && groupCursor.moveToFirst())
        {
            do
            {

                int nameCoumnIndex = groupCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);

                String name = groupCursor.getString(nameCoumnIndex);
                String szFullname=name;
                //long contactId = groupCursor.getLong(groupCursor.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID));
                long contactId = groupCursor.getLong(groupCursor.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID));
               // Log.d("your tag", "contact " + name + ":"+String.valueOf(contactId));
                name1.add(name);
                phno1.add(String.valueOf(contactId));
                boolean foundToken = false;
// IDENTIFY Contact based on name and token
                String szLookupKey = "";
                Uri lkup = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, szFullname);
                ContentResolver cr2 = getContentResolver();
                Cursor idCursor = getContentResolver().query(lkup, null, null, null, null);
// get all the names
                while (idCursor.moveToNext()) {
// get current row/contact ID = ID's are unreliable, so we will go for the lookup key
                    String szId = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts._ID));
                    String szName = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    szLookupKey = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
// for this contact ID, search the custom field
                    Log.d("", "Searching token:" + szId + " Name:" + szName + " LookupKey:" + szLookupKey);
//Log.d(LOG_TAG, "search: "+lid + " key: "+key + " name: "+name);
                }
                String whereName = ContactsContract.Data.MIMETYPE + " = ? AND " + ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID + " = ?";
                String[] whereNameParams = new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE, String.valueOf(contactId) };
                Cursor nameCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
                while (nameCur.moveToNext()) {
                    String given = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
                    String family = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
                    String display = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
                    Log.d("your tag", "Vorname " +  ":" + given);
                    name2.add(given);
                }
                nameCur.close();





            } while (groupCursor.moveToNext());
            groupCursor.close();
        }


    }
    class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
    {  private SparseBooleanArray mCheckStates;
        LayoutInflater mInflater;
        TextView tv1,tv;
        ImageView im1;
        CheckBox cb;
        MyAdapter()
        {
            mCheckStates = new SparseBooleanArray(name1.size());
            mInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        private void retrieveContactPhoto(Long contactID) {

            Bitmap photo = null;

            try {
                InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
                        ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(contactID)));

                if (inputStream != null) {
                    photo = BitmapFactory.decodeStream(inputStream);
                    ImageView imageView = (ImageView) findViewById(R.id.imageView1);
                    imageView.setImageBitmap(photo);
                }

                assert inputStream != null;
                inputStream.close();

            } catch (IOException e) {
                e.printStackTrace();
            }

        }


        @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;
        }
        public Bitmap openPhoto(long contactId) {
            Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
            Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
            Cursor cursor = getContentResolver().query(photoUri,
                    new String[] {ContactsContract.Contacts.Photo.PHOTO}, null, null, null);
            if (cursor == null) {
                return null;
            }
            try {
                if (cursor.moveToFirst()) {
                    byte[] data = cursor.getBlob(0);
                    if (data != null) {
                        return BitmapFactory.decodeStream(new ByteArrayInputStream(data));
                    }
                }
            } finally {
                cursor.close();
            }
            return null;

        }
        @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);
            im1= (ImageView) vi.findViewById(R.id.imageView1);
            Bitmap photo = null;
            Long contactID=Long.valueOf(phno1.get(position));
            im1.setImageBitmap(openPhoto(contactID));
            cb = (CheckBox) vi.findViewById(R.id.checkBox1);
            tv.setText(""+ name1.get(position));
       //     tv1.setText(""+phno1.get(position));//
           // retrieveContactPhoto(Long.valueOf(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);

        }

    }



   private class GroupInfo {
       String id;
       String title;

       @Override
       public String toString() {
           return title+ " ("+id+")";
       }

       public String getId() {
           return id;
       }
   }

    List<GroupInfo> groups = new ArrayList<GroupInfo>();

    public void loadGroups() {
        final String[] GROUP_PROJECTION = new String[] {
                ContactsContract.Groups._ID,
                ContactsContract.Groups.TITLE,
                ContactsContract.Groups.SUMMARY_WITH_PHONES
        };

        Cursor c = getContentResolver().query(
                ContactsContract.Groups.CONTENT_SUMMARY_URI,
                GROUP_PROJECTION,
                ContactsContract.Groups.DELETED+"!='1' AND "+
                        ContactsContract.Groups.GROUP_VISIBLE+"!='0' "
                ,
                null,
                null);
        final int IDX_ID = c.getColumnIndex(ContactsContract.Groups._ID);
        final int IDX_TITLE = c.getColumnIndex(ContactsContract.Groups.TITLE);

        Map<String,GroupInfo> m = new HashMap<String, GroupInfo>();

        while (c.moveToNext()) {
            GroupInfo g = new GroupInfo();
            g.id = c.getString(IDX_ID);
            g.title = c.getString(IDX_TITLE);

            int users = c.getInt(c.getColumnIndex(ContactsContract.Groups.SUMMARY_WITH_PHONES));
            if (users>0) {
                // group with duplicate name?
                GroupInfo g2 = m.get(g.title);
                if (g2==null) {
                    m.put(g.title, g);
                    groups.add(g);
                } else {
                    g2.id+=","+g.id;
                }
            }
            Log.d("LongValue", g.id+g.title);
        }
        c.close();
    }

}