I'm using ACTION_IMAGE_CAPTURE with a predetermined target Uri pretty much as suggested in the documentation. However, when I try to decode the image immediately after my activity gets it, decodeStream() fails. If I try it again a few seconds later, it works fine. I suppose the file is being written asynchronously in the background. How can I find out when it's available for use?
Here are the key parts of my code:
Determining the target file name:
String filename = String.format("pic%d.jpg", new Date().getTime());
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), filename);
try {
file.createNewFile();
} catch (IOException e) {
file = new File(context.getFilesDir(), filename);
}
targetUri = Uri.fromFile(photoFile);
Taking the picture:
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, targetUri);
fragment.startActivityForResult(takePictureIntent, RESULT_TAKE_PICTURE);
In onActivityResult():
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
// Note that data.getData() is null here.
InputStream is = getContentResolver().openInputStream(targetUri);
if (is != null) {
Bitmap bm = BitmapFactory.decodeStream(is);
decodeStream returns null. If I make the same call again a few seconds later, it succeeds. Is there anything that tells me when the file is available?
UPDATE: Following greenapps' suggestion, I'm doing a decodeStream call with inJustDecodeBounds first to get the dimensions to see if it's a memory issue. Turns out this first bounds-only decode pass fails, but now the actual decodeStream call that immediately follows succeeds! If I then do both again, they both succeed!
So it seems like the first call to decodeStream always fails, and all the others after that are good, even if they happen immediately afterwards (=within the same method). So it's probably not a problem with an asynchronous write. But something else. But what?
if (requestCode == Utility.GALLERY_PICTURE) {
Uri selectedImageUri = null;
try {
selectedImageUri = data.getData();
if (mImgProfilePic != null) {
// mImgProfilePic.setImageURI(selectedImageUri);
mImgProfilePic.setImageBitmap(decodeUri(getActivity(),
selectedImageUri, 60));
// decodeUri
}
} catch (Exception e) {
}
// //////////////
try {
// Bundle extras = data.getExtras();
// // get the cropped bitmap
// Bitmap thePic = extras.getParcelable("data");
// mImgProfilePic.setImageBitmap(thePic);
final Uri tempUri = selectedImageUri;
Log.d("check", "uri " + tempUri);
// http://dev1.brainpulse.org/quickmanhelp/webservice/api.php?act=companylogo
upLoadServerUri = "http://dev1.brainpulse.org/quickmanhelp/webservice/api.php?act=employee_profile_pic&image=";
upLoadServerUri = Utility.EMPLOYEE_PROFILE_PIC_URL
+ "&employee_id=" + empId;
dialog = ProgressDialog.show(getActivity(), "",
"Uploading file...", true);
new Thread(new Runnable() {
public void run() {
getActivity().runOnUiThread(new Runnable() {
public void run() {
// messageText.setText("uploading started.....");
}
});
uploadFilePath = getRealPathFromURI(tempUri);
uploadFile(uploadFilePath + "");
// uploadFile(tempUri+"");
}
}).start();
} catch (Exception e) {
}
// ///////
}
public static void updateFile(File file ,Context context) {
MediaScannerConnection.scanFile(context,
new String[]{file.getAbsolutePath()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
}
);
}
I think you can use this to update before you openInputStream.
From the snippet you shared I thiiink problem is that you are setting Image file to File variable file
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), filename);
But you are setting image Uri from File photoFile which is probably null
targetUri = Uri.fromFile(photoFile);
So basically you need to replace targetUri = Uri.fromFile(photoFile); with targetUri = Uri.fromFile(file);
Or even better data.getData() will return Image URi directlty like this
InputStream is = null;
try {
is = getContentResolver().openInputStream(data.getData());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (is != null) {
Bitmap bm = BitmapFactory.decodeStream(is);
((ImageView) findViewById(R.id.imageView1)).setImageBitmap(bm);
}
You still need to decode bitmap to avoid OOM exception you can use Glide to load image using image URI.
Complete Class Tested on Xpria C
package com.example.test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class TestActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
findViewById(R.id.take_picture).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
}
static final int REQUEST_TAKE_PHOTO = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
protected static final int RESULT_TAKE_PICTURE = 100;
private File createImageFile() throws IOException {
// Create an image file name
String filename = String.format("pic%d.jpg", new Date().getTime());
File file = new File(
getExternalFilesDir(Environment.DIRECTORY_PICTURES), filename);
try {
file.createNewFile();
} catch (IOException e) {
file = new File(getFilesDir(), filename);
}
return file;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
InputStream is = null;
try {
is = getContentResolver().openInputStream(data.getData());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (is != null) {
Bitmap bm = BitmapFactory.decodeStream(is);
((ImageView) findViewById(R.id.imageView1)).setImageBitmap(bm);
}
}
}
}
Related
In my project, I am capturing image from the camera. I am taking the full-size image from the app (instead of taking thumbnail). Captured image is of very big size which is 7 to 18 mb. When I have taken image from my default camera app, the size was roughly 2.5 mb only. As well as it's taking lot of time(6-10 seconds) to load and save to the folder. This happening only when I am using the android device, on emulator it's working good. This is my code:
package com.stegano.strenggeheim.fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.stegano.strenggeheim.BuildConfig;
import com.stegano.strenggeheim.R;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
public class FragmentEncode extends Fragment {
private static final String MESSAGE_IMAGE_SAVED = "Image Saved!";;
private static final String MESSAGE_FAILED = "Failed!";
private static final String IMAGE_DIRECTORY = "/StrengGeheim";
private static final int GALLERY = 0, CAMERA = 1;
private File capturedImage;
TextView imageTextMessage;
ImageView loadImage;
public FragmentEncode() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
private void galleryIntent() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri fileUri = getOutputMediaFileUri();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA);
}
private Uri getOutputMediaFileUri() {
try {
capturedImage = getOutputMediaFile();
return FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + ".provider", capturedImage);
}
catch (IOException ex){
ex.printStackTrace();
Toast.makeText(getContext(), MESSAGE_FAILED, Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_encode, container, false);
imageTextMessage = view.findViewById(R.id.imageTextMessage);
loadImage = view.findViewById(R.id.loadImage);
loadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPictureDialog();
}
});
return view;
}
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(getContext());
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera",
"Cancel"
};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
galleryIntent();
break;
case 1:
cameraIntent();
break;
case 2:
dialog.dismiss();
break;
}
}
});
pictureDialog.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == getActivity().RESULT_CANCELED) {
return;
}
try {
if (requestCode == GALLERY && data != null) {
Bitmap bitmap = getBitmapFromData(data, getContext());
File mediaFile = getOutputMediaFile();
String path = saveImage(bitmap, mediaFile);
Log.println(Log.INFO, "Message", path);
Toast.makeText(getContext(), MESSAGE_IMAGE_SAVED, Toast.LENGTH_SHORT).show();
loadImage.setImageBitmap(bitmap);
imageTextMessage.setVisibility(View.INVISIBLE);
} else if (requestCode == CAMERA) {
final Bitmap bitmap = BitmapFactory.decodeFile(capturedImage.getAbsolutePath());
loadImage.setImageBitmap(bitmap);
saveImage(bitmap, capturedImage);
Toast.makeText(getContext(), MESSAGE_IMAGE_SAVED, Toast.LENGTH_SHORT).show();
imageTextMessage.setVisibility(View.INVISIBLE);
}
} catch (Exception ex) {
ex.printStackTrace();
Toast.makeText(getContext(), MESSAGE_FAILED, Toast.LENGTH_SHORT).show();
}
}
private Bitmap getBitmapFromData(Intent intent, Context context){
Uri selectedImage = intent.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver()
.query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
return BitmapFactory.decodeFile(picturePath);
}
private String saveImage(Bitmap bmpImage, File mediaFile) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmpImage.compress(Bitmap.CompressFormat.PNG, 50, bytes);
try {
FileOutputStream fo = new FileOutputStream(mediaFile);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(getContext(),
new String[]{mediaFile.getPath()},
new String[]{"image/png"}, null);
fo.close();
return mediaFile.getAbsolutePath();
} catch (IOException ex) {
ex.printStackTrace();
}
return "";
}
private File getOutputMediaFile() throws IOException {
File encodeImageDirectory =
new File(Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
if (!encodeImageDirectory.exists()) {
encodeImageDirectory.mkdirs();
}
String uniqueId = UUID.randomUUID().toString();
File mediaFile = new File(encodeImageDirectory, uniqueId + ".png");
mediaFile.createNewFile();
return mediaFile;
}
}
Something you could do is download an available API online, or, if need be, dowload the source code of some online compressor. Then you could use it as a model. Never directly use the source code. One that is widely supported across languages is: https://optimus.keycdn.com/support/image-compression-api/
I am taking the image from the camera and getting the File. So, I am saving the image directly in file location which I generated using getOutputMediaFile() method. For that I am overloading saveImage() method like this:
private void saveImage(File mediaImage) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(mediaImage);
mediaScanIntent.setData(contentUri);
getContext().sendBroadcast(mediaScanIntent);
}
This method will put the image in the desired file location and also accessible to the Gallery for other apps. This method is same as galleryAddPic() method on this link Taking Photos Simply
But In the case of picking a photo from the Gallery, I will have to create the File in the desired location and write the bytes of the picked image into that file, so the old saveImage() method will not change.
In onActivityResult method, this is how I used overloaded saveImage() method:
else if (requestCode == CAMERA) {
saveImage(imageFile);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
loadImage.setImageBitmap(bitmap);
Toast.makeText(getContext(), MESSAGE_IMAGE_SAVED, Toast.LENGTH_SHORT).show();
imageTextMessage.setVisibility(View.INVISIBLE);
}
I am doing a texttospeech project to import txt file and read its contents using storage access framework . After OnActivityResult how to get the content to string variable and pass it to next activity . I need to copy the txt file content to next activity edittext
package com.texttospeech.texttospeech;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.texttospeech.Main2Activity;
public class MainActivity extends AppCompatActivity {
private static final int READ_REQUEST_CODE = 42;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
performFileSearch();
}
});
}
private static final int EDIT_REQUEST_CODE = 42;
/**
* Fires an intent to spin up the "file chooser" UI and select an image.
*/
private void performFileSearch() {
// ACTION_OPEN_DOCUMENT is the intent to choose a file via the system's
// file browser.
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
// Filter to only show results that can be "opened", such as a
// file (as opposed to a list of contacts or timezones).
intent.addCategory(Intent.CATEGORY_OPENABLE);
// Filter to show only text files.
intent.setType("text/plain");
startActivityForResult(intent, EDIT_REQUEST_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData){
if(requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK){
Uri uri = null;
if (resultData!= null){
uri = resultData.getData();
}
}
}
}
You open an InputStream for the obtained uri and then read from the stream as you would do if you had used a FileInputStream.
InputStream is = getContentResolver().openInputStream(resultData.getData());
I guess this will help you:
String text = readText(uri);
private String readText(Uri uri) {
File f = new File(uri.toString());
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1) {
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
Let me know if you had any question.
Problem I ran into was that the class couldn't reccognise getContentResolver() but later I realised that I am in fragment so for that you need to pass context first :
getActivity().getContentResolver() .. or simply
context.getContentResolver()
The application I'm working on allows the user to share images, which it accomplishes using an ACTION_SEND Intent. Everything works fine, unless the activity that handles the intent returns before the file is actually shared.
For example. If I share the image using Google Drive, my app receives the onActivityResult event before the file is actually sent. Since in the code that handles that event I delete the temporary file, the upload of the file to Drive fails. Is there a way to share the file without saving it? Or maybe some way to know when it has actually been sent, so it can be deleted then?
Here's some relevant code from my app.
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
// ...
public static final int REQUEST_SHARE_ACTION = 1;
private File temporaryShareFile;
// ...
protected void share (Bitmap bitmap) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/jpeg");
if(saveTemporaryFile(bitmap)) {
shareIntent.putExtra(
Intent.EXTRA_STREAM,
Uri.fromFile(this.temporaryShareFile)
);
startActivityForResult(
Intent.createChooser(shareIntent, "Share Image"),
REQUEST_SHARE_ACTION
);
} else {
Toast.makeText(
this,
R.string.file_save_fail_message,
Toast.LENGTH_LONG
).show();
}
}
protected boolean saveTemporaryFile (Bitmap bitmap) {
if(createTemporaryFile()) {
return writeTemporaryFile(bitmap);
}
return false;
}
protected boolean createTemporaryFile() {
this.temporaryShareFile = createFile("tmp_", ".jpg");
if (this.temporaryShareFile != null) {
return true;
} else {
return false;
}
}
protected File createFile(String prefix, String suffix) {
File outputDirectory = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
),
getResources().getString(R.string.app_name)
);
if(!outputDirectory.isDirectory()) {
if (!outputDirectory.mkdirs()) {
}
}
File file = null;
try {
file = File.createTempFile(
prefix,
suffix,
outputDirectory
);
return file;
} catch (IOException ioex) {
return null;
}
}
protected boolean writeTemporaryFile(Bitmap bitmap) {
return writeImageFile(
this.temporaryShareFile,
bitmap,
Bitmap.CompressFormat.JPEG,
100
);
}
protected boolean writeImageFile(
File file,
Bitmap bitmap,
Bitmap.CompressFormat format,
int quality
) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(format, quality, fileOutputStream);
fileOutputStream.close();
return true;
} catch (Exception e) {
//error writing file
Log.e("writeImageFile",e.getMessage());
return false;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_SHARE_ACTION) {
temporaryShareFile.delete();
}
}
Are you listening for the success event? See here: https://developers.google.com/drive/android/create-file
I am a very young self taught developer and I'm working on my first major project, which requires to start a camera intent once pressed, save the image that the user took and display it in a custom dialog.
I got it to work, but i stored the returned bitmap in onactivityresult so the picture is compressed and that destroys the functionality of the app.
HERE IS THE CODE THAT DOES WORK:
start intent:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
Recieve Intent and send data to dialog:
Bundle bundle = data.getExtras();
File file = new File(getCacheDir() + "/app"
+ System.currentTimeMillis() + ".jpg");
Bitmap bitmap = (Bitmap) bundle.get("data");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100 /* ignored for PNG */,
bos);
byte[] bitmapdata = bos.toByteArray();
// write the bytes in file
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos = new FileOutputStream(file);
fos.write(bitmapdata);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mdialog.setPic(file.getAbsolutePath());
Display the picture in the custom dialog:
public void setPic(final String mURi) {
this.mURI = mURi;
if (mURI != null) {
hwPic.postDelayed(new Runnable() {
#Override
public void run() {
Drawable d = Drawable.createFromPath(mURI);
hwPic.setImageDrawable(d);;
hwPic.setVisibility(View.VISIBLE);
}
}, 1000);
}
}
This works fine but since the picture is compressed any reasonably sized font in the picture is blury and illegible.
HERE IS THE CODE THAT DOES NOT WORK:
Initialize Variable:
private String MURID;
Start intent:
File file = new File(getCacheDir() + "/app"
+ System.currentTimeMillis() + ".jpg");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
MURID=file.getAbsolutePath();
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT , Uri.parse(MURID));
startActivityForResult(intent, 1);
recieve intent and send to mydialog:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {// camera intent for the dialog picture
if (resultCode == RESULT_OK) {
mdialog.setPic(MURID);
}
}
}
setpic remains the same(in the dialog):
public void setPic(final String mURi) {
this.mURI = mURi;
if (mURI != null) {
hwPic.postDelayed(new Runnable() {
#Override
public void run() {
Drawable d = Drawable.createFromPath(mURI);
hwPic.setImageDrawable(d);;
hwPic.setVisibility(View.VISIBLE);
}
}, 1000);
}
}
Im not getting any response from it and logcat didnt give me any errors either, what seems to be the problem? any help would be greatly apprecieated.
BTW: i want this to work with phones without sdcards as well.
Third-party camera apps cannot write to your getCacheDir(), and some may get confused if you point to an existing file. Use external storage instead:
package com.commonsware.android.camcon;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import java.io.File;
public class CameraContentDemoActivity extends Activity {
private static final int CONTENT_REQUEST=1337;
private File output=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir=
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
output=new File(dir, "CameraContentDemo.jpeg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(i, CONTENT_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == CONTENT_REQUEST) {
if (resultCode == RESULT_OK) {
Intent i=new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(output), "image/jpeg");
startActivity(i);
finish();
}
}
}
}
(from this sample project in this book)
BTW: i want this to work with phones without sdcards as well.
External storage is not removable storage.
I am trying to invoke the audio recorder on Android 2.2.1 (device Samsung Galaxy POP) using the following code:
private static final int ACTIVITY_RECORD_SOUND = 1;
Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
startActivityForResult(intent, ACTIVITY_RECORD_SOUND);
This invokes the recorder successfully. In my activity result i do the following:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case ACTIVITY_RECORD_SOUND:
data.getDataString();
break;
}
}
}
After i complete the recording i press back on the audio recorder which returns the control to the onActivityResult method as expected, but my resultCode is always 0 (which is Activity.RESULT_CANCELED) and my data is null. Am i missing out on something here? Kindly help me with this. This works on the emulator but not on the device. Thanks in advance.
This works for me:
#Override protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch(requestCode) {
case Flashum.TAKE_MUSIC:
case Flashum.TAKE_VOICE:
if (resultCode == Activity.RESULT_OK)
{
Log.i(Flashum.LOG_TAG, "onActivityResult got new music");
Bundle extras = data.getExtras();
try {
Uri u = data.getData();
String imageUri;
try {
imageUri = getRealPathFromURI(u);
} catch (Exception ex) {
imageUri = u.getPath();
}
File file = new File(imageUri);
FragmentFlash fragmentFlash = (FragmentFlash)mTabsAdapter.getFragment("flash");
if (fragmentFlash != null)
fragmentFlash.gotMusic(file.getPath());
} catch (Exception ex) {
String s = ex.toString();
Log.i(Flashum.LOG_TAG, "onActivityResult " + s);
}
}
else
{
Log.i(Flashum.LOG_TAG, "onActivityResult Failed to get music");
}
break;
}
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
I finally found a workaround for my problem by using the FileObserver. I achieved it by doing the following:
package com.pravaa.audiointent;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.FileObserver;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
public class AudioActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
private Button sampleButton;
private FileObserver mFileObserver;
private Vector<String> audioFileNames;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
audioFileNames = new Vector<String>();
LinearLayout finalContainer = new LinearLayout(this);
sampleButton = new Button(this);
sampleButton.setOnClickListener(this);
sampleButton.setText("Start Audio Intent");
finalContainer.addView(sampleButton);
setContentView(finalContainer);
addObserver();
}
private void addObserver() {
this.mFileObserver = new FileObserver("/sdcard/Sounds/") {
#Override
public void onEvent(int event, String path) {
if (event == FileObserver.CREATE) {
if (path != null) {
int index = path.indexOf("tmp");
String tempFileName = (String) path.subSequence(0,
index - 1);
audioFileNames.add(tempFileName);
}
} else if (event == FileObserver.DELETE) {
if (path != null) {
int index = path.indexOf("tmp");
String tempFileName = (String) path.subSequence(0,
index - 1);
if (audioFileNames.contains(tempFileName)) {
audioFileNames.remove(tempFileName);
}
}
}
}
};
}
private void readFile(String fileName) {
File attachment = new File("/sdcard/Sounds/" + fileName);
if (attachment.exists()) {
FileInputStream fis;
try {
fis = new FileInputStream(attachment);
byte[] bytes = new byte[(int) attachment.length()];
try {
fis.read(bytes);
fis.close();
attachment.delete();
saveMedia("Test" + fileName, bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mFileObserver.startWatching();
}
public void saveMedia(String fileName, byte[] data) {
String imagePath = "/sdcard/sam/";
System.out.println("Inside Folder");
File file = new File(imagePath, fileName);
System.out.println("File Created");
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
DataOutputStream dataOutputStream = new DataOutputStream(
fileOutputStream);
System.out.println("Writting File");
dataOutputStream.write(data, 0, data.length);
System.out.println("Finished writting File");
dataOutputStream.flush();
dataOutputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
startActivityForResult(intent, 2);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
// TODO Auto-generated method stub
if (requestCode == 2) {
if (mFileObserver != null) {
mFileObserver.stopWatching();
}
Enumeration<String> audioFileEnum = audioFileNames.elements();
while (audioFileEnum.hasMoreElements()) {
readFile((String) audioFileEnum.nextElement());
}
}
}}
i was facing the same issue.. So instead of using an intent, I used the MediaRecorder class and its associated methods like setAudioEncoder, setAudioSource, prepare, start, stop, setOutputFormat and setOutputFile..It works fine now..
I also agree with the best answer so far (voted by question-owner), but it cannot read the file as it is a different path. my suggestion is to store the filename as a member-variable and call getFilename() only once.
There is a known issue with Galaxy Android devices where result intents are null where you would expect them to contain a photo. This might also apply here. See http://kevinpotgieter.wordpress.com/2011/03/30/null-intent-passed-back-on-samsung-galaxy-tab/.
One way to solve this, is to add
intent.putExtra(MediaStore.EXTRA_OUTPUT, someFileUri);
to your intent, explicitly telling the target app where to store the resulting file.
Check out this example if you need help creating a good file Uri.