开发者

How can I create a contact group programmatically in Android?

I want to create a contact group, give it a particular name and then add contacts to it.

I can make contacts by using RawContacts class but I do not kno开发者_JAVA技巧w how to

  1. create a contact group
  2. and then add contacts to that particular group.

Can someone please help me out with some sample code?


Please use this Code. It will help some one.

  package com.example.new_group_and_add_contacts;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {    
ListView listView = null;       
EditText editText = null;
Cursor cursor = null;       
Context context = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main); 

    context = this;
    listView =(ListView) findViewById(R.id.mylist);  
    editText = (EditText) findViewById(R.id.textview);

    try {   
 // Create an array of Strings, for List
    ArrayAdapter<Model> adapter = new InteractiveArrayAdapter(this,getModel());       

    // Assign adapter to ListView
    listView.setAdapter(adapter);

    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
            Toast.makeText(getApplicationContext(),
                "Click ListItem Number " + position, Toast.LENGTH_LONG)
                .show();
        }       
    });

    } catch(Exception e) {
        Log.d("**** Exception: ",e.getMessage());
    }        
}

private List<Model> getModel() {
    List<Model> list = new ArrayList<Model>();

    try {
        ContentResolver cr = getContentResolver();
        cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, null, null,  ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");

        cursor.moveToFirst();
                                if (cursor.moveToFirst()) {
                                    do {
                                        String name = cursor.getString(cursor.getColumnIndex    (ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                                        String number = cursor.getString(cursor.getColumnIndex  (ContactsContract.CommonDataKinds.Phone.NUMBER));
                                        String s = name + "\n" + number;
                                        list.add(get(s));
                                        s = null;
                                    } while (cursor.moveToNext());
                                } 
    } catch(Exception e){
        Log.d("???????? Error in Contacts Read: ",""+e.getMessage());
    }

    return list;
}

private Model get(String s) {
    return new Model(s);
}


public void onClick(View v) {
    switch(v.getId())
    {
    case R.id.mybutton:             
        String s="";
        for(int i=0; i<InteractiveArrayAdapter.list.size(); i++)  {
            if(InteractiveArrayAdapter.list.get(i).isSelected()) {
                s = s+i+" ";
            }
        }
        String s1 = null; 
        s1 = editText.getText().toString();

        // Check the edittext is empty or not
        if(s1.equals("")){
            Toast.makeText(MainActivity.this, "Please Enter Any Text", Toast.LENGTH_SHORT).show();
            return;
        }


        // Check the Group is available or not
                    Cursor groupCursor = null;
                    String[] GROUP_PROJECTION = new String[] { ContactsContract.Groups._ID,     ContactsContract.Groups.TITLE };
                    groupCursor = this.managedQuery(ContactsContract.Groups.CONTENT_URI,    GROUP_PROJECTION, ContactsContract.Groups.TITLE+ "=?", new String[]{s1}, ContactsContract.Groups.TITLE + " ASC");
                    Log.d("*** Here Counts: ","** "+groupCursor.getCount());

                    if(groupCursor.getCount() > 0){
                        Toast.makeText(MainActivity.this, "Group is already available",     Toast.LENGTH_SHORT).show();
                        return;
                    }
                    else {
                        Toast.makeText(MainActivity.this, "Not available", Toast.LENGTH_SHORT).show();

      //Here we create a new Group
                        try {
                            ContentValues groupValues = null;
                            ContentResolver cr = this.getContentResolver();
                            groupValues = new ContentValues();
                            groupValues.put(ContactsContract.Groups.TITLE, s1);
                            cr.insert(ContactsContract.Groups.CONTENT_URI, groupValues);
                            Log.d("########### Group Creation Finished :","###### Success");    
                        }
                        catch(Exception e){
                            Log.d("########### Exception :",""+e.getMessage()); 
                        }
                        Toast.makeText(MainActivity.this, "Created Successfully",                                       Toast.LENGTH_SHORT).show();
                    }

                    groupCursor.close();
                    groupCursor = null;



                    Log.d(" **** Contacts add to Groups...","**** Fine");

                    String groupID = null;
                    Cursor getGroupID_Cursor = null;
                    getGroupID_Cursor = this.managedQuery(ContactsContract.Groups.CONTENT_URI,  GROUP_PROJECTION, ContactsContract.Groups.TITLE+ "=?", new String[]{s1}, null);
                    Log.d("**** Now Empty Cursor size:","** "+getGroupID_Cursor.getCount());
                    getGroupID_Cursor.moveToFirst();
                    groupID = (getGroupID_Cursor.getString(getGroupID_Cursor.getColumnIndex("_id")));
                    Log.d(" **** Group ID is: ","** "+groupID);

                    getGroupID_Cursor.close();
                    getGroupID_Cursor = null;


                    for(int i=0; i<InteractiveArrayAdapter.list.size(); i++)  {
                        if(InteractiveArrayAdapter.list.get(i).isSelected()) {
                            cursor.moveToPosition(i);
                            String contactID = cursor.getString(cursor.getColumnIndex   (ContactsContract.CommonDataKinds.Phone.CONTACT_ID));

                            long contact = Long.parseLong(contactID);
                            long group = Long.parseLong(groupID);

                            addToGroup(contact, group);

                            String name = cursor.getString(cursor.getColumnIndex    (ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                            Log.d(" **** Contact Added: ","* :"+name);
                            Toast.makeText(MainActivity.this, name+" Added Successfully",   Toast.LENGTH_SHORT).show();
                        }
                    }



        break;              
    }       
}   



public Uri addToGroup(long personId, long groupId) {

    ContentValues values = new ContentValues();
    values.put(ContactsContract.CommonDataKinds.GroupMembership.RAW_CONTACT_ID,
            personId);
    values.put(
            ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID,
            groupId);
    values
            .put(
                    ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE,
                    ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE);

    return this.context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);

}



}

Another Two classes for ListView Control.

package com.example.new_group_and_add_contacts;

import java.util.List;
import android.app.Activity;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

public class InteractiveArrayAdapter extends ArrayAdapter<Model> {

public static List<Model> list = null;
private final Activity context; 


public InteractiveArrayAdapter(Activity context, List<Model> list) {
    super(context, R.layout.rowbuttonlayout, list);
    this.context = context;
    this.list = list;
}

static class ViewHolder {
    protected TextView text;
    protected CheckBox checkbox;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = null;


    if (convertView == null) {
        LayoutInflater inflator = context.getLayoutInflater();
        view = inflator.inflate(R.layout.rowbuttonlayout, null);
        final ViewHolder viewHolder = new ViewHolder();
        viewHolder.text = (TextView) view.findViewById(R.id.label);     
        viewHolder.text.setText("Select Ringtone");         


        viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);         
        viewHolder.checkbox
                .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,
                            boolean isChecked) {
                        Model element = (Model) viewHolder.checkbox
                                .getTag();
                        element.setSelected(buttonView.isChecked());                            
                    }
                });


        view.setTag(viewHolder);
        viewHolder.checkbox.setTag(list.get(position));
    } else {
        view = convertView;
        ((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
    }


    ViewHolder holder = (ViewHolder) view.getTag();
    holder.text.setText(list.get(position).getName());

    holder.checkbox.setChecked(list.get(position).isSelected());


    return view;
    }
} 

And

package com.example.new_group_and_add_contacts;

public class Model {

private String name;
private boolean selected;

public Model(String name) {
    this.name = name;
    selected = false;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public boolean isSelected() {
    return selected;
}

public void setSelected(boolean selected) {
    this.selected = selected;
}

} 

And XML Files are, This xml file name is main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" 
android:id="@+id/layoutexample"
android:background="#000000"
>

<EditText
    android:id="@+id/textview"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:hint="Enter Group Name"
    android:textColor="#000000"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="10dp"
    />


<ListView
    android:id="@+id/mylist"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:layout_weight="1"
    android:background="#552244"
    android:cacheColorHint="#00000000"
    android:layout_margin="10dp"
    >
</ListView>

<Button 
     android:id="@+id/mybutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:text="Create New Group"
    android:onClick="onClick"
    android:layout_gravity="center_horizontal"
    android:textColor="#000000"
    />



</LinearLayout>

Another XML file for ListView, Name is rowbuttonlayout.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" 
android:orientation="horizontal"
>

<CheckBox
    android:id="@+id/check"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</CheckBox>



<TextView
    android:id="@+id/label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello"
    android:textSize="15dp"
    android:textColor="#FF0000"         
    >
</TextView>

</LinearLayout> 

This Code is working in Andoid2.2 onwards mobiles.


Groups are not part of the contacts app / content provider / Google contacts sync adapter on Android, but you will need to use the Google Contacts API directly, see http://code.google.com/apis/contacts/docs/3.0/developers_guide_protocol.html#CreatingGroups


try this code

private void getGroupId(String groupname, String acc_name) {
        ArrayList<ContentProviderOperation> opsGroup = new ArrayList<ContentProviderOperation>();
        opsGroup.add(ContentProviderOperation.newInsert(ContactsContract.Groups.CONTENT_URI)
                .withValue(ContactsContract.Groups.TITLE, groupname)
                .withValue(ContactsContract.Groups.GROUP_VISIBLE, true)
                .withValue(ContactsContract.Groups.ACCOUNT_NAME, acc_name)
                .withValue(ContactsContract.Groups.ACCOUNT_TYPE, SharedPrefs.getString(this,"AccountType"))
                .build());
        try {
            getContentResolver().applyBatch(ContactsContract.AUTHORITY, opsGroup);
            Toast.makeText(ProspectsActivity.this, "successfully, Group is created", Toast.LENGTH_SHORT).show();
            Log.e("TAG", "successfully, Group is created");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜