sir, i have a problem in updating my database. i've made a listview containing this data
name
phone number
status
i would like to update the status of person if he sent a message with a keyword "available" in it and would update my listview like this
name
phone number
available
so i decided to make the phone number as the trigger. if the phone number of the person who sent the message is in my listview, it will update the database. but here is my problem, if i saved the phone number in my listview in this format
09211234567
the sender will return their phone number as
+639211234567
so i worked around this by getting the substring and cut the phone number into "9211234567", and then add 0 to transform it into "09211234567".
however, the database status still doesn't update. but when i used the same technique in sending sms from emulator to emulator, it works just fine.
i saved the number of emulator in my listview as
5556
but the emulator returns
15555215556
so i just get the substring to get 5556
please help me. here is my code:
public static String sender;
public GroupDb info;
public String aStatus = "available";
public String nStatus = "not available";
public String addNum = "0";
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
info = new GroupDb(context);
Bundle bundle = intent.getExtras();
Object[] pdusObj = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdusObj.length];
for (int i = 0; i<pdusObj.length; i++)
{
messages[i] = SmsMessage.createFromPdu ((byte[])
pdusObj[i]);
sender = messages[i].getOriginatingAddress();
}
for (SmsMessage msg : messages) {
if (msg.getMessageBody().contains("available")) {
info.open();
String remFirstChar = sender.substring(3);
addNum += remFirstChar;
Toast.makeText(context.getApplicationContext(), "received sms from: " +addNum,
Toast.LENGTH_LONG).show();
//if starts with +639
if(sender.length() == 13)
{
info.updateStatus(addNum, aStatus);
Toast.makeText(context.getApplicationContext(), "addNum: " +addNum,
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(context.getApplicationContext(), "sender: " +sender,
Toast.LENGTH_LONG).show();
info.updateStatus(remFirstChar, aStatus);
}
info.close();
}//end if - available
here is how i updated my status
//update status
public void updateStatus(String mNumber, String mStatus) throws SQLException
{
// TODO Auto-generated method stub
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_STATUS, mStatus);
ourDatabase.update(DATABASE_TABLE, cvUpdate, KEY_NUMBER + "=" + mNumber, null);
}
update:
i even tried to enter "+63" format in listview but still, i won't update. all functions such as deletion and editing also don't work and shows force close.
You need to use PhoneNumberUtils class.
Before saving the Phone Number in database first convert it as
String formattedNumber = PhoneNumberUtils.formatNumber(phonenumber);
For comparison you can use PhoneNumberUtils.compare
Related
The android default Email is filter by subject, sender or receiver. But how to filter by content? The message body is not saved to database, which is saved to the file in after Android 5.0. Should I put the message body to the database, which do like before Android 5.0? And then filter the content according the keyword? Please give me some advice, Thanks!
case BODY:
final ContentValues dbValues = new ContentValues(values);
// Prune out the content we don't want in the DB
dbValues.remove(BodyColumns.HTML_CONTENT);
dbValues.remove(BodyColumns.TEXT_CONTENT);
// TODO: move this to the message table
longId = db.insert(Body.TABLE_NAME, "foo", dbValues);
resultUri = ContentUris.withAppendedId(uri, longId);
// Write content to the filesystem where appropriate
// This will look less ugly once the body table is folded into the message table
// and we can just use longId instead
if (!values.containsKey(BodyColumns.MESSAGE_KEY)) {
throw new IllegalArgumentException(
"Cannot insert body without MESSAGE_KEY");
}
final long messageId = values.getAsLong(BodyColumns.MESSAGE_KEY);
// Ensure that no pre-existing body files contaminate the message
deleteBodyFiles(context, messageId);
writeBodyFiles(getContext(), messageId, values);
break;
public static String buildLocalSearchSelection(Context context, long mailboxId,
String queryFilter, String queryFactor) {
StringBuilder selection = new StringBuilder();
selection.append(" (");
queryFilter = queryFilter.replaceAll("\\\\", "\\\\\\\\")
.replaceAll("%", "\\\\%")
.replaceAll("_", "\\\\_")
.replaceAll("'", "''");
String[] queryFilters = queryFilter.split(" +");
boolean isAll = false;
if (queryFactor.contains(SearchParams.SEARCH_FACTOR_ALL)) {
isAll = true;
}
if (queryFactor.contains(SearchParams.SEARCH_FACTOR_SUBJECT) || isAll) {
selection.append(buildSelectionClause(queryFilters, MessageColumns.SUBJECT));
}
if (queryFactor.contains(SearchParams.SEARCH_FACTOR_SENDER) || isAll) {
selection.append(buildSelectionClause(queryFilters, MessageColumns.FROM_LIST));
}
if (queryFactor.contains(SearchParams.SEARCH_FACTOR_RECEIVER) || isAll) {
selection.append(buildSelectionClause(queryFilters, null));
}
selection.delete(selection.length() - " or ".length(), selection.length());
selection.append(")");
return selection.toString();
}
it can use the ' MessageColumns.SNIPPET' to filter the email content.
I have written a SMSReceiver for Android and all works fine on real devices and when I test the App over Telnet.
But how can I create a unit test for the following onReceive Method in Android Studio?
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle!=null){
Object[] smsExtras = (Object[]) bundle.get("pdus");
String format = (String)bundle.get("format");
String strMessage = "";
for (Object smsExtra : smsExtras) {
SmsMessage smsMessage;
if (Build.VERSION.SDK_INT < 23){
smsMessage = SmsMessage.createFromPdu((byte[]) smsExtra);
}else {
smsMessage = SmsMessage.createFromPdu((byte[]) smsExtra, format);
}
String messageBody = smsMessage.getMessageBody();
String messageSource = smsMessage.getOriginatingAddress();
strMessage += "SMS from " + messageSource + " : " + messageBody;
Log.i(AppConstants.DEBUG_TAG, strMessage);
}
}
}
It depends on what you want to test, but it looks like you want to check that the message body and address is correctly parsed and has the expected contents. In that case you can break out that logic into a separate method and unit test it, by passing in a PDU and checking the return value.
If you want to test onReceive, it should be possible to use Mockito, pass in a MockContext and mock Intent's getExtra to return your own test Bundle object. Still, you'll need to verify something in the end. Perhaps you're planning to store the parsed data somewhere later? If so you can use that as your verification point - either by capturing and checking the argument, or verifying that the data was stored (though that's stretching the boundaries of the unit test quite a bit).
In my application i want to get sms/mms from device and display the messages in listview.By using the following code to get the all sms from device.
public void readSmsFromDevice() {
preferences = PreferenceManager
.getDefaultSharedPreferences(BackgroundService.this);
final_msg_time = preferences.getLong("msgtime", 0);
Uri uriSMSURI = Uri.parse("content://sms/");
String[] projection = { "address", "body", "date", "type" };
String where = "date" + ">" + final_msg_time;
Cursor cur = getContentResolver().query(uriSMSURI, projection, where,null, "date");
while (cur.moveToNext()) {
if(ProfileFragment.stop)
{
break;
}else{
try {
//
Message mess1=new Message();
try{
String _id = cur.getString(cur.getColumnIndex("_id"));
mess1.setId(_id);
}catch(Exception e)
{
mess1.setId("null");
}
try{
String number = cur.getString(cur.getColumnIndex("address"));
number = number.replaceAll("[\\W]", "");
if (number.trim().length() > 10) {
mess1.setNumber(number.substring(number.length() - 10,
number.length()));
mess1.setAddress(number.substring(number.length() - 10,
number.length()));
} else {
mess1.setNumber(number);
mess1.setAddress(number);
}
}
catch(Exception e){}
mess1.setBody(cur.getString(cur.getColumnIndex("body")));
String type = cur.getString(cur.getColumnIndex("type"));
Long millisecond = Long.parseLong(cur.getString(cur
.getColumnIndex("date")));
String dateString = DateFormat.format("yyyy/MM/dd hh:mm:ss a",
new Date(millisecond)).toString();
mess1.setDate_millis(millisecond);
mess1.setDate(dateString);
mess1.setType(type);
mess1.setmessagetype("sms");
messages.add(mess1);
} catch (Exception e) {}
}
}
cur.close();
}
By using this method i am getting all sms from device.But my question is how to differenciate group message.In group message one message sent different contact numbers(senders).So in normal message application group message displayed in separate column and single message displayed in separate column.So my application also i have to display the messages like message application.So in this cursor how to identify group message?Is there any column is available to identify group message?So please suggest me how to do taht.Thanks In Advance.....
the thread THREAD_ID column will give you all the messages in the same conversation. You can then use the address column to differentiate the senders of the messages in the group message.
You should also use the Telephony class that was introduced in API 19 instead of the content resolver. https://developer.android.com/reference/android/provider/Telephony.html
I want to match a String sms phone number (incoming sms) to a String Studentno (variable). How can i match and notify popup msg if successful. here's my code:
public void onReceive( Context context, Intent intent )
{
// Get SMS map from Intent
Bundle extras = intent.getExtras();
String messages = "";
String address = "";
String studentsno = "+0999234678";
String no;
if ( extras != null )
{
// Get received SMS array
Object[] smsExtra = (Object[]) extras.get( SMS_EXTRA_NAME );
// Get ContentResolver object for pushing encrypted SMS to incoming folder
ContentResolver contentResolver = context.getContentResolver();
for ( int i = 0; i < smsExtra.length; ++i )
{
SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[i]);
String body = sms.getMessageBody().toString();
address = sms.getOriginatingAddress();
messages += "SMS from " + address + " :\n";
messages += body + "\n";
no = sms.getOriginatingAddress().toString();
// Here you can add any your code to work with incoming SMS
if(no == studentsno){
Toast.makeText( context, "SUCCESS", Toast.LENGTH_LONG ).show();
}
// I added encrypting of all received SMS
putSmsToDatabase( contentResolver, sms );
}
// Display SMS message
Toast.makeText( context, messages, Toast.LENGTH_SHORT ).show();
}
}
This is my problem. how can I match 2 Strings to display popup msg? :
if(no == studentsno){
Toast.makeText( context, "SUCCESS", Toast.LENGTH_LONG ).show();
}
In Java, all strings are objects. When you use the == operator with objects, you are testing whether two objects are the same object.
Because of string interning, strings might be the same object but often not, and you are not able to influence this.
The Java Object class implements an equals method which simply tests if two objects are the same object. Any class which inherits from Object may override this method to provide it's own equality test. string does this by overriding the equals method to test whether two strings (the same object or different objects, it doesn't matter) contain the same content.
Therefore, when testing whether two strings have the same content, you should use string1.equals(string2).
http://en.wikipedia.org/wiki/String_interning
Try
if(no.equals(studentsno))
instead of
if(no == studentsno)
EDIT: Long story short, String.equals() will compare if the values of the given strings are equal (this is what you need in your situation).
== will check if the compare objects are referring to the exact same String object. So even if the comparing Strings have the same value, they are not referring to the same String object.
It appears the true "From" tag of a message sent from an email service ex. 7135192435#tmomail.net has a diffrent "From" tag then what the message details reveal once the message is recieved through SMS. I want to be able to recieve SMS message via tmomail.net but the missing link lies in what exactly the phone sees as the "From" tag.
I have successfully recieved SMS from other cell phones, and my broadcast reciever catches them. However I can not properly set the "From" filter in order to recieve these texts via tmomail.net. Thank you in advance for all nobel android wizards, who may take time from their projects to help. What follows is the code...
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// ---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
Log.d("SMS_Project", "Beginning fired!");
if (bundle != null) {
// ---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
String mFrom = msgs[i].getOriginatingAddress();
String mBody = msgs[i].getMessageBody().toString();
Log.d("SMS_Project", "The From tag follows this line");
if (mFrom.equals("JimJohanson#JollyRanchers.com")) {
Log.d("SMS_Project", "above is the from tag");
if (mBody.indexOf("1") == 0) {
str += "SMS from '" + mFrom + "'";
str += " :";
str += mBody;
str += "\n";
// ---display the new SMS message---
Log.d("SMS_Project", "Toast anyone?");
Toast.makeText(context, str, Toast.LENGTH_LONG).show();
this.abortBroadcast();
}
}
}
}
Log.d("SMS_Project", "No toast yet");}
Manifest Information:
<receiver android:name=".SmsReceiver" >
<intent-filter android:priority="99999999" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
These are my permissions:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
I suspect the propblem to be the phones lack of abilty to translate the email into a legit SMS. Perhaps it is a Multimedia Message type instead? Im going to keep combing the blue nowhere until I get this going. If you have any questions about what I have so far. Please let me know. Thanks.
Im going to try and check via the mFrom string and Log.d. For anyone else encountering this Im
//inserting...
Log.d("SMS_Project", mFrom);
//right above...
(mFrom.equals("JimJohanson#JollyRanchers.com"))
hopefully this will give me an accurate and consistent "from" tag in order to accuratley trap for a result. Can't believe its taken me this long to come up with such a simple test. Tip, learning how to properly debug and utilize LogCat is a neccessity for anyone above a copy/paste pro.
Alright disregard all of my past jaw jacking... The answer to this one is to use the getEmailFrom() function.
Example :
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
String mFrom = msgs[i].getOriginatingAddress();
String mBody = msgs[i].getMessageBody().toString();
String mEmail = msgs[i].getEmailFrom().toString();
*Boolean mSomething = msgs[i].isEmail();*
Log.d("SMS_Project_From", mFrom);
Log.d("SMS_Project_mBody", mBody);
*Log.d("SMS_Project_Email", mEmail);*
This includes the Logcat so that you can identify exactly where the email is from.