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.
Related
I am trying to build an OCR app using Google's API. Now this activity lets user select an image file using file picker, from where text is extracted. The app works fine if a user selects an image file but if you open file picker and do not select file then the app crashes.
Suppose you clicked on browse button and file picker opens but you do not select any file and press back button then it that case app crashes,but if you will select a file then it works fine.
Here I am attaching the code.
package com.example.rahulranjan.synthesize;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.text.Text;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.UUID;
public class ocr extends AppCompatActivity {
Button b, convert;
EditText t;
Uri uri;
InputStream inputStream = null;
String str = "";
StringBuffer buf = new StringBuffer();
String text;
Bitmap bitmap;
private String imagePath = "";
TextView txtView;
StringBuilder strBuilder2 = new StringBuilder();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ocr);
b = (Button) findViewById(R.id.button);
convert = (Button) findViewById(R.id.button2);
t = (EditText) findViewById(R.id.editText);
txtView = (TextView) findViewById(R.id.textView5);
txtView.setMovementMethod(new ScrollingMovementMethod());
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(" */* ");
startActivityForResult(intent, 7);
}
});
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Syntesize Text");
imagesFolder.mkdirs();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String fileSelected = data.getStringExtra("fileSelected");
Bundle result = data.getExtras();
if (resultCode == RESULT_OK) {
if (data != null) {
// Get the URI of the selected file
Uri uri = data.getData();
t.setText(uri.getPath().toString());
try {
inputStream = getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
TextRecognizer txtRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!txtRecognizer.isOperational()) {
// Shows if your Google Play services is not up to date or OCR is not supported for the device
// txtView.setText("Detector dependencies are not yet available");
Toast toast = Toast.makeText(getApplicationContext(), "Detector dependencies are not yet available", Toast.LENGTH_LONG);
toast.show();
} else {
// Set the bitmap taken to the frame to perform OCR Operations.
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray items = txtRecognizer.detect(frame);
StringBuilder strBuilder = new StringBuilder();
// The following Process is used to show how to use lines & elements as well
for (int i = 0; i < items.size(); i++) {
TextBlock item = (TextBlock) items.valueAt(i);
strBuilder.append(item.getValue());
strBuilder.append(".");
for (Text line : item.getComponents()) {
//extract scanned text lines here
Log.v("lines", line.getValue());
for (Text element : line.getComponents()) {
//extract scanned text words here
Log.v("element", element.getValue());
}
}
}
strBuilder2 = strBuilder;
}
txtView.setText(strBuilder2.toString());
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public void clear(View view)
{
txtView.setText("");
}
public void convert(View view)
{
String data = strBuilder2.toString();
File gpxfile = new File(Environment.getExternalStorageDirectory().toString()+"/Syntesize Text"+"/"+ UUID.randomUUID().toString()+".txt");
try (FileWriter writer = new FileWriter(gpxfile)) {
try {
writer.append(data);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
writer.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
writer.close();
} catch (IOException e1) {
e1.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();
}
}
might be NPE move these two lines
String fileSelected = data.getStringExtra("fileSelected");
Bundle result = data.getExtras();
inside
if (data != null) {
final result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (data != null) {
// Get the URI of the selected file
String fileSelected = data.getStringExtra("fileSelected");
Bundle result = data.getExtras();
Uri uri = data.getData();
t.setText(uri.getPath().toString());
try {
inputStream = getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
TextRecognizer txtRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!txtRecognizer.isOperational()) {
// Shows if your Google Play services is not up to date or OCR is not supported for the device
// txtView.setText("Detector dependencies are not yet available");
Toast toast = Toast.makeText(getApplicationContext(), "Detector dependencies are not yet available", Toast.LENGTH_LONG);
toast.show();
} else {
// Set the bitmap taken to the frame to perform OCR Operations.
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray items = txtRecognizer.detect(frame);
StringBuilder strBuilder = new StringBuilder();
// The following Process is used to show how to use lines & elements as well
for (int i = 0; i < items.size(); i++) {
TextBlock item = (TextBlock) items.valueAt(i);
strBuilder.append(item.getValue());
strBuilder.append(".");
for (Text line : item.getComponents()) {
//extract scanned text lines here
Log.v("lines", line.getValue());
for (Text element : line.getComponents()) {
//extract scanned text words here
Log.v("element", element.getValue());
}
}
}
strBuilder2 = strBuilder;
}
txtView.setText(strBuilder2.toString());
}
}
super.onActivityResult(requestCode, resultCode, data);
}
also better check for requestCode too
condition should be
if (resultCode == RESULT_OK && data!=null && requestCode==7) {
//your code
}
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 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.
In my app, I have a button1 which calls camera, and after capturing the image, it must be saved to the device gallery. When I click on button2, it must open the gallery, and ask to select a picture. When selected, it must be shown on the imageView below these buttons.
Here is my code:
package com.android.imageuploading;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class ImageUploadingActivity extends Activity {
private static final int REQUEST_CODE = 1;
private Bitmap bitmap;
private ImageView imageView;
private Button button_1;
public int TAKE_PICTURE = 1;
private Button button_2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) findViewById(R.id.image);
button_1 = (Button) findViewById(R.id.button1);
button_1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, TAKE_PICTURE);
}
});
button_2 = (Button) findViewById(R.id.button2);
button_2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
pickImage(getCurrentFocus());
}
});
}
public void pickImage(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
try {
// We need to recyle unused bitmaps
if (bitmap != null) {
bitmap.recycle();
}
InputStream stream = getContentResolver().openInputStream(
data.getData());
bitmap = BitmapFactory.decodeStream(stream);
stream.close();
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
super.onActivityResult(requestCode, resultCode, data);
}
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
}
The problem is, when I capture the image, it asks for save or discard. When I click on save, my app crashes, saying:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.android.imageuploading/com.android.imageuploading.ImageUploadingActivity}: java.lang.NullPointerException
Where do I need to change the code?
in my case i use this: when i click on save button pic is save and return me path in filePath variable.
String filePath =
Environment.getExternalStorageDirectory() +"/your_image_name.jpeg";
File file = new File(filePath);
Uri output = Uri.fromFile(file);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, output);
and in onactivityresul() i use this "filePath" .
Capture Image:
public class Camera extends Activity
{
private static final int CAMERA_REQUEST = 1888;
private String selectedImagePath;
WebView webview;
String fileName = "capturedImage.jpg";
private static Uri mCapturedImageURI;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent cameraIntent = new Intent(ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQUEST)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
Random randomGenerator = new Random();randomGenerator.nextInt();
String newimagename=randomGenerator.toString()+".jpg";
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + newimagename);
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//write the bytes in file
try {
fo = new FileOutputStream(f.getAbsoluteFile());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
uri=f.getAbsolutePath();
//this is the url that where you are saved the image
}
}
Choose Image:
public class ChoosePicture extends Activity
{
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
webview=(WebView)findViewById(R.id.webView1);
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, SELECT_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE)
{
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
try {
FileInputStream fileis=new FileInputStream(selectedImagePath);
BufferedInputStream bufferedstream=new BufferedInputStream(fileis);
byte[] bMapArray= new byte[bufferedstream.available()];
bufferedstream.read(bMapArray);
Bitmap bMap = BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
//this is the image that you are choosen
if (fileis != null)
{
fileis.close();
}
if (bufferedstream != null)
{
bufferedstream.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}