How to respond to 'attach' from Gmail? Responding to intent with attachment - android

I am writing an android application. This app is built on top of Gmail. I want to add the ability to attach files from other apps. The first app I am working on doing this with is a custom Box app (made with the box sdk). I can currently send an intent, open an activity in the Box app, pick an attachment, and return. However, in my Box-SDK app, once an item is selected, I have no idea how to turn it into data that I can properly send back to my Gmail app (or any original sender of the intent). I also do not know how to send that data back to the originator of the intent.
I know setResult() is involved, but I am not sure where to put it or how to properly use it to carry the data chosen in box into the email app.
What's currently happening is it just goes back into gmail without an attachment and says that the download has finished.
Here is the code I currently have:
private void onFileSelected(final int resultCode, final Intent data) {
if (Activity.RESULT_OK != resultCode) {
Toast.makeText(this, "fail", Toast.LENGTH_LONG).show();
}
else {
final BoxAndroidFile file = data.getParcelableExtra(FilePickerActivity.EXTRA_BOX_ANDROID_FILE);
AsyncTask<Null, Integer, Null> task = new AsyncTask<Null, Integer, Null>() {
#Override
protected void onPostExecute(Null result) {
Toast.makeText(MainActivity.this, "done downloading", Toast.LENGTH_LONG).show();
// Intent result2 = new Intent();
// result2.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + ));
// setResult(Activity.RESULT_OK, result2);
//// setResult(resultCode, data);
super.onPostExecute(result);
finish();
}
#Override
protected void onPreExecute() {
Toast.makeText(MainActivity.this, "start downloading", Toast.LENGTH_LONG).show();
super.onPreExecute();
}
#Override
protected Null doInBackground(Null... params) {
BoxAndroidClient client = ((HelloWorldApplication) getApplication()).getClient();
try {
File f = new File(Environment.getExternalStorageDirectory(), file.getName());
Intent result2 = new Intent();
result2.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + f.getAbsolutePath()));
setResult(Activity.RESULT_OK, data);
// setResult(resultCode, data);
System.out.println(f.getAbsolutePath());
client.getFilesManager().downloadFile(file.getId(), f, null, null);
}
catch (Exception e) {
}
return null;
}
};
task.execute();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == AUTH_REQUEST) {
onAuthenticated(resultCode, data);
}
else if (requestCode == UPLOAD_REQUEST) {
onFolderSelected(resultCode, data);
}
else if (requestCode == DOWNLOAD_REQUEST) {
onFileSelected(resultCode, data);
}
}

Try using a file provider:
https://developer.android.com/reference/android/support/v4/content/FileProvider.html#ServeUri
From the page:
"There are a variety of ways to serve the content URI for a file to a client app. One common way is for the client app to start your app by calling startActivityResult(), which sends an Intent to your app to start an Activity in your app. In response, your app can immediately return a content URI to the client app or present a user interface that allows the user to pick a file. In the latter case, once the user picks the file your app can return its content URI. In both cases, your app returns the content URI in an Intent sent via setResult()"
From another stackoverflow answer:
public void showCameraScreen(View view) {
// BUILT IN CAMERA
Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
camera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(this)) );
this.startActivityForResult(camera, 1);
}
private File getTempFile(Context context) {
// it will return /sdcard/MyImage.tmp
final File path = new File(Environment.getExternalStorageDirectory(), context.getPackageName());
if (!path.exists()) {
path.mkdir();
}
return new File(path, "MyImage.tmp");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
final File file = getTempFile(this);
byte[] _data = new byte[(int) file.length()];
try {
InputStream in = new FileInputStream(file);
in.read(_data);
in.close();
in = null;
//DO WHAT YOU WANT WITH _data. The byte array of your image.
} catch (Exception E) {
}
}
}
We can modify this code, where it says //Do What you want with the _data, just call
public final void setResult (int resultCode, Intent data)

Related

How can I send back the captured image taken from second activity back to the main activity?

This is my code from the main activity class named Account class wherein when I press the add entry button it will navigate to the next activity which is the AddEntry class
//ADD ENTRY BUTTON
accountBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Account.this, AddEntry.class);
startActivityForResult(intent,REQUEST_CODE_ADD);
}
});
After it goes to the second activity which is the AddEntry class, a picture would be captured using the user's camera when the ImageView named entryPhoto is clicked
entryPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent takePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File tempImage = null;
try {
tempImage = createImage();
} catch (Exception e) {
e.printStackTrace();
}
if (tempImage != null){
Uri uriImage = FileProvider.getUriForFile(c,"com.example.login.fileprovider",
tempImage);
mCurrentPhotoUri = uriImage;
takePhoto.putExtra(MediaStore.EXTRA_OUTPUT,uriImage);
if (ContextCompat.checkSelfPermission(c, Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(AddEntry.this,
new String[]{Manifest.permission.CAMERA},
REQ_CODE_CAMERA);
}
else {
startActivityForResult(takePhoto,REQ_CODE_TAKE_PHOTO);
}
}
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQ_CODE_TAKE_PHOTO && resultCode == RESULT_OK) {
entryPhoto.setImageURI(mCurrentPhotoUri);
}
Here is the code where I put all the the information inputted by user then send it back to the main activity. In the addPhoto is where I am supposed to put the image to be passed. I only tried passing an image from my drawable because I really don't know how to pass the image captured.
Intent data = new Intent();
data.putExtra("addPhoto",R.drawable.anonymous);
data.putExtra("addName", entryName.getText().toString());
data.putExtra("addRemark", entryRemark.getText().toString());
data.putExtra("addBirthday", entryBirthday.getText().toString());
data.putExtra("addAddress", entryAddress.getText().toString());
data.putExtra("addGender", selectedGender);
data.putExtra("addContactNo", entryContactNo.getText().toString());
data.putExtra("addHobbies", entryHobbies.getText().toString());
data.putExtra("addOtherInfo", entryOtherInfo.getText().toString());
setResult(RESULT_OK,data);
finish();
And this is the code in the onActivityResult in the main activity
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data); //ONACTRESULT OF ADD ENTRY
if (requestCode == REQUEST_CODE_ADD && resultCode == RESULT_OK){
int addPhoto = data.getIntExtra("addPhoto",1);
String addName = data.getStringExtra("addName");
String addRemark = data.getStringExtra("addRemark");
String addBirthday = data.getStringExtra("addBirthday");
String addAddress = data.getStringExtra("addAddress");
String addContactNo = data.getStringExtra("addContactNo");
String addGender = data.getStringExtra("addGender");
String addHobbies = data.getStringExtra("addHobbies");
String addOtherInfo = data.getStringExtra("addOtherInfo");
entryList.add(0,new Entry(addPhoto,addName,addRemark,addBirthday,addGender,addAddress,addContactNo,addHobbies,addOtherInfo));
myAdapter.notifyDataSetChanged();
}
Please I hope you will help me. I am still a beginner but I really want to be good at programming. Thank you in advance.
I think you can pass the Uri directly in bundle of Intent as it extends Parcelable which means it can retrieved as is
Adding
data.putExtra("addPhoto", mCurrentPhotoUri);
Retrieving
Uri photoUri = getIntent().getParcelableExtra<Uri>("addPhoto");

New activity after camera intent

i have:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foto);
Intent intentFotocamera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); //creo un timestamp univoco
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs(); //creo un nuovo album
File image = new File(imagesFolder, "QR_" + timeStamp + ".png"); //concateno
Uri uriSavedImage = Uri.fromFile(image);
intentFotocamera.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(intentFotocamera, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
Now, when the user presses the photo confirmation button (and then is saved locally) I would like to create a new activity because I want to print this photo in my app.
How do I create new activity?
In the override method onActivityResult() start the new activity.
https://developer.android.com/training/basics/intents/result.html
Example:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
// Check which request we're responding to
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
// Do something with the contact here (bigger example below)
}
}
}
Do you want to open new activity and show the photo which is taken recently?
Here is how you can do it.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
"handle here"
}
} catch (Exception ex) {
}
}

How can I get the URI with a custom camera in Android?

I'm switching from using the default camera to finally growing a pair and deciding to make a custom camera. It's only showing me how much I don't fully understand.
Here is basically way I have been doing things in the main activity as far as photos go, but it will no longer work:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == PICK_PHOTO_REQUEST) {
if (data == null) {
Toast.makeText(this, "General Error!", Toast.LENGTH_LONG).show();
}
else {
mMediaUri = data.getData();
}
Log.i(TAG, "Media URI: " + mMediaUri);
}
else {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(mMediaUri);
sendBroadcast(mediaScanIntent);
}
(...)
Here is the picture saving function along with a couple others of the new camera:
(...)
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.d("Picture taken");
String path = savePictureToFileSystem(data);
setResult(path);
finish();
}
private static String savePictureToFileSystem(byte[] data) {
File file = getOutputMediaFile();
saveToFile(data, file);
return file.getAbsolutePath();
}
private void setResult(String path) {
Intent intent = new Intent();
intent.putExtra(EXTRA_IMAGE_PATH, path);
setResult(RESULT_OK, intent);
}
*Credit to Paul Blundell
(...)
What do I need to do so that the main activity can receive the image's URI in the onactivityresult instead of the path String? Are URIs even applicable when it comes to custom cameras?
Please and thanks.
You use custom camera, but want to do it via Intent? OK, you have the absolute file path in
String abspath = data.getExtras().getString(EXTRA_IMAGE_PATH);
mMediaUri = Uri.fromFile(new File(abspath));

Android photo cature error

I am trying to capture camera photo in may app...
this is what I have:
The photo is saved but on the on Activity Result, I get Null point Exception.
What could I be possible missing out?
private Uri getImgUri() {
File filePath= new File(Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_PICTURES),APP_ALIAS);
if(!filePath.exists()){
if(!filePath.mkdirs())
return null;
}
String timeStamp= new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String path=filePath.getPath()+File.separator+"_IMG"+timeStamp+".jpg";
File file=new File(path);
return Uri.fromFile(file);
}
private void startGetPicFromCam() {
Intent intent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri uri= getImgUri();
intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
startActivityForResult(intent,MEDIA_CAPTURE_RESULT_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
if(requestCode==MEDIA_CAPTURE_RESULT_CODE){
if(resultCode==RESULT_OK){
try{
if(data.getData()!=null)
Toast.makeText(this,"saved to "+data.getData(),Toast.LENGTH_LONG).show();
else
Toast.makeText(this,"saved to path",Toast.LENGTH_LONG).show();
}
catch(Exception e){
Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG).show();
}
}
}
}
Edit, it appears I didn't read your question close enough. It appears that the issue is that when you use EXTRA_OUTPUT, a null intent is passed back. If you want to get access to your data, just query the file that you passed in as an extra. See this and this question for more detailed information.

Null Pointer exception while uploading images from a camera in Android

This is my current code:
public void onClick(View v) {
final Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
final Intent gallIntent=new Intent(Intent.ACTION_GET_CONTENT);
gallIntent.setType("image/*");
final Intent camIntent = new Intent("android.media.action.IMAGE_CAPTURE");
pickIntent.putExtra(Intent.EXTRA_INTENT, camIntent);
pickIntent.putExtra(Intent.EXTRA_INTENT, gallIntent);
pickIntent.putExtra(Intent.EXTRA_TITLE, "Select Source");
startActivityForResult(pickIntent, 0);
if (bitmap == null) {
Toast.makeText(getApplicationContext(),
"Please select image", Toast.LENGTH_SHORT).show();
} else {
dialog = ProgressDialog.show(CreatePod.this, "Uploading",
"Please wait...", true);
//new ImageUploadTask().execute();
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
Toast toast = Toast.makeText(this,"camera cancelled", 10000);
toast.show();
return;
}
// lets check if we are really dealing with a picture
if (requestCode == 0 && resultCode == RESULT_OK)
{
Bundle extras = data.getExtras();
Bitmap b = (Bitmap) extras.get("data");
//setContentView(R.layout.main);
imgView.setImageBitmap(b);
// save image to gallery
String timestamp = Long.toString(System.currentTimeMillis());
MediaStore.Images.Media.insertImage(getContentResolver(), b, timestamp, timestamp);
}
}
This gives the options Gallery and Camera(Actually, it shows an unsupported device in the place of camera. If I click on it, it gives NullPointerException and crashes. Is this the right way to do it? Or should I use PackageManger? If Yes, then how?
Looking of your code, I think you have a lack of basic android knowledge,
Miss-use of onActivityResult(), its a method of Activity class, take out it from onClick()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
}
Just check basic android activity's method and how to use them.
Update:
Look at Android-Activity

Categories

Resources