Uri Query SMS to get todays sent SMS count - java

I am sending SMS from code & also updating the Systems SMS Sent messages; with :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1)
{
int subscriptionId = SmsManager.getDefaultSmsSubscriptionId();
SmsManager MySmsManager = SmsManager.getSmsManagerForSubscriptionId(subscriptionId);
ArrayList<String> msgArray = MySmsManager.divideMessage(DefaultMsgTemplate);
MySmsManager.sendMultipartTextMessage(SendSMSTo, null,msgArray, null, null);
CurrentSmsParts = msgArray.size();
Log.d("SMS DETAILS : ", "\nFOUND LOLLIPOP MR1 OR ABOVE...");
Log.d("SMS DETAILS : ", "\nDETECTED DEFAULT SMS SIM..."+subscriptionId);
Log.d("SMS DETAILS : ", "\nSENT MSG USING SIM..."+subscriptionId);
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1)
{
SmsManager MySmsManager = SmsManager.getDefault();
ArrayList<String> msgArray = MySmsManager.divideMessage(DefaultMsgTemplate);
MySmsManager.sendMultipartTextMessage(SendSMSTo, null,msgArray, null, null);
CurrentSmsParts = msgArray.size();
Log.d("SMS DETAILS : ", "\nFOUND BELOW LOLLIPOP MR1...");
Log.d("SMS DETAILS : ", "\nDETECTED DEFAULT SMS SIM WHICHEVER AVAILABLE...");
Log.d("SMS DETAILS : ", "\nSENT MSG USING SIM1 OR SIM2 WHICHEVER IS AVAILABLE...");
}
ContentValues values = new ContentValues();
values.put("address", SendSMSTo);
values.put("body", DefaultMsgTemplate);
getContentResolver().insert(Uri.parse("content://sms/sent"), values);
SMSDone++;
Here SMSDone is my counter to count the today sent SMSs via my application... ; But Users are also able to send SMSs, without my application..!!
So..,
How can i query SMS uri to get todays sent SMS number for both of the SIM cards / Numbers?
I am inserting my SMS in Sent SMS; But how to also insert SIM number via which it has been sent, from my application?

Credits : Mike M
Followed his instructions and by having basics of earlier uri querying this is the final answer i have implemented....
Log.d("Executing :", "from here....\n");
try
{
Calendar c1 = Calendar.getInstance();
c1.setTime(new Date());
Calendar c2 = Calendar.getInstance();
c2.set(Calendar.YEAR, c1.get(Calendar.YEAR));
c2.set(Calendar.MONTH, c1.get(Calendar.MONTH));
c2.set(Calendar.DAY_OF_MONTH, c1.get(Calendar.DAY_OF_MONTH));
c2.set(Calendar.HOUR_OF_DAY, 0);
c2.set(Calendar.MINUTE, 0);
c2.set(Calendar.SECOND, 0);
long TodayStartedAt = c2.getTimeInMillis();
Log.d("Today started at ", "here" + TodayStartedAt);
final Uri SMS_INBOX = Uri.parse("content://sms/sent");
Cursor cursor = getContentResolver().query(SMS_INBOX, null, "date>=" + TodayStartedAt, null, null);
List < String > items = new ArrayList < String > ();
int counter = 0;
while (cursor.moveToNext())
{
String Date = cursor.getString(cursor.getColumnIndex("date"));
String SmsBody = cursor.getString(cursor.getColumnIndex("body"));
String PhoneNumber = cursor.getString(cursor.getColumnIndex("address"));
String FromSIM = cursor.getString(cursor.getColumnIndex("sub_id"));
Log.d("Counter : ", counter + "\n");
Log.d("Date : ", Date + "\n");
Log.d("PhoneNumber : ", PhoneNumber + "\n");
Log.d("FromSIM : ", FromSIM + "\n");
Log.d("SmsBody : ", SmsBody + "\n");
counter++;
}
cursor.close();
}
catch (Exception e)
{
Log.e("exception :", "is", e);
}
Thanks #Mike M. And Posted as it may help others in future...

Related

Getting all Contacts Details only in Some Devices Android [duplicate]

I am getting only name & birthday using the code below. But I need phone number & email also. It would be great if anyone can help me out. Thanks.
private void getContacts() {
Uri uri = ContactsContract.Data.CONTENT_URI;
String[] projection = new String[]{
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Event.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Email.DATA,
ContactsContract.CommonDataKinds.Event.START_DATE
};
String where = ContactsContract.Data.MIMETYPE + "= ? AND " +
ContactsContract.CommonDataKinds.Event.TYPE + "=" +
ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
String[] selectionArgs = new String[]{
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE
};
String sortOrder = null;
ContentResolver contentResolver = this.getActivity().getContentResolver();
Cursor cursor = contentResolver.query(uri, projection, where, selectionArgs, sortOrder);
int nameColumn = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int numberColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int emailColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
int bithDayColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE);
while (cursor.moveToNext()) {
String name = cursor.getString(nameColumn);
String number = cursor.getString(numberColumn);
String email = cursor.getString(emailColumn);
String birthDay = cursor.getString(bithDayColumn);
Log.d(TAG, "Birthday: " + birthDay);
}
}
In your projection you're limiting your query to rows of MIMETYPE CommonDataKinds.Event.CONTENT_ITEM_TYPE only, so you'll only get birthdays.
You need to ask for emails and phones mimetypes, but note that these additional information will come in separate rows for the same contact.
For example, for contact A that has 2 phones, 3 emails and a birthday, you'll get 6 results in your cursor. So you need to group them all together using the CONTACT_ID field.
Here's simple code to get you started, print the resulting HashMap and you'll get for each contact all his/hers name, emails, phones and birthday:
Map<Long, List<String>> contacts = new HashMap<Long, List<String>>();
String[] projection = {Data.CONTACT_ID, Data.DISPLAY_NAME, Data.MIMETYPE, Data.DATA1, Data.DATA2, Data.DATA3};
// query only emails/phones/events
String selection = Data.MIMETYPE + " IN ('" + Phone.CONTENT_ITEM_TYPE + "', '" + Event.CONTENT_ITEM_TYPE"', '" + Email.CONTENT_ITEM_TYPE + "')";
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(Data.CONTENT_URI, projection, selection, null, null);
while (cur != null && cur.moveToNext()) {
long id = cur.getLong(0);
String name = cur.getString(1); // full name
String mime = cur.getString(2); // type of data (phone / birthday / email)
String data = cur.getString(3); // the actual info, e.g. +1-212-555-1234
String kind = "unknown";
switch (mime) {
case Phone.CONTENT_ITEM_TYPE:
kind = "phone";
break;
case Event.CONTENT_ITEM_TYPE:
kind = "birthday";
break;
case Email.CONTENT_ITEM_TYPE:
kind = "email";
break;
}
Log.d(TAG, "got " + id + ", " + name + ", " + kind + " - " + data);
// add info to existing list if this contact-id was already found, or create a new list in case it's new
List<String> infos;
if (contacts.containsKey(id)) {
infos = contacts.get(id);
} else {
infos = new ArrayList<String>();
infos.add("name = " + name);
contacts.put(id, infos);
}
infos.add(kind + " = " + data);
}

how to get email address from contact list?

how to get email address from contact list.below code I got number and name and display on list.but I want number,name and email address so pls check below code
ContentResolver contactResolver = context.getContentResolver();
Cursor c = contactResolver.query(ContactsContract.Contacts.CONTENT_URI, new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.HAS_PHONE_NUMBER }, null, null, null);
Cursor cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
null, null, null);
if(cursor.getCount()>0)
while ( cursor.moveToNext()) {
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// String photoUri = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
// String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Log.e("TAG", " Name: " + displayName+"==>phone Number==>"+number);
contactNameArrayList.add(displayName);
contactNumberArrayList.add(number);
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = contactResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { contactId }, null);
while (pCur.moveToNext())
{
String phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String type = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
String s = (String) ContactsContract.CommonDataKinds.Phone.getTypeLabel(context.getResources(), Integer.parseInt(type), "");
// Log.e("TAG", s + " phone: " + phone);
}
pCur.close();
}
Cursor emailCursor = contactResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
null, null, null);
while (emailCursor.moveToNext())
{
String email = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
int type = emailCursor.getInt(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
String s = (String) ContactsContract.CommonDataKinds.Email.getTypeLabel(context.getResources(), type, "");
Log.e("TAG", s + " email: " + email);
}
emailCursor.close();
} cursor.close();
Log.e(TAG,"contactNameArrayList sIZE==>"+contactNameArrayList.size()+"contactNumberArrayList size==>"+contactNumberArrayList.size()+"contactEmailAddressArrayList size==>"+contactEmailAddressArrayList.size());
}
I create three array for name and number and email id but above code I got only mobile and name.when I am add name and mobile no in array so simultaneously store email id particular mobile no in email id array.so pls help ...
You can get Email from contact using this
public List<String> getEmail(int contactId) {
List<String> emailStr = new ArrayList<String>();
ContentResolver cr = context.getContentResolver();
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{String.valueOf(contactId)}, null);
while (emailCur.moveToNext()) {
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
emailStr.add(email);
System.out.println("Email " + email );
}
emailCur.close();
return emailStr;
}
Use Following Code to get multiple numbers and email from one contact and all contacts from phonebook.
private void getContactsFromPhoneBook() {
String unique_id = ApplicationConstant.phone_id;
System.out.println("Unique_ID : " + unique_id);
Contact_To_Sync contact_to_sync = new Contact_To_Sync();
List<Contacts> AllContact_toSync = new ArrayList<>();
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
System.out.println("Contacts Count : " + cur.getCount());
if (cur.getCount() > 0) {
Contacts contacts = null;
List<String> Phones;
List<String> Emails;
while (cur.moveToNext()) {
contacts = new Contacts();
Phones = new ArrayList<>();
Emails = new ArrayList<>();
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String timeStamp = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.CONTACT_LAST_UPDATED_TIMESTAMP));
contacts.setContact_id(id);
contacts.setName(name);
System.out.println("name : " + name + ", ID : " + id + " Status : " + timeStamp);
// get the phone number
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("phone" + phone);
Phones.add(phone);
}
pCur.close();
// get email and type
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
Emails.add(email);
System.out.println("Email " + email + " Email Type : " + emailType);
}
emailCur.close();
contacts.setEmails(Emails);
contacts.setPhones(Phones);
AllContact_toSync.add(contacts);
}
contact_to_sync.setContacts(AllContact_toSync);
contact_to_sync.setPhone_device_name(unique_id);
if (!contact_to_sync.getContacts().isEmpty()) {
Sync_Contacts_To_Server(contact_to_sync);
}
}
}

getIntExtra() always returning the default value

I have two different apps, AppA and AppB, I am trying to send an int from AppB to AppA, but the getIntExtra() in AppA is always getting the default value 0. Currently in AppA, gameRecords_str is receiving the correct string value, but I keep getting the default value 0 for gameCounter. What went wrong?
AppB:
String query = "SELECT * FROM gameRecord";
Cursor mcursor = database.rawQuery(query, null);
int counter = mcursor.getCount(); // Find out the number of records found in database
System.out.println("Number of record : " + counter);
Intent sendCounter = new Intent();
sendCounter.setAction("com.joy.AppA.LAUNCH_IT");
sendCounter.putExtra("counter", counter);
startActivity(sendCounter);
String gameRecord_str;
int flag;
mcursor.moveToFirst();
if (mcursor != null) {
if (mcursor.moveToFirst()) {
do {
String record = mcursor.getString(mcursor.getColumnIndex("record"));
gameRecord_str = record;
Intent i = new Intent();
i.setAction("com.joy.AppA.LAUNCH_IT");
i.putExtra("gameRecord", gameRecord_str);
startActivity(i);
} while (mcursor.moveToNext());
AppA:
Intent intent = getIntent();
int gameCounter = intent.getIntExtra("counter", 0); //Number of records from game AppB
System.out.println("gameCounter : " + gameCounter);
for (int i=0; i<=gameCounter; i++) {
String gameRecords_str = intent.getStringExtra("gameRecord");
System.out.println("Game record received from AppB : " + gameRecords_str);
Thanks in advance for your help!

Sending sms through smsManager stoppeed working

I made an app to read values from the database and send messages through the smsManager and it was perfectly fine but all of a sudden it stopped working, Anybody have any idea what could be the cause? It returns sent status but the messages are not being sent in reality. Here is the code:
package com.brs;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.telephony.SmsManager;
import android.widget.Toast;
/**
* Created by Sahil on 17-06-2015.
*/
public class Sending extends IntentService {
public static int cursor_count=0;
public Sending()
{
super("Sending");
}
SQLiteDatabase sqliteDatabase;
DatabaseHandler databasehandler;
Cursor cursor, cursor2;
protected void onHandleIntent(Intent workIntent) {
databasehandler = new DatabaseHandler(getApplicationContext());
sqliteDatabase = databasehandler.getReadableDatabase();
cursor = databasehandler.read_queue(sqliteDatabase);
cursor.moveToFirst();
System.out.println("The Vlaues for cursor : " + cursor.getCount());
//cursor_count = cursor.getCount();
cursor2 = databasehandler.read_polls(sqliteDatabase);
System.out.println("The Vlaues for cursor2 : " + cursor2.getCount());
int t = 0;
//To reach the first pending statement.
do {
String stats;
stats = cursor.getString(2);
System.out.println("The status is " + stats);
if (stats.matches("PENDING")) {
System.out.println("THE DEBUG CHECKER");
t = 1;
break;
}
} while (cursor.moveToNext());
if (t == 1)
{
do
{
String ques = "", opt1 = "", opt2 = "", opt3 = "", opt4 = "", opt5 = "", keyword = "", start_date = "", end_date = "", message = "";
int k = cursor.getInt(0);
System.out.println("The cursor index:" + k);
if (cursor2.moveToFirst())
{
do
{
int pol_id;
pol_id = cursor2.getInt(0);
if (pol_id == k)
{
ques = cursor2.getString(1);
opt1 = cursor2.getString(2);
opt2 = cursor2.getString(3);
opt3 = cursor2.getString(4);
opt4 = cursor2.getString(5);
opt5 = cursor2.getString(6);
keyword = cursor2.getString(7);
start_date = cursor2.getString(8);
end_date = cursor2.getString(9);
message = cursor2.getString(10);
break;
}
} while (cursor2.moveToNext());
}
for (int i = 0; i < 20; i++) {
int id;
String number;
String status;
id = cursor.getInt(0);
number = cursor.getString(1);
status = cursor.getString(2);
System.out.println("The id :" + id);
System.out.println("The number:" + number);
System.out.println("The status :" + status);
if (id == k) {
String sms;
if (message.matches("")) {
sms = ques + "\nA." + opt1 + "\nB." + opt2 + "\nC." + opt3 + "\nD." + opt4 + "\nE." + opt5 + "\nSTART DATE:" + start_date + "\nEND DATE:" + end_date + "\nReply in the below given format:\n" + id + " " + keyword + " (A|B|C|D|E)";
} else {
sms = message + "\nSTART DATE:" + start_date + "\nEND DATE:" + end_date + "\nReply in the below given format:\n" + id + " " + keyword + " (A|B|C|D|E)\nResponses in Invalid format would not be processed.\nSent from GOLL_POLL";
}
try {
SmsManager smsManager = SmsManager.getDefault();
PendingIntent sentPI;
String SENT = "SMS_SENT";
sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
smsManager.sendTextMessage(number, null, sms, sentPI, null);
databasehandler.update_queue(id, number, "SENT");
} catch (Exception e) {
databasehandler.update_queue(id, number, "FAIL");
System.out.println("Message sending failed");
e.printStackTrace();
}
System.out.println("The status:" + cursor.getString(2));
if (cursor.moveToNext()) {
} else {
break;
}
}
else {
break;
}
}
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
}
}, 40000);
cursor.moveToPrevious();
} while (cursor.moveToNext());
System.out.println("The end has been reached:");
}
}
}

getting "CursorIndexOutOfBoundsException "

I'm trying to retrieve the data of sqlite database . and put it on a string to display it further but I'm getting this error , Kindly help me in solving the error !
here is the logcat data showing error
12-31 13:18:55.141: E/1.6(3833): 2222
12-31 13:18:55.191: E/1.2.2(3833): android.database.CursorIndexOutOfBoundsException: Index 9 requested, with a size of 9
12-31 13:18:55.191: E/1.7(3833): 2222
and here is the piece of code which is showing the error!
public String getdata() {
// TODO Auto-generated method stub
Log.e("1.1", "2222");
String[] column = new String[]{KEY_ROWID, KEY_NAME, KEY_HOTNESS };
Log.e("1.2", "2222");
Cursor c = ourDatabase.query(DATABASE_TABLE, column, null, null, null, null, null);
Log.e("1.3", "2222");
String result = "";
Log.e("1.4", "2222");
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iHotness = c.getColumnIndex(KEY_HOTNESS);
Log.e("1.5", "2222");
try{
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext());
{
Log.e("1.6", "2222");
result = result + c.getString(0) + " " + c.getString(1) + " " + c.getString(2) + "\n";
}
}catch(Exception e)
{
Log.e("1.2.2", e.toString());
}
Log.e("1.7", "2222");
return result;
}
Note : after putting the below code in try catch it's moving to next activity but not showing any result data
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext());
{
Log.e("1.6", "2222");
result = result + c.getString(0) + " " + c.getString(1) + " " + c.getString(2) + "\n";
}
next activity code :
TextView tv = (TextView) findViewById(R.id.textView3);
Log.e("1", "111111");
HotOrNot info = new HotOrNot(this);
Log.e("2", "111111");
info.open();
Log.e("3", "111111");
String data = info.getdata();
Log.e("4", "111111");
info.close();
Log.e("5", "111111");
tv.setText(data);
Log.e("6", "111111");
}
}
You have a semicolon too much:
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()); // look here :(
... so your for loop runs to the end of the cursor. Afterwards you try to get some data from the cursor, what fails, because you are already after the last entry.
Just use this one:
while(c != null && c.moveToNext())
{
Log.e("1.6", "2222");
result = result + c.getString(0) + " "
+ c.getString(1) + " "
+ c.getString(2) + "\n";
}
Most likely you can skip the c != null.

Categories