Android run time permission error - android

I am developing an application that required to access contacts in phone. this method is executed inside a thread. But when app start for the first time it crashes and says android.permission.READ_CONTACTS or android.permission.READ_CONTACTS required as error. as soon as press on OK in on error pop up dialog box. it restart it self asking for permission and works fine.
here's the code inside fragment on onCreateView method to check whether permission already has been granted.
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_CONTACTS)
== PackageManager.PERMISSION_GRANTED) {
Runnable r = new Runnable() {
#Override
public void run() {
getContacts();
}
};
Thread thread = new Thread(r);
thread.start();
}else{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)) {
Toast.makeText(getActivity(),"Read contacts permission is required to function app correctly",Toast.LENGTH_LONG)
.show();
}
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
}
here's the onRequestPermissionsResult method.
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case REQUEST_READ_CONTACTS :
Runnable r = new Runnable() {
#Override
public void run() {
getContacts();
}
};
Thread thread = new Thread(r);
thread.start();
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
here's the code for get contact method.
public void getContacts() {
ContentResolver cr = getActivity().getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur != null) {
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String imgPath = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor ncur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
if (ncur != null) {
while (ncur.moveToNext()) {
String phoneNumber = ncur.getString(ncur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String reDefinedPhoneNumber = "";
if (phoneNumber.contains("-")) {
String[] split = phoneNumber.split("-");
for (String k : split) {
reDefinedPhoneNumber = reDefinedPhoneNumber.concat(k);
}
} else if (phoneNumber.contains(" ")) {
String[] split = phoneNumber.split(" ");
for (String k : split) {
reDefinedPhoneNumber = reDefinedPhoneNumber.concat(k);
}
} else {
reDefinedPhoneNumber = phoneNumber;
}
Contact contact = new Contact();
contact.setId(contact.getId());
contact.setName(name);
contact.setNumber(reDefinedPhoneNumber);
contact.setImgPath(imgPath);
contacts.add(contact);
}
ncur.close();
}
}
}
}
cur.close();
}
}
Here's AndroidManifest.xml code.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.shan.chathuranga.smsscheduler">
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
</manifest>
what am I doing wrong. works fine in below marshmallow.

Related

How can I reach contacts when I have taken permission?

I am writing an application to Google Play. I have to take permission from user because İf I don"t my app will be shut down. My purpose is first time user start my app. I want to take Contacts permission from him/her then load her/his contacts to customized listview. But When I want permission from users, My contacts are not loading to my customized Listview. How can I fix it?
Here my permission is in xml file
<uses-permission android:name="android.permission.READ_CONTACTS"
/>
<uses-permission android:name="android.permission.VIBRATE"></uses-permission>
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
My request Permissions method:
if (ContextCompat
.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_CONTACTS) != (int) PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CALL_PHONE)
!= (int)PackageManager.PERMISSION_GRANTED) {
// Check if user has opted "Never show again"
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.READ_CONTACTS) ||
ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.CALL_PHONE)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[] {
Manifest.permission.READ_CONTACTS,
Manifest.permission.CALL_PHONE
}, requestCode);
}
}
} else {
getNumber(this.getContentResolver()); // it is taking method of contacts
}
chosinglist = (ListView) findViewById(R.id.chosing);
chosinglist.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
GetNumber methods:
private void getNumber(ContentResolver contentResolver) {
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cursor.moveToFirst()) {
// ArrayList<String> alContacts = new ArrayList<String>();
do {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
while (pCur.moveToNext()) {
String phoneNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String name = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
listte.add(name);
listtearama.add(phoneNumber);
// alContacts.add(contactNumber);
break;
}
pCur.close();
}
} while (cursor.moveToNext());
}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.checkrow,
R.id.checkedTextView2, listte);
kaydet.setEnabled(false);
chosinglist.setAdapter(adapter); }
I think you are initializing ListView after fetching the contacts
Try this:
chosinglist = (ListView) findViewById(R.id.chosing);
chosinglist.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
if (permissionNotGranted)
{
}
else
{
getNumber(this.getContentResolver()); // it is taking method of contacts
}
Please try this:
if (ContextCompat
.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_CONTACTS) != (int) PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CALL_PHONE)
!= (int)PackageManager.PERMISSION_GRANTED) {
// Check if user has opted "Never show again"
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.READ_CONTACTS) ||
ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.CALL_PHONE)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[] {
Manifest.permission.READ_CONTACTS,
Manifest.permission.CALL_PHONE
}, requestCode);
}else{
getContactDetails();
}
}
} else {
getContactDetails(); // it is taking method of contacts
}
public void getContactDetails() {
ContentResolver cr = getActivity().getContentResolver();
String[] PROJECTION = new String[]{ContactsContract.RawContacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_ID,
ContactsContract.CommonDataKinds.Email.DATA,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.RawContacts.VERSION};
String order = "CASE WHEN "
+ ContactsContract.Contacts.DISPLAY_NAME
+ " NOT LIKE '%#%' THEN 1 ELSE 2 END, "
+ ContactsContract.Contacts.DISPLAY_NAME
+ ", "
+ ContactsContract.CommonDataKinds.Phone.DATA
+ " COLLATE NOCASE";
String filter = ""+ ContactsContract.Contacts.HAS_PHONE_NUMBER + " > 0 and " + ContactsContract.CommonDataKinds.Phone.TYPE +"=" + ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;
Cursor cur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, filter, null, order);
for (int i = 0; i < cur.getColumnCount(); i++) {
Timber.e("column " + i + "=" + cur.getColumnName(i));
}
if (cur.moveToFirst()) {
do {
String name = cur.getString(1);
String number = cur.getString(4);
number = Utils.removeExtraCharFromString(number);
if (number.length() > 8) {
mContactNumbers = mContactNumbers + number + ",";
PhoneContacts phoneContacts = new PhoneContacts();
try {
phoneContacts.setName(URLEncoder.encode(name, "UTF-8"));
phoneContacts.setNumber(number);
phoneContacts.setNameInitial(String.valueOf(phoneContacts.getName().charAt(0)));
listOfContactsRaw.add(phoneContacts);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
} while (cur.moveToNext());
}
cur.close();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Set set = new TreeSet(new Comparator() {
#Override
public int compare(Object o1, Object o2) {
PhoneContacts phoneContacts1 = (PhoneContacts) o1;
PhoneContacts phoneContacts2 = (PhoneContacts) o2;
if (phoneContacts1.getNumber().equalsIgnoreCase(phoneContacts2.getNumber())) {
return 0;
}
return 1;
}
});
set.addAll(listOfContactsRaw);
System.out.println("\n***** After removing duplicates *******\n");
listOfContacts = new ArrayList(set);
initRecyclerView();
}
}, 200);
}

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?

How read a sms from android

I try to make a simple app for read sms from my smartphone,
I run the code but and but anythings shows in my application
I try to debug the code I found this variable cur cannot be found
what is the problem here ?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private static final int request_permission = 123;
#RequiresApi(api = Build.VERSION_CODES.M)
public void ButtonLoad(View view) {
if((int) Build.VERSION.SDK_INT >=23){
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS)!= PackageManager.PERMISSION_GRANTED){
if(!shouldShowRequestPermissionRationale(Manifest.permission.READ_SMS)){
requestPermissions( new String[]{Manifest.permission.READ_SMS},request_permission);
}
return;
}
}
LoadInboxMassges();
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode){
case request_permission:
if (grantResults[0]==PackageManager.PERMISSION_GRANTED){
LoadInboxMassges();
}else {
//permission_Denied
}
}
}
void LoadInboxMassges(){
try {
String sms = "";
Uri uriSMSURI = Uri.parse("content://sms/inbox");
Cursor cur = getContentResolver().query(uriSMSURI, null,null, null, null);
cur.moveToPosition(0);
while (cur.moveToNext()) {
sms += "From : " + cur.getString(cur.getColumnIndex("adress")) + " : " + cur.getString(cur.getColumnIndex("body")) + "\n";
TextView txtDisplay = (TextView) findViewById(R.id.txtv);
txtDisplay.setText(sms);
}
}catch (Exception ex)
{
}
}
1 remove this line cur.moveToPosition(0);
2 Change the word "adress" of this line:
sms += "From : " + cur.getString(cur.getColumnIndex("adress")) + " : " + cur.getString(cur.getColumnIndex("body")) + "\n";
to "address".
Other suggestions:
There are some other errors or something improper in your code, such as:
1 Reading sms in your inbox may spend a long time. That may crash your app.
2 Your txtDisplay should be placed out of the loop body.
3 You should call cur.close(); after cur is in the end.
In your LoadInboxMassges() method
remove the code cur.moveToPosition(0);
change in the following manner
if (cursor != null) {
while (cursor.moveToNext()) {
// read your cursor here
}

How to get Number of Unread mails count from Gmail account

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

ClearCallLog not updating listview

I am a school student learning android. I am doing a simple contacts app! When i click on clear calllog button, my recent contacts listview remains the same. Its not getting cleared. But when i close the app and reopen again, the recent contacts fragment is getting cleared! I debugged the code, code is not entering after cursor.movetoNext() line when i click on clearcall log. Kindly help me techies!
I programmed like updateFragment2ListView() gets called when i clear the call log button in menu!
public class RecentContacts extends Fragment {
HashMap contactMap = new HashMap();
View rootView;
RecentAdapter rr;
ListView list;
private static final int PERMISSIONS_REQUEST_READ_CALLLOG = 100;
Cursor cursor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_recent_contacts, container, false);
list = (ListView) rootView.findViewById(R.id.customlist);
getRecentContacts();
rr = new RecentAdapter(contactMap, getActivity());
list.setAdapter(rr);
return rootView;
}
public void updateFragment2ListView() {
getRecentContacts();
rr.notifyDataSetChanged();
list.setAdapter(rr);
System.out.println("Fragment recent updated-updateFragment2listview");
}
#Override
public void onResume() {
getRecentContacts();
rr.notifyDataSetChanged();
System.out.println("Fragment recent updated- onresume");
super.onResume();
}
#Override
public void onStart() {
System.out.println("Fragment recent onstart");
super.onStart();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
void getRecentContacts() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && getContext().checkSelfPermission(Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CALL_LOG}, PERMISSIONS_REQUEST_READ_CALLLOG);
//After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method
System.out.println("Security check ok");
} else {
System.out.println("Entered recent onstart");
int i=0;
Uri queryUri = android.provider.CallLog.Calls.CONTENT_URI;
String[] projection = new String[]{
ContactsContract.Contacts._ID,
CallLog.Calls._ID,
CallLog.Calls.NUMBER,
CallLog.Calls.CACHED_NAME,
CallLog.Calls.DATE,
CallLog.Calls.TYPE};
String sortOrder = String.format("%s limit 500 ", CallLog.Calls.DATE + " DESC");
try {
System.out.println("Entering cursor in recent contacts");
cursor = getActivity().getContentResolver().query(queryUri, projection, null, null, sortOrder);
System.out.println("Entered cursor in recent contacts");
} catch (SecurityException e) {
Log.e("", "");
}
while (cursor.moveToNext()) {
System.out.println("Entered cursor.movetoNext recent contacts");
String phoneNumber = cursor.getString(cursor
.getColumnIndex(CallLog.Calls.NUMBER));
System.out.println("Entered phone number in recent contacts");
String title = (cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME)));
int duration1 = cursor.getColumnIndex(CallLog.Calls.DURATION);
System.out.println("Duration" + duration1);
System.out.println("Entered duration in recent contacts");
int date = cursor.getColumnIndex(CallLog.Calls.DATE);
String callDate = cursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
System.out.println("Call Date" + callDayTime);
int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
String callType = cursor.getString(type);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
System.out.println("Call type" + dir);
// if (phoneNumber == null || title == null) continue;
String uri = "tel:" + phoneNumber;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uri));
String intentUriString = intent.toUri(0);
contactMap.put(i, new RecentPojo(title, phoneNumber, duration1, false, callDayTime, dir));
// Toast.makeText(this,title,Toast.LENGTH_SHORT).show();
i++;
}
cursor.close();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if ((requestCode == PERMISSIONS_REQUEST_READ_CALLLOG)) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission is granted
System.out.println("");
getRecentContacts();
} else {
Toast.makeText(getContext(), "Until you grant the permission, we cannot display the names", Toast.LENGTH_SHORT).show();
}
}
}
}
You have to call rr.notifyDataSetChanged(); when you clear it so the ListView is refreshed.

Categories

Resources