I have an application that defines a word and then sends the definition via SMS. The problem is that the user has to type in a phone number. I was thinking that perhaps the app should bring up the contacts list, so the user can select a contact which the user can then send the message to that contact. Here is my code for the SMSActivity:
public class SMSActivity extends Activity
{
String APPTAG = "SMSTransmit";
//Private static strings:
private final static String SENT = "SMS_SENT";
private final static String DELIVERED = "SMS_DELIVERED";
private Button btnSend;
private Button btnExit;
private Button btnClear;
private EditText etPhoneNumber;
private EditText etUserMessage;
//Private BroadcastReceiver member variables:
private SMSDispatchReceiver sendReceiver = null;
private SMSReceiptReceiver receiptReceiver = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms);
Bundle extras = getIntent().getExtras();
String definiedWord = null;
if (extras != null)
{
definiedWord = extras.getString("DEFINITION");
}
else
{
definiedWord = "None";
}
Log.d("recievedAGAIN", definiedWord);
Log.v(APPTAG, "MainActivity: onCreate() called");
//Create a new broadcast receiver for sending the SMS
sendReceiver = new SMSDispatchReceiver();
//Create a new broadcast receiver for receipt of the send SMS
receiptReceiver = new SMSReceiptReceiver();
//Register the new receivers (as new IntentFiler() objects):
registerReceiver(sendReceiver, new IntentFilter(SENT));
registerReceiver(receiptReceiver, new IntentFilter(DELIVERED));
//Get the view objects:
btnSend = (Button) findViewById(R.id.btnSend);
btnClear = (Button) findViewById(R.id.btnClear);
btnExit = (Button) findViewById(R.id.btnExit);
etPhoneNumber = (EditText) findViewById(R.id.etNumber);
etUserMessage = (EditText) findViewById(R.id.etMessage);
//Disable the soft keyboard (this is only in general):
InputMethodManager inMethodMgr = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inMethodMgr.hideSoftInputFromInputMethod(etPhoneNumber.getWindowToken(), 0);
inMethodMgr.hideSoftInputFromInputMethod(etUserMessage.getWindowToken(), 0);
//Set the hint for the EditText boxes:
etPhoneNumber.setHint("Enter phone number (Default = 5556)");
etUserMessage.setHint(definiedWord);
//Create an click event listener for the Send button (OnClickListener):
btnSend.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String strMessage = null;
String strNumber = null;
//Get the phone number from the EditText box:
strNumber = etPhoneNumber.getText().toString();
//Check the phone number:
if (strNumber.length() <= 0)
{
//No phone number, then get the default (5556):
strNumber = SMSProperties.getPhoneNumber();
}
//Get the message from the EditText box:
strMessage = etUserMessage.getText().toString();
//Check the message contains some content:
if (strMessage.length() > 0)
{
//Sent the SMS to the phone number
sendSMS(strNumber, strMessage);
} else
{
//Warn the user and reset the focus / hint:
Toast.makeText(getBaseContext(), "No message text! Please enter some text for the SMS!!", Toast.LENGTH_SHORT).show();
etUserMessage.setHint("Enter message text here . . . ");
etUserMessage.requestFocus();
}
}
});
//Create an click event listener for the Clear button (OnClickListener):
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Clear the appropriate EditText box:
if (etUserMessage.isFocused()) {
//Clear the text in the user message EditText box:
etUserMessage.setText("");
//Set the hint in the user message EditText box:
etUserMessage.setHint("Enter message text here . . . ");
} else if (etPhoneNumber.isFocused()) {
//Clear the text in the phone number EditText box:
etPhoneNumber.setText("");
//Set the hint in the phone number EditText box:
etPhoneNumber.setHint("Enter phone number (Default = 5556)");
}
}
});
//Create an click event listener for the Exit button (OnClickListener):
btnExit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Finish the activity:
//NOTE: As this is the main activity it will cause onDestroy() to be called!
finish();
}
});
}
//Method to send an SMS message to another device:
private void sendSMS(String strNum, String strMsg)
{
//TODO: Create a pending intent for the SMSDistatchReceiver (SENT):
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent("SENT"), 0);
//TODO: Create a pending intent for the SMSReceiptReceiver (DELIVERED):
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent("DELIVERED"), 0);
//Get a default SmsManager object:
SmsManager smsMgr = SmsManager.getDefault();
//TODO: Send the SMS using the SmsManager:
smsMgr.sendTextMessage(strNum, null, strMsg, sentPI, deliveredPI);
}
consider contact is a button to bring up the contact list
contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View g) {
Intent q = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(q, 1001);
}
});
and to handle the result (which is referenced by 1001) use this:
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
// getting the URI from result for further working
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String id =c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String hasPhone =c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1")) {
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,
null, null);
phones.moveToFirst();
//this string will hold the contact number
String cNumber = phones.getString(phones.getColumnIndex("data1"));
//this string will hold the contact name
String cName = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
}
}}
}
Related
I've been working on this app that collects information, then sends it in email form. All of my other EditTexts are working with the exception of the very first one, pilot (the hint is name, as in the name of the pilot). I've gone through this thoroughly for multiple hours but I just cant seem to find what is the problem. The only reason I know its null is because when it goes into the email format all it says is null
public class InfoSheet extends AppCompatActivity {
private double VesselUnits;
private EditText pilot, ship, to, from, LOA, MBDTH, CUSD, zone1, zone2, CallSign;
private Spinner agent_spinner;
private Button btnSubmit;
private String date, agent, Spilot, Sship, Sto, Sfrom, Szone1, Szone2, SCallSign, SVesselUnits;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info_sheet);
date=getTodaysDate();
addListenerOnButton();
}
public void collectNCalc(){
//grab all of our info
agent_spinner = (Spinner) findViewById(R.id.agent_spinner);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
pilot = (EditText) findViewById(R.id.Pilot);
ship = (EditText) findViewById(R.id.ship);
to = (EditText) findViewById(R.id.to);
from = (EditText) findViewById(R.id.from);
LOA = (EditText) findViewById(R.id.LOA);
MBDTH = (EditText) findViewById(R.id.MBDTH);
CUSD = (EditText) findViewById(R.id.CUSD);
zone1 = (EditText) findViewById(R.id.zone1);
zone2 = (EditText) findViewById(R.id.zone2);
CallSign = (EditText) findViewById(R.id.CallSign);
//convert what we need to int to do equations
String sLOA = LOA.getText().toString();
double intLOA = Integer.valueOf(sLOA);
intLOA = intLOA*3.281;
String sMBDTH = MBDTH.getText().toString();
double intMBDTH = Integer.valueOf(sMBDTH);
intMBDTH = intMBDTH*3.281;
String sCUSD = CUSD.getText().toString();
double intCUSD = Integer.valueOf(sCUSD);
intCUSD = intCUSD*3.281;
VesselUnits = intLOA*intMBDTH*intCUSD;
VesselUnits = VesselUnits/10000;
Spilot=pilot.getText().toString();
Sship=ship.getText().toString();
Sto=to.getText().toString();
Sfrom=from.getText().toString();
Szone1=zone1.getText().toString();
Szone2=zone2.getText().toString();
SCallSign=CallSign.getText().toString();
agent=agent_spinner.getSelectedItem().toString();
//SVesselUnits=String.valueOf(VesselUnits);
}
public void addListenerOnButton() {
final Context context2 = this;
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i2 = new Intent(context2, DigitalSignature.class);
//do the Calc
collectNCalc();
//pass to next activity
i2.putExtra("Pilot",Spilot);
i2.putExtra("ship",Sship);
i2.putExtra("to",Sto);
i2.putExtra("from",Sfrom);
i2.putExtra("zone1",Szone1);
i2.putExtra("zone2",Szone2);
i2.putExtra("callsign",SCallSign);
i2.putExtra("agent",agent);
i2.putExtra("vessleunits",VesselUnits);
i2.putExtra("date",date);
startActivity(i2);
}
});
}
its sent to the next and final activity:
public class DigitalSignature extends AppCompatActivity {
String pilot, ship, to, from, zone1, zone2, CallSign, agent, date;
Toolbar toolbar;
Button btn_get_sign, mClear, mGetSign, mCancel, btn_send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_digital_signature);
Bundle extras = getIntent().getExtras();
if (extras != null) {
pilot = extras.getString("pilot");
ship = extras.getString("ship");
to = extras.getString("to");
from = extras.getString("from");
zone1 = extras.getString("zone1");
zone2 = extras.getString("zone2");
CallSign = extras.getString("callsign");
agent = extras.getString("agent");
vesselUnit = extras.getDouble("vesselunits");
date = extras.getString("date");
}
btn_send.setOnClickListener(new OnClickListener() {
public void onClick(View v){
Uri path = Uri.parse("file://" + file);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_TEXT, pilot+"\n"+ship+"\n"+to+"\n"+from+"\n"+zone1+"\n"+zone2+"\n"+CallSign+"\n"+agent+"\n"+vesselUnit);
// set the type to 'email'
emailIntent.setType("image/png");
String to[] = {"metropilottickets#gmail.com"};
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
// the attachment
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
// the mail subject
emailIntent.putExtra(Intent.EXTRA_SUBJECT, pilot+"'s Ticket for "+ship);
startActivity(Intent.createChooser(emailIntent , "Send email..."));
}
});
}
I left out a lot of the other code that's irrelevant to my question, but if anyone can point out why I'm getting null you'd be a life saver!
You need to use extras.getString("Pilot");
insteadof extras.getString("pilot");
I just found out my app doesn't capable of sending more than 160 characters at a time. it works fine on characters less than 160. when I try to send more than 160 characters at a time. it display "messages sent" toast but message doesn't going anywhere what should I change to send more than 160 characters.
thank you
here is the code
public class MainActivity7 extends ActionBarActivity {
String value ;
Button button;
TextView editext2;
TextView editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity7);
editText = (TextView) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
editext2 = (TextView) findViewById(R.id.editText2);
Intent a = getIntent();
editText.setText(a.getStringExtra("item") );
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendSMSMessage();
}
});
}
private void sendSMSMessage() {
Log.i("Send SMS", "");
String phoneno = editext2.getText().toString();
String message = editText.getText().toString();
try{
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneno,null,message,null,null);
Toast.makeText(getApplicationContext(),"sms sent.",
Toast.LENGTH_LONG).show(); }
catch (Exception e){
Toast.makeText(getApplicationContext(),
"sms failed,please try again",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
To send more than 160 characters in SMS you need to send it as a multiple SMS.
SmsManager sm = SmsManager.getDefault();
ArrayList<String> parts =sm.divideMessage(LONG_TEXT);
int numParts = parts.size();
ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>();
ArrayList<PendingIntent> deliveryIntents = new ArrayList<PendingIntent>();
for (int i = 0; i < numParts; i++) {
sentIntents.add(PendingIntent.getBroadcast(getContext(), 0, mSendIntent, 0));
deliveryIntents.add(PendingIntent.getBroadcast(getContext(), 0, mDeliveryIntent, 0));
}
sm.sendMultiPartTextMessage(mDestAddr,null, parts, sentIntents, deliveryIntents);
In my application,i have created an edit-text view and three buttons. When user clicks on "Add More Contacts" button, it will add another edit-text view and when user clicks "Add Contact" this will take him to contacts of phone-book from where he can choose the contacts to which he wants to send the SMS. I have written program for all this but i don't know how to send message to all users automatically without the user confirmation when he just pressed the "Send Message"Button. I tried SMSManager but its depreciated.Please suggest me.
public class MainActivity extends Activity {
private Button btn_cntct;
public int REQUESTCODE = 1;
private LinearLayout layoutLinear;
private Button btn_addmore_cntct;
private int id = 1;
Button b_alert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// defining button elements for picking contacts from phone-book
btn_cntct = (Button) findViewById(R.id.bpickperson);
btn_cntct.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// using Intent for fetching contacts from phone-book
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, REQUESTCODE);
}
});
// defining button and edit-text values for adding mutli edit-texts
// views
layoutLinear = (LinearLayout) findViewById(R.id.mLayout);
btn_addmore_cntct = (Button) findViewById(R.id.baddmorecontacts);
btn_addmore_cntct.setOnClickListener(OnClick());
EditText editview = new EditText(this);
editview.setText("Add more");
}
// implementing OnClickListener OnClick() method for "btn_addmore_cntct"
// button
private OnClickListener OnClick() {
// TODO Auto-generated method stub
// changing return type "null" to "new OnClickListner"
return new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final EditText tab = new EditText(getApplicationContext());
tab.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
// setting id for edit-text views
tab.setId(id);
// and increment
id++;
// adding (0) to display edit-text view on the top
layoutLinear.addView(tab, 0);
tab.requestFocus();
// for sending sms
b_alert = (Button) findViewById(R.id.balert);
b_alert.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String smsNumber = tab.getText().toString();
String smsText = "I am in danger";
Uri uri = Uri.parse("smsto:" + smsNumber);
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", smsText);
startActivity(intent);
}
});
}
};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// calling onActivityResult when contacts has been selected from the
// phone-book, giving back the REQUESTCODE i started it with, the RC it
// returned with
// any additional data from it.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
Uri uri = data.getData();
Log.i("data", uri.toString());
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver()
.query(uri,
new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String name = c.getString(0);
String number = c.getString(1);
int type = c.getInt(2);
showSelectedNumber(name, number, type);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
// defining showSelectedNummber to display selected contact from phone-book
// to Edit-Text View
public void showSelectedNumber(String name, String number, int type) {
if (layoutLinear == null) {
Log.i("layoutLinear is null", "null");
} else {
Log.i("layoutLinear is not null", "not null");
}
EditText userNumber = (EditText) layoutLinear.getChildAt(0);
if (userNumber == null) {
Log.i("edittext is null", "null");
} else {
Log.i("edittext is not null", "not null");
}
String typeNumber = (String) ContactsContract.CommonDataKinds.Phone
.getTypeLabel(getResources(), type, "");
userNumber.setText(name + ": " + number + " " + typeNumber);
}
}
You this with loop of Numbers you need to send
SmsManager.getDefault().sendTextMessage("NUMBER",
null, "TEXT_TO_SEND", null, null);
I need a little or much help here.
I created a fragment that takes a photo and passes it as an attachment on the email that I send.
The fragment works but it has some bugs, please take a look:
I tried almost every code and example to take a photo and manage to put it on an imageview but in vain it does not work, because I have a samsung mobile and samsung mobiles work different. So I copied onActivityResult method from another guy's tutorial.(If there is a simpler please way be my guest)
The application crashes when I try to send the email for a second time. The first time when I press the send button it sends the email, but when I press it again, it crashes.
For a weird reason the email works only with the gmail application that I have installed on my samsung. I have another mail client (the default) but when I choose it, the app crashes.
I use onsavedinstansestate but when rotate the device, again, the app crashes.
I believe that my questions 2 and 4 are a matter of the saveInstancestate because if on every refresh of the fragment, everything is reset (imageviews etc).
Here I write my contact fragment, kindly take a look
public class contact extends Fragment {
private String dataImported;
private TextView txt;
private ImageView imgThumbNail;
private Bitmap bmap;
String mCurrentPhotoPath;
private static final int CAMERA_IMAGE_CAPTURE = 0;
private static final int EMAIL_SEND = 1;
private Uri uriThumbnailImage;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Save the thumbnail
if (uriThumbnailImage != null){
imgThumbNail.buildDrawingCache();
bmap = imgThumbNail.getDrawingCache();
outState.putParcelable("savedImage", bmap);
}
}
private void dispatchTakePictureIntent(){
Intent TakePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(TakePictureIntent, CAMERA_IMAGE_CAPTURE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.e(getTag(), "onCreateView 3");
txt = (TextView) getActivity().findViewById(R.id.txt_fragment3);
imgThumbNail = (ImageView) getActivity().findViewById(R.id.imageThumbnail);
if (container == null){
return null;
}
return inflater.inflate(R.layout.fragment3_layout,
container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
txt = (TextView) getActivity().findViewById(R.id.txt_fragment3);
Log.e(getTag(), "onActivityCreated 3");
if ((savedInstanceState != null) && (savedInstanceState.getParcelable("savedImage") != null))
{
bmap = (Bitmap) savedInstanceState.getParcelable("savedImage");
System.out.println(bmap);
imgThumbNail = (ImageView) getActivity().findViewById(R.id.imageThumbnail);
imgThumbNail.setImageBitmap(bmap);
}
//create onClickListener for the email
email();
//create onClickListener for the photo
takephoto();
if (this.dataImported == null)
txt.setText("Στείλτε μας την δικιά σας γλυκιά συνταγή!");
else
txt.setText(this.dataImported);
}
private void takephoto() {
ImageButton btnTakePhoto =(ImageButton) getActivity().findViewById(R.id.btn_takePhoto);
btnTakePhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_IMAGE_CAPTURE)
{
// Describe the columns you'd like to have returned. Selecting from the Thumbnails
String[] projection = {
MediaStore.Images.Thumbnails._ID, //The columns we want
MediaStore.Images.Thumbnails.IMAGE_ID,
MediaStore.Images.Thumbnails.KIND,
MediaStore.Images.Thumbnails.DATA
};
String selection = MediaStore.Images.Thumbnails.KIND + "=" + MediaStore.Images.Thumbnails.MINI_KIND;
String sort = MediaStore.Images.Thumbnails._ID + " DESC";
#SuppressWarnings("deprecation")
Cursor myCursor = getActivity().managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, selection, null, sort);
long imageId = 01;
long thumbnailImageId = 01;
String thumbnailPath = "";
try{
myCursor.moveToFirst();
imageId = myCursor.getLong(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.IMAGE_ID));
thumbnailImageId = myCursor.getLong(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID));
thumbnailPath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
}finally{myCursor.close();}
//Create new Cursor to obtain the file Path for the large image
String[] largeFileProjection = {
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA
};
String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
myCursor = getActivity().managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, largeFileProjection, null, null, largeFileSort);
String largeImagePath = "";
try{
myCursor.moveToFirst();
//This will actually give the file path location of the image.
largeImagePath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
}finally{myCursor.close();}
// These are the two URI's you'll be interested in. They give a handle to the actual images
Uri uriLargeImage = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(imageId));
uriThumbnailImage = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, String.valueOf(thumbnailImageId));
//I connect image to the imageView and show it on the screen
imgThumbNail = (ImageView) getActivity().findViewById(R.id.imageThumbnail);
imgThumbNail.setImageURI(uriThumbnailImage);
}//if
}
private void email() {
final EditText onomaSintagis = (EditText) getActivity().findViewById(R.id.txt_onomaSintagis_send);
final EditText onomaPelati = (EditText) getActivity().findViewById(R.id.txt_CustomerName_send);
final EditText sintagiPelati = (EditText) getActivity().findViewById(R.id.txt_Sintagi_send);
ImageButton btnSendEmail =(ImageButton) getActivity().findViewById(R.id.btn_sendEmail);
btnSendEmail.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Send email", "");
String[] TO = {"info#urweb.eu"};
String[] BCC = {"t.itzaris#gmail.com"};
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("message/rfc822");
emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
emailIntent.putExtra(Intent.EXTRA_BCC, BCC);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Αποστολή Συνταγής:"+onomaSintagis.getText()+" Από τον/την:"+onomaPelati.getText());
emailIntent.putExtra(Intent.EXTRA_TEXT, sintagiPelati.getText());
//I get the uriThumbnailImage(path of the photo) and i put it on the intent
Uri uri = Uri.parse(uriThumbnailImage.toString());
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
try{
startActivityForResult(Intent.createChooser(emailIntent, "Send mail..."), EMAIL_SEND);
}catch(android.content.ActivityNotFoundException ex){
Toast.makeText(getActivity(), "Sorry, There is no email application installed.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Use Custom camera, it can provide a more compelling experience for your users with special features. check this
http://developer.android.com/guide/topics/media/camera.html#custom-camera
For tutorial
http://capycoding.blogspot.in/2012/06/custom-camera-application.html
and send the saved file as an attachment using path.
From the given ListView in picture, I select the contact to send sms and move to another activity (second picture). And from this sms Activity picture. When I press back hardware button available on phone, I should move where I want. I don't want a default Activity to be displayed. How can I do this?
public class SendSms extends Activity{
ListView listView;
List<RowItems> rowItems;
CustomListViewAdapter adapter;
String toNumbers = "";
String separator;
int i=0,j,count=0,count1; String a[]=new String[5];
String number,val2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new4);
listView = (ListView) findViewById(R.id.list);
rowItems = new ArrayList<RowItems>();
val2=getIntent().getStringExtra("name");
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String rawContactId = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
Cursor c = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.Phone.NUMBER,
// ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.PHOTO_ID
}, ContactsContract.Data.RAW_CONTACT_ID + "=?", new String[] { rawContactId }, null);
if (c != null) {
if (c.moveToFirst()) {
String number = c.getString(0);
//int type = c.getInt(1);
String name = c.getString(1);
int photoId = c.getInt(2);
Bitmap bitmap = queryContactImage(photoId);
RowItems p=new RowItems(bitmap, number, name);
rowItems.add(p);
}
adapter = new CustomListViewAdapter(this,
R.layout.new5, rowItems);
listView.setAdapter(adapter);
c.close();
}
}
}
}
private Bitmap queryContactImage(int imageDataRow) {
Cursor c = getContentResolver().query(ContactsContract.Data.CONTENT_URI, new String[] {
ContactsContract.CommonDataKinds.Photo.PHOTO
}, ContactsContract.Data._ID + "=?", new String[] {
Integer.toString(imageDataRow)
}, null);
byte[] imageBytes = null;
if (c != null) {
if (c.moveToFirst()) {
imageBytes = c.getBlob(0);
}
c.close();
}
if (imageBytes != null) {
return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
} else {
return null;
}
}
public void showResult(View v) {
// String result = "";
String result1="";
for (RowItems p : adapter.getBox()) {
if (p.chck){
// result += "\n" + p.getTitle();
result1 +="\n" +p.getDesc();
a[i]=p.getTitle();
i++;
count++;
}
count1=count;
}
Toast.makeText(this, result1+"\n", Toast.LENGTH_LONG).show();
}
public void send(View v) throws IOException {
int value=a.length-count1;
for(j=0;j<a.length-value;j++){
if(android.os.Build.MANUFACTURER.equalsIgnoreCase("Samsung")){
separator = ",";
} else
separator = ";";
number = a[j];
toNumbers= toNumbers +number +separator;
}
toNumbers = toNumbers.substring(0, toNumbers.length());
Uri sendSmsTo = Uri.parse("smsto:" + toNumbers);
String smsValue = "help iam in danger..i am presently at \n"+val2;
if(val2==null){
Toast.makeText(SendSms.this, "wait.....", Toast.LENGTH_LONG).show();
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("vnd.android-dir/mms-sms");
intent.putExtra("sms_body", smsValue);
intent.setData(sendSmsTo);
startActivity(intent);
}
Use startAtctivityForResult, and in onActivityResult check the resultCode. If it is Activity.RESULT_CANCELLED, the user 'backed out' of the SMS activity. Due to the implementation of the SMS activity being outside of your control, this might not be the only case when the result code says it has been cancelled.
I think you should, when the Activity picture is displayed, try to call the onBackPressed method.
// back button pressed method
#Override
public void onBackPressed() {
super.onBackPressed();
// new intent to call an activity that you choose
Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);
// finish the activity picture
this.finish();
}
If you don't want to call an external Activity, you can hide the layout calling by the Intent as below:
// back button pressed method
#Override
public void onBackPressed() {
super.onBackPressed();
// your layout with the picture is displayed, hide it
if(MySecondView.getVisibility() == View.VISIBLE)
MySecondView.setVisibility(View.Gone);
// display the layout that you want
MyDefaultView.setVisibility(View.VISIBLE);
}
As I said below, try with a boolean that you initialize to false at the beginning of your Class. When you start the Intent.ACTION_VIEW, make this boolean to true:
public class Foo extends Activity {
private boolean isSms = false;
// some stuff
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("vnd.android-dir/mms-sms");
// ...
startActivity(intent);
// make your boolean to true
isSms = true;
// create the onBackPressed method
#Override
public void onBackPressed() {
// check if the user is on the sms layout
if(isSms)
// do something
else
// do something else like finish(); your activity
}
}
Or you can try to use the onKeyDown method (see here: onKeyDown (int keyCode, KeyEvent event)) as below:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0) {
// dome some stuff
return true;
}
return super.onKeyDown(keyCode, event);
}
You can see the diffence between these two methods here: onBackPressed() not working and on the website that I talk in the comments below.
Hope this will be useful.
UPDATE:
A better way should make an startActivityForResult to start the Intent.ACTION_VIEW:
startActivityForResult(intent, 1);
And then, you return the cancel code like this:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode != 1 && resultCode == RESULT_CANCELED) {
// do something
}
}
This is #FunkTheMonk, just above, who tells the good choice!
Add this method to the class to handle device back button.
#Override
public void onBackPressed() {
// do something
}
Please note that it requires API Level 5 or higher.
You have to overide go back behaviour of hardware back button by calling a method name onbackpressed();
#Override
public void onBackPressed() {
super.onBackPressed();
// set intent to activity where you want to move on after back press
Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);
// also clean the current activity from stack.
youractivityname.this.finish();
}