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.
Related
This question already has answers here:
Low picture/image quality when capture from camera
(3 answers)
Closed 5 years ago.
I want to take a picture from the Camera and Upload it to Server, but when I take a Picture from the Camera and Upload the Picture is low Resolution.
Code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CaptureImageFromCamera = (ImageView)findViewById(R.id.imageView);
CaptureImageFromCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, 1);
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1)
try {
onCaptureImageResult(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void onCaptureImageResult(Intent data) throws IOException {
bitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes;
bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
"DCA/Attachment/" + System.currentTimeMillis() + ".png");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ImageViewHolder.setImageBitmap(bitmap);
}
Can be seen that the image quality is low resolution.
Is there a way to solve this problem?
[UPDATE] HOW I TO SOLVE THIS
I read the article here to solve this problem
Note: Read from the start page
package com.example.admin.camsdemo;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
Button captureimage;
ContentValues cv;
Uri imageUri;
ImageView imgView;
public static final int PICTURE_RESULT=111;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
captureimage=(Button)findViewById(R.id.opencamera);
imgView=(ImageView)findViewById(R.id.img);
captureimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cv = new ContentValues();
cv.put(MediaStore.Images.Media.TITLE, "My Picture");
cv.put(MediaStore.Images.Media.DESCRIPTION, "From Camera");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cv);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, PICTURE_RESULT);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICTURE_RESULT:
if (requestCode == PICTURE_RESULT)
if (resultCode == Activity.RESULT_OK) {
try {
Bitmap thumbnail = MediaStore.Images.Media.getBitmap(
getContentResolver(), imageUri);
imgView.setImageBitmap(thumbnail);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
Try using TextureView.SurfaceTextureListener and camera.takePicture(shutterCallback, rawCallback, pictureCallback)
For images taken from camera, you should consider JPEG compression. PNG is more suitable for icons where the colors used are few.
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);
}
}
}
}
I need to write text file in the smartphone internal memory, and then need to copy this .txt file to your computer via the USB cable and accessing his memory (This copy process will make manual, need to locate this file and understand which memory location will be recorded).
I am using the code below, which shows no errors when I run, but I do not know if this recording, and I do not know exactly what directory on your smartphone it should be.
This function is the button to call the function salvarInternalStorage
findViewById(R.id.distance_demo_button).setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
Trilateration tri = new Trilateration(v.getContext());
try {
tri.salvarInternalStorage("Trying to Save This text Example");
} catch (IOException e) {
e.printStackTrace();
}
startListBeaconsActivity(DistanceBeaconActivity.class.getName());
}
});
This function is where you should write to the "File.txt" the text passed by parameter.
public void salvarInternalStorage(String texto) throws IOException{
// Use Activity method to create a file in the writeable directory
FileOutputStream fos = context.openFileOutput("FileTeste.txt", context.MODE_PRIVATE);
// Create buffered writer
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos));
writer.write(String.valueOf(texto.getBytes()));
writer.close();
}
With SAF:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
createFile("text/plain","Arquivo.txt");
}
private static final int WRITE_REQUEST_CODE = 43;
private void createFile(String mimeType, String fileName) {
Intent intent = new Intent(Intent.ACTION_CREATE_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);
// Create a file with the requested MIME type.
intent.setType(mimeType);
intent.putExtra(Intent.EXTRA_TITLE, fileName);
startActivityForResult(intent, WRITE_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode==WRITE_REQUEST_CODE&&resultCode==RESULT_OK)
alterDocument(data.getData());
}
private void alterDocument(Uri uri) {
try {
ParcelFileDescriptor txt = getContentResolver().
openFileDescriptor(uri, "w");
FileOutputStream fileOutputStream =
new FileOutputStream(txt.getFileDescriptor());
fileOutputStream.write(("Tentando Gravar Esse Texto Exemplo").getBytes());
fileOutputStream.close();
txt.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Or you can use the OPEN_DOCUMENT_TREE once to choose a directory and after that you have all permissions to save any file under that directory without ask the user. Something like this:
Uri sdCardUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode)
{
case 1:
if (resultCode == Activity.RESULT_OK) {
sdCardUri = data.getData();
getContentResolver().takePersistableUriPermission(sdCardUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
createFile();
break;
}
}
private void createFile() {
DocumentFile sdCard=DocumentFile.fromTreeUri(this,sdCardUri);
DocumentFile createFile=sdCard.findFile("teste.txt");
if (createFile==null)
createFile=sdCard.createFile("text","teste.txt");
OutputStream outStream = null;
try {
outStream = getContentResolver().openOutputStream(createFile.getUri());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
String teste="Isto é um teste";
outStream.write(teste.getBytes());
outStream.flush();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is code i'm using
Intent i = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, cameraData);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
InputStream is = getContentResolver().openInputStream(data.getData());
Main.this.getContentResolver().delete(data.getData(), null,
null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
String error = e.toString();
Dialog d = new Dialog(this);
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}
} else {
is = null;
}
}
I'm doing this way because i don't want to save pics to dcim folder.
It is working fine on samsung, htc and some other devices but it crashes on alcatel one touch 5020x Jelly Bean 4.1.1,
returns null pointer exception.
Is there another way to do this, but not to save pics to dcim folder.
I have seen many solutions to do this but all of them save a pic to dcim folder
Thanx
I'm doing this way because i don't want to save pics to dcim folder.
Then include EXTRA_OUTPUT in your ACTION_IMAGE_CAPTURE Intent, to tell whichever camera app handles your request where to put the image. Quoting the documentation:
The caller may pass an extra EXTRA_OUTPUT to control where this image will be written. If the EXTRA_OUTPUT is not present, then a small sized image is returned as a Bitmap object in the extra field.
Your code is written to not do anything of what is documented. Instead, you are assuming that the camera app will return a Uri of where an image is. This is not part of the documented protocol, and so your code will fail when interacting with many camera apps.
Is there another way to do this, but not to save pics to dcim folder.
This code will put the image in another spot on external storage:
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);
output=new File(getExternalFilesDir(null), "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) {
// use the output File object
}
}
}
}
This is not the best solution but it works!
final static int cameraData = 13579;
final static int camera2Data = 97531;
InputStream is = null;
int camera2 = 0;
SharedPreferences spData;
public static String spName = "MySharedString";
camera start:
if (camera2 == 1) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
output = new File(getExternalFilesDir(null),
"CameraContentDemo.jpg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(i, camera2Data);
} else {
Intent i = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, cameraData);
}
onActivitrForResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == cameraData) {
if (resultCode == RESULT_OK) {
try {
is = getContentResolver().openInputStream(data.getData());
Main.this.getContentResolver().delete(data.getData(), null,
null);
} catch (Exception e) {
// TODO Auto-generated catch block
camera2 = 1;
if (camera2 == 1) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
output = new File(getExternalFilesDir(null),
"CameraContentDemo.jpeg");
i.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(output));
startActivityForResult(i, camera2Data);
}
SharedPreferences.Editor editor = spData.edit();
editor.putInt("cam2", 1);
editor.commit();
}
} else {
is = null;
}
}
if (requestCode == camera2Data) {
if (resultCode == RESULT_OK) {
try {
is = new FileInputStream(output);
} catch (Exception e) {
// TODO Auto-generated catch block
SharedPreferences.Editor editor = spData.edit();
editor.putInt("cam2", 0);
editor.commit();
}
} else {
is = null;
}
}
}
So, like i said, its not the best solution but it works.
When the app starts for the first time on Alcatel, it starts with the old code, crashes and catcher the exception, saves camera2 variable to be 1, and starts the camera again with the second code that works fine.
When i load on other devices, it works fine to and no pics are saved to DCIM folder
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.