How to get Number of Unread mails count from Gmail account - android

Hi i am trying to find Number of unread mails count from my Gmail account for this i searched lot in Google but i did not get
any working solution and finally i found one document from below link i followed same process but it returns always Unread mails count as 0 but in Gmail account there is 2 Unread messages
http://android-developers.blogspot.in/2012/04/gmail-public-labels-api.html
Can some one help me please i am waiting for correct solution since 3 days
public static int getGmailCount(Context context) {
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(GmailContract.Labels.getLabelsUri("ensisinfo102#gmail.com"),
null,
null, null,
null);
if (cursor == null || cursor.isAfterLast()) {
Log.d(TAG, "No Gmail inbox information found for account.");
if (cursor != null) {
cursor.close();
}
return 0;
}
int count = 0;
while (cursor.moveToNext()) {
if (CANONICAL_NAME_INBOX_CATEGORY_PRIMARY.equals(cursor.getString(cursor.getColumnIndex(CANONICAL_NAME)))) {
count = cursor.getInt(cursor.getColumnIndex(NUM_UNREAD_CONVERSATIONS));
System.out.println("count is====>" + count);
break;
}
}
cursor.close();
return count;
}

I never tried this but can you try this.
public class MainActivity extends AppCompatActivity {
AccountManager accountManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
accountManager = AccountManager.get(this);
Account account= getAccount(accountManager);
Log.d("MainActivity","UnreadCount-----> "+getUnreadCount(account.name));
}
public Account getAccount(AccountManager accountManager) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return null;
}
Account[] accounts = accountManager.getAccountsByType("com.google");
Account account;
if (accounts.length > 0) {
account = accounts[0];
} else {
account = null;
}
return account;
}
public int getUnreadCount(String accountName) {
Cursor cursor = getContentResolver().query(
GmailContract.Labels.getLabelsUri(accountName),
UnreadQuery.PROJECTION, null, null, null
);
try {
if (cursor == null || cursor.isAfterLast()) {
return 0;
}
int unread = 0;
while (cursor.moveToNext()) {
String canonicalName = cursor.getString(UnreadQuery.CANONICAL_NAME);
int unreadInLabel = cursor.getInt(UnreadQuery.NUM_UNREAD_CONVERSATIONS);
if (GmailContract.Labels.LabelCanonicalNames.CANONICAL_NAME_INBOX_CATEGORY_PRIMARY.equals(canonicalName)) {
unread = Math.max(unread, unreadInLabel);
}
}
return unread;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private interface UnreadQuery {
String[] PROJECTION = {
GmailContract.Labels.NUM_UNREAD_CONVERSATIONS,
GmailContract.Labels.CANONICAL_NAME,
};
int NUM_UNREAD_CONVERSATIONS = 0;
int CANONICAL_NAME = 1;
}
}

Related

Contacts Update to DB Not working with ContentObserver

I am working with an Android application which shows the list of contacts in the phone like Whats-app. I am successful with getting the contacts to the Application database. When I try to update my DB when a contact is newly added/edited/deleted using Content Observer, I mainly face two problems
1. When Calls ,
String contactName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
I am getting wrong name. eg:- I edited Samuel's Contact no but checking the above code getting David's name.
when I try to get contact number by using the code,
contactNumber = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
I am getting error
E/CursorWindow: Failed to read row 0, column -1 from a CursorWindow which has 402 rows, 41 columns.
03-01 17:16:56.546 3660-3660/com.xxxxxxxxx.xxxxx W/System.err: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Please Anybody help me to find the solution.
Here is my Code
public class ContactObserver extends ContentObserver {
Intent i;
private static final String TAG = "ObserverReceiver";
private Context context;
BaseActivity mBaseActivity;
public ContactObserver(Handler handler, BaseActivity context) {
super(handler);
this.mBaseActivity = context;
this.context = context;
}
public ContactObserver() {
super(null);
}
#Override
public boolean deliverSelfNotifications() {
return true;
}
#Override
public void onChange(boolean selfChange, Uri uri) {
super.onChange(selfChange, uri);
if (!selfChange) {
try {
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
Log.d(TAG, "Observer has been started..");
// Contacts Cursor
final Cursor cur = context.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
// Check which contact is added or updated
if (cur != null) {
while (cur.moveToNext()) {
// Get contact added/updated timestamp but CONTACT_LAST_UPDATED_TIMESTAMP
// Get new/updated contact detail here
final String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
final String contactName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String contactNumber = null;
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
try {
contactNumber = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
} catch (Exception e) {
e.printStackTrace();
}
}
String finalContactNumber = contactNumber;
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
List<Contacts> sContacts = ContactDatabase
.getDatabase(context)
.contactsDao()
.getBySystemid(id);
Log.i("Contacts1+", new Gson().toJson(sContacts));
if (sContacts.size() > 0) {
for (Contacts mContacts : sContacts) {
String phone = finalContactNumber;
if (phone == null) {
phone = mContacts.getPhone();
}
Log.i("Contacts1+", contactName + " : " + phone);
if (phone != null && phone.length() > 0) {
phone = phone.replace(" ", "");
}
while (String.valueOf(phone.charAt(0)).equals("0")) {
String num = "";
for (int i = 1; i < phone.length(); i++) {
num = num + phone.charAt(i);
}
phone = num;
}
if (phone.length() == 10) {
phone = getSharedPreference(AppConstants.SharedKey.COUNTRY_CODE) + phone;
}
if ((mContacts.getName() != contactName || mContacts.getPhone() != phone)) {
mContacts.setName(contactName);
if (!mContacts.getPhone().equalsIgnoreCase(phone)) {
mContacts.setPhone(phone);
mContacts.setIslisted("false");
}
if (mContacts.getPhone().equalsIgnoreCase(phone) || mContacts.getName().equalsIgnoreCase(contactName)) {
ContactDatabase.getDatabase(context)
.contactsDao()
.update(mContacts);
cur.close();
}
}
}
} else {
Contacts mContacts = new Contacts();
String contactNumber = null;
try {
contactNumber = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (contactNumber != null && contactNumber.length() > 0) {
contactNumber = contactNumber.replace(" ", "");
contactNumber = contactNumber.replace("-", "");
}
while (String.valueOf(contactNumber.charAt(0)).equals("0")) {
String num = "";
for (int i = 1; i < contactNumber.length(); i++) {
num = num + contactNumber.charAt(i);
}
contactNumber = num;
}
if (contactNumber.length() == 10) {
contactNumber = getSharedPreference(AppConstants.SharedKey.COUNTRY_CODE) + contactNumber;
}
String contactName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
mContacts.setPhone(contactNumber);
mContacts.setName(contactName);
mContacts.setSystemid(id);
mContacts.setIslisted("false");
List<Contacts> cContacts = ContactDatabase
.getDatabase(context)
.contactsDao()
.getbyPhone(contactNumber);
if (cContacts.size() == 0) {
ContactDatabase.getDatabase(context)
.contactsDao()
.insert(mContacts);
}
} catch (Exception e) {
e.printStackTrace();
}
}
i = new Intent(context, ContactSynchService.class);
context.startService(i);
cur.close();
}
});
thread.start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public String getSharedPreference(String key) {
SharedPreferences prefs = mBaseActivity.getSharedPreferences(AppConstants.SHARED_KEY, MODE_PRIVATE);
return prefs.getString(key, "DEFAULT");
}
}
I tried these links, but none of them could give a solution.
ContentObserver for contact update manually
ContentObserver not working in android
Android: ContentObserver not working in android 4.3
Any help will be appreciated. Thanks in Advance

Invalid column data1 error while retrieving contact number using Loader

public class MainActivity extends BaseActivity implements View.OnClickListener, LoaderManager.LoaderCallbacks<Cursor>{
private static final String TAG = "ContentProviderDemo";
private int recentOpPerfomed;
private final int LOAD_CONTACTS=1;
private final int WRITE_CONTACTS=2;
private final int UPDATE_CONTACTS=3;
private final int DELETE_CONTACTS=4;
private boolean firstTimeLoaded=false;
private TextView textViewQueryResult;
private Button buttonLoadData, buttonAddContact,buttonRemoveContact,buttonUpdateContact, buttonPhotoTagActivity;
private ContentResolver contentResolver;
private EditText editTextContactName;
private CursorLoader mContactsLoader;
private String[] mColumnProjection = new String[]{
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
ContactsContract.CommonDataKinds.Phone.NUMBER}
;
private String mSelectionCluse = ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " = ?";
private String[] mSelectionArguments = new String[]{"Ajay"};
private String mOrderBy = ContactsContract.Contacts.DISPLAY_NAME_PRIMARY;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewQueryResult = (TextView) findViewById(R.id.textViewQueryResult);
editTextContactName=(EditText)findViewById(R.id.editTextContactName);
buttonLoadData = (Button) findViewById(R.id.buttonLoadData);
buttonAddContact=(Button)findViewById(R.id.buttonAddContact);
buttonRemoveContact=(Button)findViewById(R.id.buttonRemoveContact);
buttonUpdateContact=(Button)findViewById(R.id.buttonUpdateContact);
buttonPhotoTagActivity=(Button)findViewById(R.id.buttonPhotoTagActivity);
buttonLoadData.setOnClickListener(this);
buttonAddContact.setOnClickListener(this);
buttonRemoveContact.setOnClickListener(this);
buttonUpdateContact.setOnClickListener(this);
buttonPhotoTagActivity.setOnClickListener(this);
contentResolver=getContentResolver();
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
if(i==1){
return new CursorLoader(this,ContactsContract.Contacts.CONTENT_URI,mColumnProjection, null,null,null);
}
return null;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if(cursor!=null && cursor.getCount()>0){
StringBuilder stringBuilderQueryResult=new StringBuilder("");
while (cursor.moveToNext()){
if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
// Query phone here. Covered next
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "
+ ContactsContract.Contacts._ID, null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i("Number", phoneNumber);
stringBuilderQueryResult.append(cursor.getString(0)+" , "+cursor.getString(1)+
" , "+cursor.getString(2)+" , "+phoneNumber+"\n");
}
phones.close();
}
}
textViewQueryResult.setText(stringBuilderQueryResult.toString());
}else{
textViewQueryResult.setText("No Contacts in device");
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonLoadData:loadContacts();
break;
case R.id.buttonAddContact: addContact();
break;
case R.id.buttonRemoveContact:deleteContact();
break;
case R.id.buttonUpdateContact: modifyCotact();
break;
case R.id.buttonPhotoTagActivity: startPhotoTagActivity();
break;
default:
break;
}
}
private void startPhotoTagActivity(){
startActivity(new Intent(this,PhotoTaggingActivity.class));
}
private void insertContacts(){
String newName=editTextContactName.getText().toString();
if(newName!=null && !newName.equals("") && newName.length()!=0){
ArrayList<ContentProviderOperation> cops=new ArrayList<ContentProviderOperation>();
cops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE,"accountname#gmail.com")
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, "com.google")
.build());
cops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, editTextContactName.getText().toString())
.build());
try{
getContentResolver().applyBatch(ContactsContract.AUTHORITY,cops);
}catch (Exception exception){
Log.i(TAG,exception.getMessage());
Toast.makeText(this,exception.getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
private void addContact() {
recentOpPerfomed=WRITE_CONTACTS;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
insertContacts();
} else {
requestRunTimePermissions(this,new String[]{Manifest.permission.WRITE_CONTACTS},MY_PERMISSION_REQUEST_WRITE_CONTACTS);
}
}
private void updateContact(){
String [] updateValue=editTextContactName.getText().toString().split(" ");
ContentProviderResult[] result=null;
String targetString=null;
String newString=null;
if(updateValue.length==2){
targetString=updateValue[0];
newString=updateValue[1];
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
if(newString!=null && !newString.equals("") && newString.length()!=0)
{
String where= ContactsContract.RawContacts._ID + " = ? ";
String [] params= new String[] {targetString};
ContentResolver contentResolver=getContentResolver();
ContentValues contentValues=new ContentValues();
contentValues.put(ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY,newString);
// UPDATE <table_name> SET column1 = value1, column2 = value2 where column3 = selection_value
contentResolver.update(ContactsContract.RawContacts.CONTENT_URI,contentValues, where,params);
}
}
}
}
private void modifyCotact(){
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
updateContact();
} else {
requestRunTimePermissions(this,new String[]{Manifest.permission.WRITE_CONTACTS}, MY_PERMISSION_REQUEST_WRITE_CONTACTS);
}
}
private void removeContacts(){
recentOpPerfomed=DELETE_CONTACTS;
String newName=editTextContactName.getText().toString();
if(newName!=null && !newName.equals("") && newName.length()!=0){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
//display_name = '<entered_value>'
String whereClause=ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY+ " = '"+editTextContactName.getText().toString()+"'";
//DELETE FROM <table_name> where column1 = selection_value
getContentResolver().delete(ContactsContract.RawContacts.CONTENT_URI,whereClause,null);
}
}
}
private void deleteContact(){
recentOpPerfomed=DELETE_CONTACTS;
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.WRITE_CONTACTS)==PackageManager.PERMISSION_GRANTED){
removeContacts();
}else{
requestRunTimePermissions(this,new String[]{Manifest.permission.WRITE_CONTACTS}, MY_PERMISSION_REQUEST_WRITE_CONTACTS);
}
}
private void loadContacts() {
recentOpPerfomed=LOAD_CONTACTS;
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.READ_CONTACTS)==PackageManager.PERMISSION_GRANTED){
Log.i(TAG,"Permisssion is granted");
if (firstTimeLoaded == false) {
getLoaderManager().initLoader(1, null, this);
firstTimeLoaded = true;
} else {
getLoaderManager().restartLoader(1, null, this);
}
}else{
requestRunTimePermissions(this,new String[]{Manifest.permission.READ_CONTACTS}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
}
#Override
public void onRequestPermissionsResult(final int requestCode, #NonNull final String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(permissions.length==1){
if(requestCode==MY_PERMISSIONS_REQUEST_READ_CONTACTS || requestCode==MY_PERMISSION_REQUEST_WRITE_CONTACTS && grantResults[0]==PackageManager.PERMISSION_GRANTED){
switch (recentOpPerfomed){
case WRITE_CONTACTS: addContact();loadContacts();break;
case DELETE_CONTACTS: deleteContact();loadContacts();break;
case UPDATE_CONTACTS: modifyCotact();loadContacts();break;
case LOAD_CONTACTS:loadContacts();
default: break;
}
}
}
}
}
Wasted almost an day on this. Trying to get Phone Number from Contacts APP.
I am trying to retrieve all contacts phone number using Loader. There is no proper explanation in Logcat where i am going wrong. Any help would be greatly appreciated. I keep getting saying Invalid column data1,but what is Invalid column data1?

Android: Insert/Update/Delete contact

I am developing an application in which I list the device contacts, and perform some manipulation with them. I listen to contact changes as described in the following links: Link 1, Link 2
My code is as follows:
public class ContactService extends Service {
private int mContactCount;
Cursor cursor = null;
private int contactStateCheckingFlag=0;
static ContentResolver mContentResolver = null;
public static final String AUTHORITY = "com.example.contacts";
public static final String ACCOUNT_TYPE = "com.example.myapplication.account";
public static final String ACCOUNT = "myapplication";
Account mAccount;
Bundle settingsBundle;
int i=0;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();// Get contact count at start of service
mContactCount = getContactCount();
this.getContentResolver().registerContentObserver(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, true, mObserver);
Cursor curval = getApplicationContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, null, null, null);
if (curval != null && curval.getCount() > 0) {
curval.getCount();
}
curval.close();
}
private int getContactCount() {
try {
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null,null);
if (cursor != null) {
return cursor.getCount();
} else {
cursor.close();
return 0;
}
} catch (Exception ignore) {
} finally {
cursor.close();
}
return 0;
}
private ContentObserver mObserver = new ContentObserver(new Handler()) {
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
new ContactServiceAsyncClass().execute();
}
};
private class ContactServiceAsyncClass extends AsyncTask<Void, Void, Void> {
ArrayList<Integer> arrayListContactID = new ArrayList<Integer>();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
// Get the current count of contacts
int currentCount = getContactCount();
// Add New Contact
if (currentCount > mContactCount){
Cursor contactCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (contactCursor.getCount()<=0) {
Log.d("Contact Cursor count"," is zero");
}else {
Log.d("Contact Cursor count", " > 0");
// Fetch all contact ID from cursor
if(contactCursor.moveToFirst()){
do {
int contactID = contactCursor.getInt(contactCursor.getColumnIndex(ContactsContract.Data._ID));
arrayListContactID.add(contactID);
} while (contactCursor.moveToNext());
}
// Sort the array list having all contact ID
Collections.sort(arrayListContactID);
Integer maxID=Collections.max(arrayListContactID);
Log.d("maxID", ""+maxID);
// Get details of new added contact from contact id
String whereName = ContactsContract.Data._ID + " = ?";// Where condition
String[] whereNameParams = new String[] { ""+maxID}; // Pass maxID
Cursor cursorNewContact = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, whereName, whereNameParams, null);
if(cursorNewContact.getCount()<=0){
}else {
if(cursorNewContact.moveToFirst()){
do{
// Fetch new added contact details
} while(cursorNewContact.moveToNext());
}
}
cursorNewContact.close();
}
contactCursor.close();
} else if(currentCount < mContactCount){
// Delete Contact/
// CONTACT DELETED.
} else if(currentCount == mContactCount){
// Update Contact1
}
mContactCount = currentCount;
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
}
I am able to fetch new added contact. The question is how to delete and update contact? How to know which contact is deleted and updated, as the contact change broadcast doesn't specify the id of the contact that changed?
Please provide your valuable suggestions and guide me in detail.
Thank you.
For delete operation,
1.First you store the previous list of contacts id in local database.
for example: you added contact id`s are 123,124,125.
Now we assume your last added contact(125) was deleted.
How we find it?.
simple first get the list of old contact list. and compare with current contact list.
If old contact list element not in the new list, that contact is deleted from phone.
Note: If delete operation complete, you need to update the contact id`s into DB.
For Update operation,
1.Use VERSION flag for indicating any changes in your contact.
2.VERSION default value is 1. if you modify the contacts,it automatically increase to 2.
3.So you need to store old version value in your local DB. and compare the version value increase or not. If increase the VERSION value you need to update this contact.
Refer the official link,
https://developer.android.com/reference/android/provider/ContactsContract.RawContacts.html
For complete project,
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android-apps/4.0.4_r2.1/com/android/exchange/adapter/ContactsSyncAdapter.java?av=f

Android:How to get all available Calendars from mobile

Unfortunately I have unable to found any help regarding this.
Actually I want to fetch all available calendars(may be calendar preference) list from mobile for example Google calendar, yahoo calendar.
For better explanation I captured some images from Smooth Calendar application which is in below image after config button click from the widget.
==>
Here the Calendars preference showing all calendars available in phone and after choosing the Calendars option it shows all calendars to select what user wants.
Can someone helps me here and shares some knowledge that how to do this.
Thanks
To get all available calendars from mobile hope so this code will help.
Cursor cursor;
if (android.os.Build.VERSION.SDK_INT <= 7) {
cursor = getContentResolver().query(Uri.parse("content://calendar/calendars"), new String[] { "_id", "displayName" }, null,
null, null);
}
else if (android.os.Build.VERSION.SDK_INT <= 14) {
cursor = getContentResolver().query(Uri.parse("content://com.android.calendar/calendars"),
new String[] { "_id", "displayName" }, null, null, null);
}
else {
cursor = getContentResolver().query(Uri.parse("content://com.android.calendar/calendars"),
new String[] { "_id", "calendar_displayName" }, null, null, null);
}
// Get calendars name
Log.i("#calendar","Cursor count " + cursor.getCount());
if (cursor.getCount() > 0) {
cursor.moveToFirst();
String[] calendarNames = new String[cursor.getCount()];
// Get calendars id
int calendarIds[] = new int[cursor.getCount()];
for (int i = 0; i < cursor.getCount(); i++) {
calendarIds[i] = cursor.getInt(0);
calendarNames[i] = cursor.getString(1);
Log.i("#calendar","Calendar Name : " + calendarNames[i]);
cursor.moveToNext();
}
} else {
Log.e("#calendar","No calendar found in the device");
}
Fortunately I have found some help from developer site and able to get all available calendars and show them with dynamic Checkpreferences.
hope my code will help some one in future.
CalendarPreference.java
public class CalendarPreference extends PreferenceActivity{
private static final String CALENDAR_ID = "calendarId";
private static final String[] PROJECTION = new String[] { Calendars._ID,
Calendars.CALENDAR_DISPLAY_NAME, Calendars.CALENDAR_COLOR };
private Set<String> initialActiveCalendars;
CheckBoxPreference mCheckBoxPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.calendaraccounts);
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
initialActiveCalendars = prefs.getStringSet("PREF_ACTIVE_CALENDARS", null);
populatePreferenceScreen(initialActiveCalendars);
}
private void populatePreferenceScreen(Set<String> activeCalendars) {
Cursor cursor = createLoadedCursor();
if (cursor == null) {
return;
}
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
CheckBoxPreference checkboxPref = new CheckBoxPreference(this);
checkboxPref.setTitle(cursor.getString(1));
checkboxPref.setIcon(createDrawable(cursor.getInt(2)));
int calendarId = cursor.getInt(0);
checkboxPref.getExtras().putInt(CALENDAR_ID, calendarId);
checkboxPref.setChecked(activeCalendars == null
|| activeCalendars.contains(String.valueOf(calendarId)));
getPreferenceScreen().addPreference(checkboxPref);
}
}
#Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
return true;
}
private Cursor createLoadedCursor() {
Uri.Builder builder = Calendars.CONTENT_URI.buildUpon();
ContentResolver contentResolver = getContentResolver();
return contentResolver.query(builder.build(), PROJECTION, null, null, null);
}
#Override
public void onPause() {
super.onPause();
HashSet<String> selectedCalendars = getSelectedCalenders();
if (!selectedCalendars.equals(initialActiveCalendars)) {
persistSelectedCalendars(selectedCalendars);
Log.v("Selected Calendars", selectedCalendars.toString());
NewWidget.updateAllWidgets(this);
}
}
private void persistSelectedCalendars(HashSet<String> prefValues) {
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
Editor editor = prefs.edit();
editor.putStringSet("PREF_ACTIVE_CALENDARS", prefValues);
editor.commit();
}
private HashSet<String> getSelectedCalenders() {
PreferenceScreen preferenceScreen = getPreferenceScreen();
int prefCount = preferenceScreen.getPreferenceCount();
HashSet<String> prefValues = new HashSet<String>();
for (int i = 0; i < prefCount; i++) {
Preference pref = preferenceScreen.getPreference(i);
if (pref instanceof CheckBoxPreference) {
CheckBoxPreference checkPref = (CheckBoxPreference) pref;
if (checkPref.isChecked()) {
prefValues.add(String.valueOf(checkPref.getExtras().getInt(CALENDAR_ID)));
}
}
}
return prefValues;
}
private Drawable createDrawable(int color) {
Drawable drawable = getResources().getDrawable(R.drawable.prefs_calendar_entry);
drawable.setColorFilter(new LightingColorFilter(0x0, color));
return drawable;
}
}
And here res/xml/calendaraccounts.xml
<PreferenceScreen>
</PreferenceScreen>

EditText Limit Upto 5 contacts only

I am making a Panic App, and allowing user to add multiple contacts and showing selected contacts into EditText by doing Tap on Add to Contacts button, whenever he/she wants to add.
In EditText getting something like this: 9867XXXXXX, 9866XXXXXX, ......
Changes i require:
Limit upto 5 Contacts only
I know how to limit for characters length in EditText, but don't know how to limit of 5 contacts only ?
private Button btnAddContacts ;
private EditText editContacts
..............................
btnAddContacts = (Button) findViewById(R.id.btnAddContacts);
btnAddContacts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent it= new Intent(Intent.ACTION_GET_CONTENT);
it.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(it, 1);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
if(editContacts != null && editContacts.getText().toString().length()==0)
editContacts.setText(number);
else
if(editContacts != null) editContacts.append(","+number);
}
You can use a flag say maxNoContacts
Snippet:
public YourActivity extends Activity
{
int maxNoContacts = 0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState)
...
btnAddContacts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(maxNoContacts <5 )
{
Intent it= new Intent(Intent.ACTION_GET_CONTENT);
it.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(it, 1);
}
else
{
//show toast saying you added maximum no of contacts.
}
}
});
}
//Update maxNoContacts if contacts fetched properly.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
maxNoContacts++; //Increment maxNoContacts if it fetches contact properly.
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
}

Categories

Resources