I want to get (TO)address of sms saved as draft. I have tried query on canonical_addresses table it is giving me message "Failed to find provider info for canonical_addresses" in logs.
Then I have tried query on sms/draft table it is giving me null as an address.
What is wrong in my code? How should I get information about draft sms? I have searched but didn't get any solution.Plz suggest me some solution.
The way is to get the thread_id that corresponds to the draft message. Find the to address by using thread_id
public String getPhoneNumbersFromThreadID(Context ctx, String threadId)
{
//System.out.println(threadId);
String phoneList = "";
ArrayList<String> phoneCheckList = new ArrayList<String>();
if(thread2Phone.containsKey(threadId))
{
return thread2Phone.get(threadId);
}
if(threadId == null || threadId.equals(""))
{
return "No Name";
}
if(threadId.trim().length() == 0) return "No Name";
Cursor c = ctx.getContentResolver().query(SMSMainListActivity.Sms_CONTENT_URI,
null,
"thread_id = '" + threadId + "'", null, "date ASC");
if (c != null) {
try {
if (c.moveToFirst()) {
while (c.isAfterLast() == false) {
String num = c.getString(c
.getColumnIndex("address"));
num = num.replaceAll(";", ",");
String[] thisNum = num.split(",");
for (int i=0; i<thisNum.length; i++)
{
phoneCheckList.add(formatNumber(thisNum[i])) ;
}
c.moveToNext();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
c.close();
}
}
try {
phoneCheckList = removeDuplicates(phoneCheckList);
Iterator it = phoneCheckList.iterator();
int i = 0;
while (it.hasNext()) {
String name = ""+it.next();
//System.out.println("Iterated "+name);
if(i==0)
phoneList = ""+name;
else
phoneList += ";"+name;
i++;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
phoneCheckList.clear();
thread2Phone.put(threadId, phoneList);
return phoneList;
}
Related
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
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;
}
I'd like to load messages from phone in my activity. I search for solution, but I can`t find any.
Use this :
private String SmsDetails(Application mContext) {
// TODO Auto-generated method stub
smsInbox = new ArrayList<Entry>();
final Uri SMS_Inbox = Uri.parse("content://sms/inbox");
String smsHistory = "";
try {
String sDirection = "1";
String sMessageType = "0";
String SMS_READ_COLUMN = "read";
String SORT_ORDER = " _id ASC";
int count = 0;
Cursor cursor;
int iLastIDRun = 0;
// "address = '+9180009'"
cursor = mContext.getContentResolver().query(
SMS_Inbox,
new String[] { "_id", "thread_id", "address", "person",
"date", "body" },
" _id > " + String.valueOf(iLastIDRun), null,
SORT_ORDER);
sMessageType = "1";
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
do {
String address = cursor.getString(2);
long timestamp = cursor.getLong(4);
String sBody = cursor.getString(5);
if (address.startsWith("1")) {
address = address.substring(1);
}
//store the required details
} while (cursor.moveToNext());
}
} catch (Exception e) {
e.printStackTrace();
}
cursor.close();
}
doCheckSmsHistory();
} catch (Exception e) {
e.printStackTrace();
}
return smsHistory;
}
I'm trying to retrieve info about user videos stored in sdcard, and I've this method:
protected void addVideo () {
cursor = cr.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
mediaColumns, null, null, null);
if (cursor.moveToFirst()) {
int i = 1;
do {
VideoItem newVVI = new VideoItem();
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Video.Media._ID));
newVVI.idthumb = cursor.getString(cursor
.getColumnIndex(MediaStore.Video.Thumbnails._ID));
Cursor thumbCursor = cr.query(
MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
thumbColumns, MediaStore.Video.Thumbnails.VIDEO_ID
+ "=" + id, null, null);
if (thumbCursor.moveToFirst()) {
newVVI.thumbPath = thumbCursor.getString(thumbCursor
.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
}
newVVI.filePath = cursor.getString(cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
newVVI.title = cursor.getString(cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
try {
newVVI.date = cursor.getString(cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_TAKEN));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
newVVI.date = "0";
}
try {
newVVI.duration = cursor.getString(cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
newVVI.duration = "0";
}
try {
newVVI.size = cursor.getString(cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
newVVI.size = "0";
}
try {
newVVI.resolution = cursor.getString(cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.RESOLUTION));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
newVVI.resolution = "0";
}
newVVI.mimeType = cursor
.getString(cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE));
newVVI.id = Integer.toString(i);
ITEMS.add(newVVI);
ITEM_MAP.put(newVVI.id, newVVI);
i++;
} while (cursor.moveToNext());
cursor.close();
} else {
Log.d("TEST", ": else);
}
}
The problem is that for MediaStore.Video.Media.DATE_TAKEN, MediaStore.Video.Media.DURATION,MediaStore.Video.Media.SIZE, and MediaStore.Video.Media.RESOLUTION I got always "0" because for these I always catch the IllegalArgumentException.
Why?
The values are 0 because that is the default and they were never set to be anything else.
The MediaStore does not automatically calculate these values when a video is copied to sdcard.
For duration you could try using MediaPlayer to load the video and then call getDuration.
this code return info from one special audio.but it worked truely.
you can change it acording to my main Question whit while statement for get all audios or videos.
you must change MediaStore.audio in my response to Mediastore.Video.
String name="";
String duration="";
String path="";
Log.d("Loading file: " + filepath,"");
// This returns us content://media/external/videos/media (or something like that)
// I pass in "external" because that's the MediaStore's name for the external
// storage on my device (the other possibility is "internal")
Uri audiosUri = MediaStore.Audio.Media.getContentUri("external");
Log.d("audiosUri = " + audiosUri.toString(),"");
String[] projection = {MediaStore.Audio.AudioColumns.DATA,MediaStore.Audio.AudioColumns.DISPLAY_NAME,MediaStore.Audio.AudioColumns.DURATION};
// TODO This will break if we have no matching item in the MediaStore.
Cursor cursor = managedQuery(audiosUri, projection, MediaStore.Audio.AudioColumns.DATA + " LIKE ?", new String[] { filepath }, null);
cursor.moveToFirst();
path =cursor.getString( cursor.getColumnIndex(projection[0]));
name=cursor.getString( cursor.getColumnIndex(projection[1]));
int iduration = cursor.getColumnIndex(projection[2]);
duration=CalTotalTime(Integer.valueOf(iduration));
Log.d("pathhhhhhhhhhhhhhhhhh", path);
Log.d("nameeeeeeeeeeeeeeeeeeeeeee", name);
Log.d("duration", duration);
cursor.close();
see this link too:
get your info from files by mediastore
hi frnds i have a button and a textview in a whole view,when i click the button then all contact are sved in csv file but i wnt when these contact are going to csv file it update text as "exporting 3 (this count is changingmeans 1 2 3 4 5....till total no of contacts) contcts " means text view is changing when i click button then how to do it
the code for getting total no. of contacts in phone is below...
update:
#Override
protected Boolean doInBackground(String... args) {
int count;
CSVWriter writer = null;
try
{
writer = new CSVWriter(new FileWriter(Environment.getExternalStorageDirectory().getAbsolutePath() + "/my_test_contact.csv"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String displayName;
String number;
String emailid;
long _id;
String columns[] = new String[]{ ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
writer.writeColumnNames(); // Write column header
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
columns,
null,
null,
ContactsContract.Data.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
startManagingCursor(cursor);
if(cursor.moveToFirst()) {
do {
_id = Long.parseLong(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)));
displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)).trim();
number = getPrimaryNumber(_id);
emailid=getEmailid(_id);
writer.writeNext((displayName + "/" + number+ "/" + emailid).split("/"));
}
while(cursor.moveToNext());
csv_status = true;
} else {
csv_status = false;
}
try {
if(writer != null)
writer.close();
} catch (IOException e)
{
Log.w("Test", e.toString());
}
return null;
}
insert this code anywhere in activity
doInBackground :
Runnable myRun = new Runnable(){
public void run(){
int count;
CSVWriter writer = null;
try
{
writer = new CSVWriter(new FileWriter(Environment.getExternalStorageDirectory().getAbsolutePath() + "/my_test_contact.csv"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String displayName;
String number;
String emailid;
long _id;
String columns[] = new String[]{ ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
writer.writeColumnNames(); // Write column header
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
columns,
null,
null,
ContactsContract.Data.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
startManagingCursor(cursor);
int i = 1;
if(cursor.moveToFirst()) {
do {
publishProgress() //<<<< DO THIS
_id = Long.parseLong(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)));
displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)).trim();
number = getPrimaryNumber(_id);
emailid=getEmailid(_id);
writer.writeNext((displayName + "/" + number+ "/" + emailid).split("/"));
}
while(cursor.moveToNext());
csv_status = true;
} else {
csv_status = false;
}
try {
if(writer != null)
writer.close();
} catch (IOException e)
{
Log.w("Test", e.toString());
}
////////////////// end loop
}
}
onProgressUpdate()
runOnUiThread(new Runnable() {
public void run(){
TEXTVIEW.setText("GETTING contact"+integer);//update text! /// here
}
});