Create gmail contact group in android - android

In my android application i have try to create a gmail group but not able to create
the way i have tried is below
ArrayList<ContentProviderOperation> opsGroup = new ArrayList<ContentProviderOperation>();
opsGroup.add(ContentProviderOperation
.newInsert(ContactsContract.Groups.CONTENT_URI)
.withValue(ContactsContract.Groups.TITLE, GroupTitle)
.withValue(ContactsContract.Groups.GROUP_VISIBLE, 1)
.withValue(ContactsContract.Groups.ACCOUNT_NAME, "sarobrindha")//my gmail name
.withValue(ContactsContract.Groups.ACCOUNT_TYPE,
"gmail.com")
.withValue(ContactsContract.Groups.SHOULD_SYNC, true)
.build());
try {
con.getContentResolver().applyBatch(ContactsContract.AUTHORITY,
opsGroup);
} catch (Exception e) {
e.printStackTrace();
}
What mistake i have done.
Kindly help me to figure out
Thanks

You may simply make DB Queries to do so.
make a look into this method:
private Boolean createGrp(String GroupName) {
// TODO Auto-generated method stub
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(getActivity(), "Please Enter Any Text", Toast.LENGTH_SHORT).show();
return false;
}
// Check the Group is available or not
Cursor groupCursor = null;
String[] GROUP_PROJECTION = new String[] {
ContactsContract.Groups._ID, ContactsContract.Groups.TITLE
};
groupCursor = getActivity().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(getActivity(), "Group is already available", Toast.LENGTH_SHORT).show();
return false;
} else {
// Toast.makeText(Create_Group_Main_Page.this, "Not available", Toast.LENGTH_SHORT).show();
// Here we create a new Group
try {
ContentValues groupValues = null;
ContentResolver cr = getActivity().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());
return false;
}
}
groupCursor.close();
groupCursor = null;
Log.d(" **** Contacts add to Groups...", "**** Fine");
String groupID = null;
Cursor getGroupID_Cursor = null;
getGroupID_Cursor = getActivity().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);
}
}
return true;
}

Related

trying to update a contact with this code isn't working

I'm trying to use this code to allow a user edit a contact's name and number. I get no errors and when I print nameofcontact and numberofcontact in my log it shows me the latest changes I've made to the name and number of the contact.
But it's not saving to my contacts database. Any ideas what's wrong?
public void editButton(View view) {
// the text in the 'nameofcontact' edittext box, can be modified by the user
contactname = nameofcontact.getText().toString();
// the text in the 'numberofcontact' edittext box, can be modified by the user
contactnumber = numberofcontact.getText().toString();
ContentResolver cr = getContentResolver();
String where = ContactsContract.Data.DISPLAY_NAME + " = ? AND " +
ContactsContract.Data.MIMETYPE + " = ? AND " +
String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE) + " = ? ";
String[] params = new String[] {contactname,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_HOME)};
Cursor phoneCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, where, params, null);
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
// if ( (null == phoneCur) ) {
// createContact(name, phone);
// } else
{
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where, params)
.withValue(ContactsContract.CommonDataKinds.Phone.DATA, contactnumber)
.build());
}
phoneCur.close();
try {
cr.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println (contactname);
System.out.println (contactnumber);
Toast.makeText(this, "Updated", Toast.LENGTH_SHORT).show();
}
Please check you add below permission in your manifeast or not
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
and you can use this method it works for me.
public boolean updateContact(String name, String number, String ContactId) {
boolean success = true;
String phnumexp = "^[0-9]*$";
try {
name = name.trim();
number = number.trim();
if (name.equals("") && number.equals("")) {
success = false;
} else if ((!number.equals("")) && (!match(number, phnumexp))) {
success = false;
} else {
ContentResolver contentResolver = SwipableHomeActivity.this
.getContentResolver();
String where = Data.CONTACT_ID + " = ? AND "
+ Data.MIMETYPE + " = ?";
String[] nameParams = new String[]{
ContactId,
StructuredName.CONTENT_ITEM_TYPE};
String[] numberParams = new String[]{
ContactId,
Phone.CONTENT_ITEM_TYPE};
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
if (!name.equals("")) {
ops.add(ContentProviderOperation
.newUpdate(
Data.CONTENT_URI)
.withSelection(where, nameParams)
.withValue(StructuredName.DISPLAY_NAME, name)
.build());
}
if (!number.equals("")) {
ops.add(ContentProviderOperation
.newUpdate(
Data.CONTENT_URI)
.withSelection(where, numberParams)
.withValue(Phone.NUMBER, number).build());
}
contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
}
} catch (Exception e) {
e.printStackTrace();
success = false;
}
return success;
}

Sent messages are shown duplicated in my List View

private class getItemLists extends AsyncTask<Void, String, String> {
private Context mContext;
public getItemLists(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
ld.setVisibility(View.VISIBLE);
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
// Intent i = new Intent("notify.intent.MAIN");
// mContext.sendBroadcast(i);
}
#Override
protected String doInBackground(Void... params) {
try {
Chatdb db = new Chatdb(mContext);
String[] smsid = db.getAllinboxsmsid();
// Create Inbox box URI
Uri inboxURI = Uri.parse("content://sms/inbox");
// List required columns
String[] reqCols = new String[] { "_id", "address", "body",
"date", "read" };
// Get Content Resolver object, which will deal with Content
// Provider
ContentResolver cr = mContext.getContentResolver();
// Fetch Inbox SMS Message from Built-in Content Provider
Cursor c = cr.query(inboxURI, reqCols, null, null, null);
boolean exists = false;
if (c.moveToLast()) {
do {
exists = false;
publishProgress((c.getCount() - c.getPosition() + ";" + c
.getCount()));
for (int x = 0; x < smsid.length; x++) {
if (smsid[x].equals(c.getString(0))) {
exists = true;
}
}
if (!exists) {
if (c.getString(4).equals("0")) {
smsRead = "1";
} else {
smsRead = "0";
}
db.addMsgWithTime(c.getString(1), c.getString(2),
"1", "0", "L", c.getString(0),
c.getString(3), smsRead);
publishProgress((c.getCount() - c.getPosition()
+ ";" + c.getCount()));
// Intent in = new
// Intent("SmsMessage.intent.MAIN").putExtra(
// "get_msg", c.getString(1));
//
// // You can place your check conditions here(on
// the SMS or the
// // sender)
// // and then send another broadcast
// SuperMain.this.sendBroadcast(in);
}
} while (c.moveToPrevious());
}
// c.close();
//
String[] SentSmsId = db.getAllsentsmsid();
Uri sentURI = Uri.parse("content://sms/sent");
// List required columns
String[] reqColsSent = new String[] { "_id", "address", "body",
"date", "read" };
// Get Content Resolver object, which will deal with Content
// Provider
// Fetch Inbox SMS Message from Built-in Content Provider
c = cr.query(sentURI, reqColsSent, null, null, null);
if (c.moveToLast()) {
do {
exists = false;
publishProgress((c.getCount() - c.getPosition() + ";" + c
.getCount()));
for (int x = 0; x < SentSmsId.length; x++) {
if (SentSmsId[x].equals(c.getString(0))) {
exists = true;
}
}
if (!exists) {
db.addMsgWithTime(c.getString(1), c.getString(2),
"0", "0", "S", c.getString(0),
c.getString(3), "1");
// db.close();
publishProgress((c.getCount() - c.getPosition()
+ ";" + c.getCount()));
}
} while (c.moveToPrevious());
}
c.close();
db.close();
} catch (Exception e) {
Log.d("ERROR", e.toString());
}
return "done";
}
#Override
protected void onPostExecute(String done) {
super.onPostExecute(done);
// Toast.makeText(mContext, "Messages have synced successfully",
// 3).show();
ld.setVisibility(View.INVISIBLE);
}
}
This is my Loading procedure of Inbox and Sent messages and showing at mu list view.
here ld is my loader... showing when data is loading
public String[] getAllsentsmsid() {
String selectQuery = "SELECT " + KEY_SMSID + " FROM " + TABLE_THREAD
+ " WHERE " + KEY_SMSID + "<>'0' AND " + KEY_ORIGIN + "='0'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] allid = new String[cursor.getCount()];
int x = 0;
if (cursor.moveToFirst()) {
do {
allid[x] = cursor.getString(0);
x++;
} while (cursor.moveToNext());
}
db.close();
return allid;
}
public String[] getAllinboxsmsid() {
String selectQuery = "SELECT " + KEY_SMSID + " FROM " + TABLE_THREAD
+ " WHERE " + KEY_SMSID + "<>'0' AND " + KEY_ORIGIN + "='1'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] allid = new String[cursor.getCount()];
int x = 0;
if (cursor.moveToFirst()) {
do {
allid[x] = cursor.getString(0);
x++;
} while (cursor.moveToNext());
}
db.close();
return allid;
}
These are my database methods where I am storing messages id and save them in my database.
In my list view making duplicate threads of chatting.

Database is not retrieving all rows instead getting only unique rows

I am working on a code snippet where i am storing my json encoded data into a txt file,and using following method to separate all parts and adding them into database.
public boolean addAnswersFromJSONArray() {
boolean flag = false;
Answer answer = new Answer();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "user_live.txt");
FileReader fr;
JsonReader reader;
try {
fr = new FileReader(file);
reader = new JsonReader(fr);
reader.beginArray();
reader.setLenient(true);
while (reader.hasNext()) {
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("product_name")) {
answer.setProductName(reader.nextString());
} else if (name.equals("subject")) {
answer.setSubject(reader.nextString());
} else if (name.equals("month")) {
answer.setMonth(reader.nextString());
} else if (name.equals("year")) {
answer.setYear(reader.nextString());
} else if (name.equals("question")) {
answer.setQuestion(reader.nextString());
} else if (name.equals("answer")) {
answer.setAnswer(reader.nextString());
} else if (name.equals("question_no")) {
answer.setQuestion_no(reader.nextString());
} else if (name.equals("marks")) {
answer.setMarks(reader.nextString());
} else {
reader.skipValue();
}
}
answer.save(db);
reader.endObject();
flag = true;
}
reader.endArray();
reader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
file.delete();
db.close();
}
return flag;
}
and then i am retrieving each fields departments,subjects,month and year,questions,answers,question_no, but while retrieving marks i am getting only unique entries that is 10 and 5....Ideally the size of one set is 18 so i m getting ArrayIndexoutOfBounds Exception.
//database calling part
marks = db.getMarksList(department, subject, month_year);
database method is,
public String[] getMarksList(String department, String subject,
String month_year) {
String month = month_year.split("-")[0];
String year = month_year.split("-")[1];
String whereClause = DEPARTMENT + " = '" + department + "'" + " AND "
+ SUBJECT + " = '" + subject + "' AND " + MONTH + " = '"
+ month + "' AND " + YEAR + " = '" + year + "'";
System.out.println("questions: " + whereClause);
Cursor cursor = db.query(true, "ANSWERS", new String[] { "MARKS" },
whereClause, null, null, null, "DEPARTMENT", null);
String list[] = new String[cursor.getCount()];
int i = 0;
if (cursor != null && cursor.getCount() > 0) {
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
.moveToNext()) {
list[i] = new String(cursor.getString(0));
i++;
}
}
return list;
}
Can anyone help me to resolve this issue?? Why getting only unique value,I have checked my json result also each row contains marks.
i got the solution for this,
Changed database query and method as following,
public List<Answer> getMarksList(String department, String subject,
String month_year) {
List<Answer> list = new ArrayList<Answer>();
String month = month_year.split("-")[0];
String year = month_year.split("-")[1];
try {
String sql1 = "select all marks from " + TABLE_NAME
+ " where department = '" + department
+ "' AND subject = '" + subject + "' AND month = '" + month
+ "' AND year = '" + year + "';";
SQLiteDatabase db1 = this.getWritableDatabase();
Cursor cursor = db1.rawQuery(sql1, null);
if (cursor.moveToFirst()) {
do {
Answer a = new Answer();
a.setMarks(cursor.getString(0));
list.add(a);
} while (cursor.moveToNext());
}
} catch (Exception e) {
}
return list;
}
using "all" in query is retrieving all records.

How to edit the nativecontacts fields using contact id

How to edit firstname,surname,mobilenumber,photo,email,address in native contact in android programmatically using contact id. Please help me. Thanks in advance.
on Button click do the following:
Intent in = new Intent(Intent.ACTION_INSERT_OR_EDIT);
in.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
startActivityForResult(in,EDIT_CONTACT);
and in onActivityResult Function do this:
case EDIT_CONTACT:
if (resultCode == RESULT_OK) {
Uri contactData = data.getData();
Cursor cur = managedQuery(contactData, null, null, null, null);
ContentResolver contect_resolver = getContentResolver();
if (cur.moveToFirst()) {
String id = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String name = "";
String no = "";
String key = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts.LOOKUP_KEY));
String where = ContactsContract.Data.DISPLAY_NAME + " = ? AND " +
ContactsContract.Data.MIMETYPE + " = ? AND " +
String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE) + " = ? ";
String[] params = new String[] {name,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_HOME)};
Cursor phoneCur = contect_resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
if (phoneCur.moveToFirst()) {
name = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
no = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
key = phoneCur.getString(phoneCur.getColumnIndexOrThrow(ContactsContract.Contacts.LOOKUP_KEY));
System.out.println("EDITIDDDDDDDDDD"+name);
System.out.println("EDITIDDDDDDDDDD"+no);
System.out.println("EDITIDDDDDDDDDD"+key);
/*ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
if ( (null == phoneCur) ) {
// createContact(name, phone);
} else {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where, params)
.withValue(ContactsContract.CommonDataKinds.Phone.DATA, no)
.build());
}
phoneCur.close();
try {
cr.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
id = null;
name = null;
no = null;
phoneCur = null;
key = null;
contect_resolver = null;
cur = null;
}
}
}
break;

adding custom type of number to a contact [Android]

I been working on an app that helps sending sms to your contacts. Everything is great, except that I'm supposed to add a "custom field number" to a contact such as "Work" or "Private". I'd search the web for answers and the ones that are useful for evryone, aren't for me. This is my code:
private void AddCtxtAttribute(int contactID, String contactNumber) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = ContentProviderOperation
.newInsert(Data.CONTENT_URI);
builder.withValue(Data.RAW_CONTACT_ID, contactID);
builder.withValue(ContactsContract.Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
builder.withValue(ContactsContract.Data.DATA1, contactNumber);
builder.withValue(ContactsContract.Data.DATA2, Phone.TYPE_CUSTOM);
builder.withValue(ContactsContract.Data.DATA3, "My Custom Label");
ops.add(builder.build());
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
Log.e("RESULT", "Success! " + contactID + " - "
+ contactNumber);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ERROR", "error : " + e.toString());
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ERROR", "error : " + e.toString());
}
}
And it's called:
AddCtxtAttribute(contacto_id, contacto_numero);
where contacto_id and contacto_numero are a int and a String respectively.
The problem is that when I pressed the button, I have the ID (contacto_id) of that contact but it updates other contact. (like the id's don't match) but i've debug it and the id doesn't change.
Can anyone help me with this?
I figured it out!
the problem was that i was using diferent column names and uris in reading the contacts and inserting a new contact number.
I did this:
to query all contacts:
private void llenar_contactos() {
ProgressDialog progress;
lista_contactos_cel_sobrantes = null;
sobrantes = false;
lista_contactos_cel = new ArrayList<HashMap<String, Object>>();
progress = ProgressDialog.show(contactsActivity.this, "",
"Cargando Contactos. Porfavor espere...");
String[] projection = new String[] { Data.RAW_CONTACT_ID,
Phone.DISPLAY_NAME, Phone.NUMBER, Phone.LABEL };
String selection = Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'";
// ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER + "='1'";
String sort_order = "display_name ASC";
Uri mContacts = Data.CONTENT_URI;
// ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
Cursor contacts = getContentResolver().query(mContacts, // Contact URI
projection, // Which columns to return
selection, // Which rows to return
null, // Where clause parameters
sort_order // Order by clause
);
total_contactos = contacts.getCount();
if (total_contactos > 0) {
int i = 0;
int multiplo = 0;
int indice_total = 0;
int temp_registros = 0;
String contact_id = "";
String name = "";
String phoneNo = "";
String label = "";
sobrantes = false;
int nameFieldColumnIndex = 0;
while (contacts.moveToNext()) {
nameFieldColumnIndex = contacts.getColumnIndex(Data.RAW_CONTACT_ID);
if (nameFieldColumnIndex > -1) {
contact_id = contacts.getString(nameFieldColumnIndex);
}
nameFieldColumnIndex = contacts.getColumnIndex(Phone.DISPLAY_NAME);
if (nameFieldColumnIndex > -1) {
name = contacts.getString(nameFieldColumnIndex);
}
nameFieldColumnIndex = contacts.getColumnIndex(Phone.NUMBER);
if (nameFieldColumnIndex > -1) {
phoneNo = contacts.getString(nameFieldColumnIndex);
}
nameFieldColumnIndex = contacts.getColumnIndex(Phone.LABEL);
if (nameFieldColumnIndex > -1) {
label = contacts.getString(nameFieldColumnIndex);
}
if(label != null){
Log.i("CONTACTO", "id: " + contact_id + " -> name: " + name
+ " ->number: " + phoneNo + " ->label: " + label);
} else {
Log.d("CONTACTO", "id: " + contact_id + " -> name: " + name
+ " ->number: " + phoneNo + " ->label: " + label);
}
}
contacts.close();
}
}
And to insert a new custom label:
private void AddCtxtAttribute(int contactID, String contactNumber) {
if (contactID != 0 && contactNumber != null) {
ArrayList<ContentProviderOperation> ops =
new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValue(Data.RAW_CONTACT_ID, contactID)
.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, contactNumber)
.withValue(Phone.TYPE, Phone.TYPE_CUSTOM)
.withValue(Phone.LABEL, "My Custom Label")
.build());
try{
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Categories

Resources