When i do debug it didnt go to try block than catch block , this is my code please help me!
public void onClick(View v) {
try {
path = Environment.getExternalStorageDirectory()+"/audio_meena.AMR";
File newFile = new File(path);
Uri uri =Uri.fromFile(newFile);
Intent audioIntent=new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
startActivityForResult(audioIntent, RQS_RECORDING);
mr.setAudioSource(MediaRecorder.AudioSource.MIC);
mr.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
FileDescriptor PATH_NAME = null;
mr.setOutputFile(PATH_NAME);
} catch (Exception e) {
// TODO: handle exception
}
}
});
either set the "onClick" attribute to the view you wish (via the layout) , or find it right after the "setContentView" using "findViewById" and then use "setOnClickListener" for the view .
about "OnActivityResult", you need to put it in the activity itself as a stand alone method .
Related
I have an activity where I open a image picker intent and the when I get the selected Uri, I create a copy of the file in cache directory and then pass the location of the image to Picasso to load the image. I am doing this because some apps like Google Photos do not allow the actual Uris to be passed to different activities for security reasons.
Here is my code for the same :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_external_photo_share);
ButterKnife.bind(this);
LogUtil.i(TAG, "onCreate called");
tinyDB = new TinyDB(this);
if (tinyDB.getBoolean(AppConstants.LOGIN_STATE, false)) {
imageUri = (Uri) getIntent().getExtras().get(Intent.EXTRA_STREAM);
if (imageUri == null || imageUri.toString().isEmpty()) {
ExternalPhotoShareActivity.this.finish();
}
String newActualPath = getActualPathFromUri(imageUri);
Uri newUri = null;
if (newActualPath != null) {
newUri = Uri.fromFile(new File(newActualPath));
}
Intent intent = new Intent(ExternalPhotoShareActivity.this, AddCaptionActivity.class);
intent.putExtra("externalImageUri", newUri);
intent.putExtra("externalImagePath", newActualPath);
startActivity(intent);
ExternalPhotoShareActivity.this.finish();
} else {
final Dialog dialog = new Dialog(ExternalPhotoShareActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_external_share_error);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
TextView goBack = (TextView) dialog.findViewById(R.id.textView86);
goBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if(dialog != null) {
if(dialog.isShowing()) {
dialog.dismiss();
}
}
} catch (final IllegalArgumentException e) {
// Handle or log or ignore
} catch (final Exception e) {
// Handle or log or ignore
}
ExternalPhotoShareActivity.this.finish();
}
});
}
}
private String getActualPathFromUri(Uri selectedImageUri) {
Bitmap bitmap = null;
try {
bitmap = getBitmapFromUri(selectedImageUri);
} catch (IOException e) {
e.printStackTrace();
}
if (bitmap == null) {
return null;
}
File imageFileFolder = new File(getCacheDir(), "galleri5");
if (!imageFileFolder.exists()) {
imageFileFolder.mkdir();
}
FileOutputStream out = null;
File imageFileName = new File(imageFileFolder, "galleri5-" + System.currentTimeMillis() + ".jpg");
try {
out = new FileOutputStream(imageFileName);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (IOException e) {
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return imageFileName.getAbsolutePath();
}
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
assert parcelFileDescriptor != null;
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
I call getActualPathFromUri() in my activity's onCreate() method. Sometimes, when the images from gallery are large, it takes some seconds to load the image on the screen. So, I thought about executing these two methods in background thread so that I could show the UI while the background work is done.
I recently started using Android Support Annotations and tried to annotate the getActualPathFromUri() with #WorkerThread. But in my onCreate() method, it marks it red and says that this method should be called from Worker Thread, currently inferred thread is main.
What is the proper way of doing this? Should I even do it in background thread or not? Thanks.
The annotations #WorkerThread or #UIThread are only used for flagging a method. Android Studio will raise an error when your method is called from a thread that does not match your annotated constraint. See this documentation.
For advice on threading with AsyncTask see this android developers blog post.
In this case, with the annotation #WorkerThrad you're saying that getActualPathFromUri() should only be called from a worker thread. As you're calling it from onCreate() which runs inside the UI-thread, lint detects the issue and flags it.
The fact that you annotate the method like that, does not mean you're running the method inside a worker thread. Annotation in this case is just a way to flag the developer (that might be different than yourself if working in a team) that a particular method is meant to be called in a particular thread.
If you want to actually run that method in an actual worker thread, just call it inside an AsyncTask#doInBackground method.
EDIT: if you don't wanna use AsyncTask you can use any other Android threading mechanism, like IntentService, GcmTaskService and whatnot but, you should not run it inside the UI thread because it may cause jank.
I am developing a custom camera app in Android. My goal is to save a picture to file and open it in the fullscreen mode as soon as the file has been saved. Unfortuantely, the problem is that my main activity (ImageCapture) doesn't wait for ImageCaptureCallback results before calling the next activity (ImageDisplay).
To take a picture I am using a custom ImageCaptureCallback, which saves captured image to "tmpPicturePath" using OutputStream. Later the ImageDisplay activity is called - it reads the file saved in tmpPicturePath.
camera.takePicture(mShutterCallback, mPictureCallbackRaw, new ImageCaptureCallback(this));
// ImageCaptureCallback saves the file in tmpPicturePath
Intent intent = new Intent(ImageCapture.this, ImageDisplay.class);
intent.putExtra("tmpPicturePath", this.getTmpPicturePath());
startActivity(intent);
BUT the file that should be created in ImageCaptureCallback is not yet available at the moment of calling ImageDisplay activity. The overall effect is that not the actual but the previously taken picture is available in the ImageDisplay class. Do you have an idea how to handle this issue? In other words how to wait for callback results before calling the next activity?
Many thanks!
Sample code for taking picture from camera
void selectPhoto() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From your Camera");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, SELECT_PHOTO);
}
and in onActivityResult() method
try {
imageBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I have a Problem. I start from my own Application the Build-In Photoapplication with a Photo-Intent.
String photoName = System.currentTimeMillis() + ".jpg";
File file = new File(getFilesDir(),//Environment.getExternalStoragePublicDirectory(
//Environment.DIRECTORY_DCIM),
photoName); // Anlegen der Datei im entsprechenden
// Verzeichnis
FileOutputStream fos = null;
try {
fos = openFileOutput(photoName, Context.MODE_WORLD_WRITEABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outputFileUri = Uri.fromFile(file);
intentPhoto.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
//startActivity(intentPhoto);
startActivityForResult(intentPhoto, TAKE_PICTURE);
This is my Code to start the Activity. As you can see, the first thing i do is to set up the file in the directory and then give the intent the location of the file to store it.
But everytime i take a picture it is not saved to the Pictures Directory. The only way to save the picture is to turn off the phone and restart it. Then every picture I have taken befor is there. This happens since the last updated to 4.1.1. Befor i updated the phone, everything worked fine, but since the update I have this problem.
Can somebody help me? Does anyone have the same Issue?
Make sure you offer the new file to be scanned:
MediaScannerConnection.scanFile(this,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
// code to execute when scanning is complete
}
});
You can pass in a null argument for the OnScanCompletedListener if you don't need to be notified when the scanner has picked it up, but you might want to at least put a logging statement there.
It works fine now, the problem was that I create the File by my self, with:
File file = new File(..);
But you have to use:
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "IMG_"+ timeStamp+.jpg");
And put it into the intent to save the file at once without restarting the phone.
So I want to save whatever users write in their EditText to be saved for the next time. This exact same code works for java project but with Android project, it doesnt work.
The code is below.
The PrintWriter out = new PrintWriter("hi"); always gives the FileNotFoundException e.
In java project, this code The PrintWriter out = new PrintWriter("hi"); makes a new file with the name "hi" but android project does not produce a new file instead returns the error. It does not save the String from the EditText to be opened when the app opens up again later.
Does anyone have a solution to this problem?
public void onCreate(blablabla)
{blablabla
try {
FileReader reader = new FileReader ("hi");
Scanner in = new Scanner(reader);
String line = in.nextLine();
mEditText.setText(line);
in.close();
} catch (FileNotFoundException e) {
mEditText.setText("");
Toast.makeText(mContext, "null!!", Toast.LENGTH_SHORT).show();
}
#Override
protected void onDestroy()
{
super.onDestroy();
// The activity is about to be destroyed.
try {
PrintWriter out = new PrintWriter("hi");
out.write(mEditText.toString());
out.close();
} catch (FileNotFoundException e) {
Toast.makeText(mContext, "Can't save", Toast.LENGTH_SHORT).show();
}
}
May be Android permission problem. See http://developer.android.com/guide/topics/manifest/manifest-intro.html#perms
Or better to use SharedPreferences?
I'm new to android. Now, i'm doing image capturing function using:
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
The problem is after I capture my photo, the new captured photo does not display on the image display page.
Does anyone here know where there is code that can help me refresh my android or any step that I need to do so that my image display page can be updated once I capture a new photo?
Any help would be very appreciated and many thanks to you first.
Updated answer:
I use this, may be this can help others:
mScanner = new MediaScannerConnection(
Camera.this,
new MediaScannerConnection.MediaScannerConnectionClient() {
public void onMediaScannerConnected() {
mScanner.scanFile(outputFileUri.getPath(), null /* mimeType */);
}
public void onScanCompleted(String path, Uri uri) {
//we can use the uri, to get the newly added image, but it will return path to full sized image
//e.g. content://media/external/images/media/7
//we can also update this path by replacing media by thumbnail to get the thumbnail
//because thumbnail path would be like content://media/external/images/thumbnail/7
//But the thumbnail is created after some delay by Android OS
//So you may not get the thumbnail. This is why I started new UI thread
//and it'll only run after the current thread completed.
if (path.equals(outputFileUri.getPath())) {
mScanner.disconnect();
//we need to create new UI thread because, we can't update our mail thread from here
//Both the thread will run one by one, see documentation of android
Camera.this
.runOnUiThread(new Runnable() {
public void run() {
}
});
}
}
});
mScanner.connect();
Sally, did you mean that after you take a photo you don't see it in the gallery or file-manager when you look at the directory you know the file to be in?
If so, you need to run the media-scanner like this:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
... where uri is the uri of the photo, since you know it already, although you can use the uri of the directory instead if that's easier (though it is slower - potentially very slow if the directory contains many files or nested directories).
you should take photo using below code::
Calendar cal = Calendar.getInstance();
File file = new File(Environment.getExternalStorageDirectory(),(cal.getTimeInMillis()+".jpg"));
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
selectedImageUri = Uri.fromFile(file);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, selectedImageUri);
startActivityForResult(i, CAMERA_RESULT);
and on activity result you can use these code:::
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case CAMERA_RESULT:
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), selectedImageUri);
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
You can refresh your activity with :
Intent myIntent = getIntent();
finish();
startActivity(myIntent);