The Group is created and contacts are added in batches. The test is successful on Samsung S2.

Source: Internet
Author: User
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;@Overridepublic 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;}@Overridepublic 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;    }} 

 

Another class

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;}} 

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>

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>

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.