I'm a beginner to Java and Android, and I have a problem with launching a camera. Precisely I need a small camera preview that would be under my control. (I want to put a sight in the middle of it). I tried to paste this to my project:
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/graphics/CameraPreview.html
But there are loads of errors, after my naive 'fixing', program crashes, before starting anything..
I tried searching google for quite a long time, unsuccessfully.
Is somebody in posession of something that would just work without problems? A project would be nice :)
Thanks in advance
Bye
in your onCreate method, provide the below lines,
String imgName = getImageName();
startCamera(imgName);
And below your onCreate, provide these methods. your camera is ready.
private void startCamera(String ImageName) {
Intent cameraIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
Uri.fromFile(new File(ImageName)));
startActivityForResult(cameraIntent, TAKE_PICTURE_WITH_CAMERA);
}
private String getImageName() {
String imgname = "";
String imgpath = "";
String strDirectory="/sdcard";
try {
imgname = String.format("%d.mp4", System.currentTimeMillis());
imgpath = strDirectoy + "/" + imgname;
File file = new File(strDirectoy);
boolean exists = file.exists();
if (!exists) {
boolean success = (new File(strDirectoy)).mkdir();
if (success)
Log.e("Directory Creation", "Directory: " + strDirectoy
+ " created");
else
Log.e("Directory Creation", "Error in Create Directory");
}
Log.i("Imagename : ", imgpath);
} catch (Exception e) {
Log.e("fileException", e.getMessage());
e.printStackTrace();
}
return imgpath;
}
Related
I have been looking at the forum and found some tips but none of them bring me to the final solution. I need the code if possible, please.
I am creating a txt file every time I close my app and what I am aiming for is to rename the file in case it already exists with the following format:
file.txt - file(1).txt - file(2).txt
Up until now what I get is the following:
file.txt - file.txt1 - file.txt12
The code that I have is the following:
int num = 0;
public void createFile(String name) {
try {
String filename = name;
File myFile = new File(Environment.getExternalStorageDirectory(), filename);
if (!myFile.exists()) {
myFile.createNewFile();
} else {
num++;
createFile(filename + (num));
}
} catch (IOException e) {
e.printStackTrace();
}
}
Thanks everybody in advance!
Your filename variable contains the whole name of your file (i.e. file.txt). So when you do this:
createFile(filename + (num));
It simply adds the number at the end of the file name.
You should do something like this:
int num = 0;
public void createFile(String prefix) {
try {
String filename = prefix + "(" + num + ").txt"; //create the correct filename
File myFile = new File(Environment.getExternalStorageDirectory(), filename);
if (!myFile.exists()) {
myFile.createNewFile();
} else {
num++; //increase the file index
createFile(prefix); //simply call this method again with the same prefix
}
} catch (IOException e) {
e.printStackTrace();
}
}
Then just call it like this:
createFile("file");
Should I be using something other than the MediaScannerConnection.scanFile method to refresh the gallery?
After saving a new jpg I run media scanner to refresh the gallery app like so
MediaScannerConnection.scanFile(this,
new String[] { fullname }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.d("ExternalStorage", "#### Scanned " + path + ":");
Log.d("ExternalStorage", "#### -> uri=" + uri);
}
});
The output of the log shows the following correct output
#### Scanned /data/data/com.mypackage/files/skit_106_01.jpg:
#### -> uri=content://media/external/images/media/95
The gallery app shows no media available
This code has been working perfectly for some time now. It was only when I created an Android avd against version 4.4.2 for further testing that the problem has surfaced.
The code I have seems to be the recommended way of refreshing the gallery app according to Androids documentation so maybe this issue is related to the way I am saving the file, the code for which is as follows.
UPDATE
The code checks for external storage availability and will write to external storage and if external storage is not available it will write the file to internal storage.
private void doSave(String fname, boolean doShare) {
fname = "skit_"+mCurrentSkitId +
"_"+mSkitManager.getCurrentFrameCount(
mCurrentSkitId)+1;
Log.d(TAG, "#### doSave fName = " + fname + " Current skit id = " + mCurrentSkitId);
CharSequence text = getResources().getString(R.string.saved_as)
+ " " + fname;
try {
Bitmap b = mMainView.getSaveBitmap();
if (b == null) {
text = getResources().getString(R.string.save_fail_1);
;
Toast.makeText(this, text, Toast.LENGTH_LONG).show();
return;
}
fname = FileUtils.replaceInvalidFileNameChars(fname);
String value = fname;
File folder = FileUtils.getWritableFolder(this);
/*
* String folder =
* Environment.getExternalStorageDirectory().toString() +
* "/Pictures"; try { folder =
* Environment.getExternalStoragePublicDirectory
* (Environment.DIRECTORY_PICTURES).toString(); } catch
* (NoSuchFieldError e) {
*
* }
*/
String ext = ".jpg";
if (mPrefs.getString("format", "JPG").equals("PNG"))
ext = ".png";
String fullname = folder.getAbsolutePath() + File.separator + value
+ ext;
Map<String, String> hm = new HashMap<String, String>();
hm.put("filename", fullname);
FileOutputStream fos;
if (folder == getFilesDir())
fos = openFileOutput(value + ext, Context.MODE_WORLD_WRITEABLE);
else {
File f2 = new File(fullname);
fos = new FileOutputStream(f2);
}
b.compress(CompressFormat.JPEG, 95, fos);
fos.close();
String[] str = new String[1];
str[0] = fullname;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO) {
MediaScannerConnection.scanFile(this,
new String[] { fullname }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.d("ExternalStorage", "#### Scanned " + path + ":");
Log.d("ExternalStorage", "#### -> uri=" + uri);
}
});
}
text = text + value + ext + " "
+ getResources().getString(R.string.saved_end);
;
mLastSaveName = value;
setDetailTitle();
mSkitManager.createFrame(mCurrentSkitId, fullname);
} catch (Exception e) {
Map<String, String> hm = new HashMap<String, String>();
hm.put("text", e.toString());
e.printStackTrace();
text = getResources().getString(R.string.save_fail_2)
+ e.toString();
} catch (Error e) {
Map<String, String> hm = new HashMap<String, String>();
hm.put("text", e.toString());
e.printStackTrace();
text = getResources().getString(R.string.save_fail_2)
+ e.toString();
}
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
The code that does the check for external storage availability looks like this
public static File getWritableFolder(Context context) {
File folder = context.getFilesDir();
if (externalStorageAvailable()) {
try {
folder = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
if (!folder.exists() || !folder.canWrite()) {
folder = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
}
if (!folder.exists() || !folder.canWrite()) {
folder = Environment.getExternalStorageDirectory();
}
} catch (Exception e) {
folder = Environment.getExternalStorageDirectory();
} catch (Error e) {
folder = Environment.getExternalStorageDirectory();
}
if (!folder.exists() || !folder.canWrite()) {
folder = context.getFilesDir();
}
}
return folder;
}
private static boolean externalStorageAvailable() {
boolean mExternalStorageAvailable;
boolean mExternalStorageWriteable;
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but
// all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
return mExternalStorageAvailable && mExternalStorageWriteable;
}
If anyone is able to pick holes in any of the above that might help to solve this issue then that would be great.
i was having mixed results with MediaScannerConnection so i used the sendBroadcast method instead. I do not know if the sendBroadcast method is not standard/should not be used but it works for me.
public void galleryAddPic(File currentPhotoPath) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(currentPhotoPath);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
Also regarding the MediaScannerConnection : https://stackoverflow.com/a/4825615/1497188
I am newbie to android, i faced a problem with camera in android.
In my class, i have some instance variables(holding some values which i got from Activity1 through intent) and a button and image view.
when i click that button the application opens camera and stores in sd card, after that i am doing some operations with instance variables.
But the problem is the variables are reinitialized to default values.
i have used shared preference or storing(variables data) in another class as static variables then it works fine.
My question is why all instance variables are reinitialized.
in my application Activity1--(calling)--->Activity2[this has a button and an imageview], here i am passing some data through intent from Activity1 to Activity2, In Activity2 (in Activity2 i am getting data successfully before calling camera ) if am calling camera,the data which i got from intent are reinitialized to default values.To avoid this i have not passed the data from Activity1(i have stored in SharedPreference or in constant class as static variables it works fine).My question is are these only solutions?
This is camera code in activity2
// camera code
public void openCamera() {
if (Helper.checkCameraHardware(this)) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateFileName = sdf.format(new Date()); // generating
// todays date
// for folder
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
String curentDateandTime = sdf1.format(new Date()); // generating
// todays
// date with
// min,seconds
// for image
// creating an folder in sd card : ed ==> sdCard path/IMG_Folder
// in helper class / folder with todays date
File sdImageMainDirectory = new File(Environment
.getExternalStorageDirectory().getPath()
+ "/"
+ Helper.IMG_FOLDER + "/" + dateFileName);
if (!sdImageMainDirectory.exists()) { // if folder not exists it
// created
sdImageMainDirectory.mkdirs();
}
// setting image path to sd card/Img_folder in helper
// class/todays date folder
image_PATH = Environment.getExternalStorageDirectory()
.getPath()
+ "/"
+ Helper.IMG_FOLDER
+ "/"
+ dateFileName + "/";
// creating a new file(jpg) at above image path
File file = new File(image_PATH, curentDateandTime + ".jpg");
// re-initilization of image_PATH to new file(jpg)
image_PATH = image_PATH + curentDateandTime + ".jpg";
savePreferences();
// creating an uri for file
Uri outputFileUri = Uri.fromFile(file);
Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
i.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(i, 1234);
} catch (Exception e) {
Helper.AlertBox(this,
"Error No: 001\nPlease Contact Technical Person.\n"
+ e.toString());
}
} else {
Helper.AlertBox(this, "Camera Not Found.!");
}
}
private void savePreferences() {
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("image_PATH", image_PATH);
// Commit the edits!
editor.commit();
}
private void restorePreferences() {
SharedPreferences settings = getPreferences(MODE_PRIVATE);
image_PATH = settings.getString("image_PATH", "");
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// image_PATH = "";
image_str = "";
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1234) {
if (resultCode == RESULT_OK) {
restorePreferences();
System.out.println("image_PATH :" + image_PATH);
File file = new File(image_PATH);
if (file.exists()) {
Log.e("File exist :", "File exist at " + image_PATH);
FileInputStream in;
BufferedInputStream buf;
try {
// in = new FileInputStream(image_PATH);
// buf = new BufferedInputStream(in);
// bMap = BitmapFactory.decodeStream(buf);
// iv_image.setVisibility(View.VISIBLE);
// iv_image.setImageBitmap(bMap);
// ConstantClass.image_PATH = image_PATH;
// if (in != null) {
// in.close();
// }
// if (buf != null) {
// buf.close();
// }
intent = new Intent(TakePhoto.this, PhotoPreview.class);
intent.putExtra("index", Helper.index);
Log.e("test", "0");
Helper.bitMap[Helper.index] = image_PATH;
Log.e("test", "1");
Helper.btn[Helper.index] = false;
Log.e("test", "2");
startActivity(intent);
Log.e("test", "3");
// Helper.AlertBox(this, "Image Captured.");
} catch (Exception e) {
Helper.AlertBox(this,
"Error No: 004\nPlease contact technical person.\n"
+ e.toString());
Log.e("Error reading file", e.toString());
}
} else {
Helper.AlertBox(this,
"Error No: 005\nPlease contact technical person.");
}
} else {
Toast.makeText(getApplicationContext(), "Cam Not Supported",
5000).show();
}
}
}
// camera code end
when i click on image Button,openCamera() will be called.
Thanks in advance
Your problem has no relation to the Camera or Shared Preferences. The same can happen to any activity that goes off screen.
After an activity returns from onPaused() callback, the system has no obligations to keep the instance in memory. But, if you call Activity.finish() at some point, the object will be destroyed for sure.
Anyway, the idea to save Activity1 state in Shared Preferences is a viable one. The preferred alternative is to use Activity.onSaveInstanceState(), but it does not make your life much easier, and is not safer.
I'm developing an app using Cordova 2.6 and I have a problem using the camera.getPicture function on older phones (that don't have gigs of memory).
When the app opens the camera, it (the app) is moved to the background. Then Android's Garbage Collector kicks in and kills the app. So when I've taken my picture and it is returned to my app it crashes (Force Close) with a null pointer exception.
The problem is well known but is not documented as a 'quirck'.
Here's someone else with the same problem:
Camera example from the docs page fails on android 2.3.x
The biggest problem I have is that I can't detect this. If I could I might give the user a warning but now it just force closes and ruins the experience.
EDIT: here's the exception from logcat:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=null} to activity
Help?
One solution is to create a custom camera plugin and save your image to a set image file. When the app reloads may it be a crash or a forced closed due to memory check for the existence of that file and continue.
This would require some saving a state before the camera was called so that the app could reinitialize to handle image.
The place I believe to put a check for a previouly taken image could be in the onCreate method in your main class or onActivityResult in the camera plugin
Here is a similar thread Taking a picture from the camera fails 20% of the time
Bellow is code for is what I have started on this but handling all the different camera bugs can be problematic, ie Android ACTION_IMAGE_CAPTURE Intent
To get this to work for this task you need to use the getExternalSaveFile method to save your file and then modify your oncreate / onactivityresult to handle the restarting of the app.
Here is Javascript to the call plugin
CameraSW.takePhoto("onPhotoURISuccess");
//Then, to get the location of the photo after you take it and load the page again
var imgPath = CameraSW.getPhotoUri();
console.log("capturePhotoEdit: imgPath " + imgPath);
function onPhotoURISuccess(imageURI) {
}
Register your main app so you can reach the functions in javascript
static public Uri getCameraSaveFile(Context context, String directory,
String basename, boolean fixed, String ext) {
String fileName = your_app.getImageFileName(basename, fixed,ext);
//"" + System.currentTimeMillis() + ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,
"Image capture by camera");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
Uri imageUri = context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Log.i("MainActivity",
"new image uri to string is " + imageUri.toString());
Log.i("MainActivity", "new image path is " + imageUri.getPath());
return imageUri;
}
static public Uri getExternalSaveFile(String directory, String basename,
boolean fixed, String ext) {
try {
Uri newImageUri = null;
if (ext == null)
ext = "jpg";
String dir_name = Environment.getExternalStorageDirectory()
.getPath() + "/" + directory + "/";
File path = new File(dir_name);
Log.e(TAG, "getExternalSaveFile path = "
+Environment.getExternalStorageDirectory().getPath() + "/"
+ directory + "/");
// crashing here ? wtf
if (!path.exists()) {
try {
Log.i(TAG, "getExternalSaveFile: mkdirs" + dir_name);
path.mkdirs();
} catch (Exception e) {
Log.e(TAG,
"getExternalSaveFile: mkdir error" + e.getMessage());
}
}
if (!path.isDirectory()) {
Log.e(TAG, "getExternalSaveFile: file is not directory"
+ dir_name);
return null;
}
boolean setWritable = false;
setWritable = path.setWritable(true, false);
if (!setWritable) {
Log.e(TAG,
"getExternalSaveFile Failed to set the file to writable");
}
File file = new File(path, your_app.getImageFileName(basename, fixed,
ext));
newImageUri = Uri.fromFile(file);
Log.i(TAG, "getExternalSaveFile new image uri to string is "
+ newImageUri.toString());
Log.i(TAG,
"getExternalSaveFile new image path is "
+ newImageUri.getPath());
return newImageUri;
} catch (Exception e) {
Log.e(TAG, "getExternalSaveFile: main error" + e.getMessage());
}
return null;
}
static public String getImageFileName(String basename, boolean fixed,
String ext) {
String file = null;
if (fixed) {
file = basename + "." + ext;
} else {
file = basename + System.currentTimeMillis() + "." + ext;
}
return file;
}
public void takePhoto(final String callback) {
Log.v(TAG, "takePhoto: Starting takePhoto: " + callback);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Log.v(TAG, "takePhoto: new intent");
//Uri path = getExternalSaveFile("your_app", "question_", true, "jpg");
Uri path = getCameraSaveFile(this,"your_app", "question_", true, "jpg");
if (path == null) {
Log.e(TAG, "takePhoto: path is not writable or can not be found");
// should pass error on ward to phonegap
return;
}
image_uri = path.toString();
intent.putExtra(MediaStore.EXTRA_OUTPUT, path);
Log.v(TAG, "takePhoto: getExternalSaveFile");
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
// Intent intent = new
// Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
// Uri.fromFile(new File(folderPath, filePath)));
if (your_app.webView != null && your_app.webView.pluginManager != null) {
CameraSWPlugin plugin = (CameraSWPlugin)your_app.webView.pluginManager.getPlugin("CameraSW");
if (plugin == null) {
Log.e(TAG, "takePhoto: startActivityForResult: plugin CameraSWPlugin null make sure plugin is listed in config.xml <plugin name=\"CameraSW\" value=\"com.your_app.your_app.CameraSWPlugin\" />");
throw new NullPointerException("takePhoto: startActivityForResult: plugin CameraSWPlugin null make sure plugin is listed in config.xml <plugin name=\"CameraSW\" value=\"com.your_app.your_app.CameraSWPlugin\" />");
} else {
plugin.setPath(path);
plugin.setSuccess_callback(callback);
startActivityForResult(
plugin,
intent, TAKE_PICTURE);
Log.v(TAG, "takePhoto: startActivityForResult");
}
} else {
// should not happen
Log.v(TAG, "webView or Pluginmanager not read");
}
}
public String getPhotoUri() {
return image_uri;
// return Uri.fromFile(new File(folderPath, filePath)).toString();
}
The plugin file CameraSWPlugin.java
package com.your_app.your_app;
import static com.your_app.your_app.CommonUtilities.TAKE_PICTURE;
import java.io.File;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import static com.your_app.your_app.CommonUtilities.TAG;
/**
* I did not include the
* This class echoes a string called from JavaScript.
*/
public class CameraSWPlugin extends CordovaPlugin {
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("echo")) {
String message = args.getString(0);
your_app.invalidate();
this.echo(message, callbackContext);
return true;
}
return false;
}
private void echo(String message, CallbackContext callbackContext) {
if (message != null && message.length() > 0) {
callbackContext.success(message);
} else {
callbackContext.error("Expected one non-empty string argument.");
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v(TAG, "Photo onActivityResult requestCode = " + requestCode + " resultCode = " + resultCode + " data = " + data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK) {
//Do whatever you need to do when the camera returns
//This is after the picture is already saved, we return to the page
if (this.path != null) {
//
try {
this.sendJavascript(path.toString());
} catch (Exception e) {
Log.v(TAG, "onActivityResult: path json error " + e.getMessage());
e.printStackTrace();
}
} else {
Log.v(TAG, "onActivityResult: path was not set " + requestCode);
}
}
break;
default:
Log.v(TAG, "Something strange happened... " + requestCode);
break;
}
}
private String success_callback = null;
private Uri path = null;
public String getSuccess_callback() {
return success_callback;
}
public void setSuccess_callback(String success_callback) {
this.success_callback = success_callback;
}
public void sendJavascript( JSONObject _json )
{
String _d = "javascript:"+this.success_callback+"(" + _json.toString() + ")";
Log.v(TAG + ":sendJavascript", _d);
if (this.success_callback != null ) {
this.webView.sendJavascript( _d );
}
}
public void sendJavascript( String _json )
{
String _d = "javascript:"+this.success_callback+"(" + JSONObject.quote(_json) + ")";
Log.v(TAG + ":sendJavascript", _d);
if (this.success_callback != null ) {
this.webView.sendJavascript( _d );
}
}
public void setPath(Uri path) {
this.path = path;
}
}
And be sure to add to your config.xml
<plugin name="CameraSW" value="com.your_app.your_app.CameraSWPlugin" />
For ME there is a bug in the camera plugin. I fixed it for MY situation. This may or may not apply to yours.
Scenario:
Using a tablet where the NATIVE CAMERA APP rotates to Landscape when it launches.
My app is running in portrait. Because of this it needs to saveInstance var's and reload them.
What I found and what I fixed:
First look at ProcessResultFromCamera function -> these lines:
String sourcePath = (this.allowEdit && this.croppedUri != null) ?
this.croppedFilePath :
this.imageFilePath;
It's using imageUri but saving imageFilePath? Maybe this is intended maybe not.
I added a quick debug helper class to push out Toasts. I added Toasts all throughout CameraLauncher.java.
I looked at onSaveInstanceState and noticed a couple things:
imageFilePath is not being stored anywhere in onSaveInstanceState so when the Activity recreates itself...the imageFilePath that was initially created is now null. This imageFilePath is what's passed into ExifInterface. If you note ABOVE...sourcePath is assigned to imageFilePath.
This would explain why we get the "filename cannot be null" as that specific exception is thrown in ExifInterface.java I believe.
**_exif.createInFile(sourcePath);_** <<---- sourcePath is null
exif.readExifData();
rotate = exif.getOrientation();
if (this.**imageUri** != null) {
state.putString(IMAGE_URI_KEY, this.**imageFilePath**);
}
The Fix??
Update imageUri in onSaveInstanceState. Add imageFileName to onSaveInstanceState.
Add imageFileName to onRestore
here's the actual code to update/add in onSaveInstanceState:
if (this.imageUri != null) {
state.putString(IMAGE_URI_KEY, String.valueOf(this.imageUri));
}
if (this.imageFilePath != null) {
state.putString(IMAGE_FILE_PATH_KEY, this.imageFilePath);
}
here's the code to ADD in onRestoreStateForActivityResult:
if (state.containsKey(IMAGE_FILE_PATH_KEY)) {
this.imageFilePath = state.getString(IMAGE_FILE_PATH_KEY);
}
I ran into an issue with something that I am probably just overlooking.
I want to take a picture from the surface preview of the camera, and save it to the sd_card. This works ALMOST perfect. I assigned it a file name, but it does not use the filename.
This is what I have been trying to do :
Button imagecapture = (Button) findViewById(R.id.imagecapture);
imagecapture.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String filename = null;
ImageCaptureCallback iccb = null;
try {
filename = timeStampFormat.format(new Date());
ContentValues values = new ContentValues();
values.put(Media.TITLE, filename);
values.put(Media.DESCRIPTION, "Image capture by camera");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
iccb = new ImageCaptureCallback(getContentResolver().openOutputStream(uri));
} catch (Exception ex) {
ex.printStackTrace();
Log.e(getClass().getSimpleName(), ex.getMessage(), ex);
}
camera.takePicture(mShutterCallback, mPictureCallbackRaw, iccb);
com.froogloid.android.gspot.Park.imageFileName = filename;
}
});
It won't use the filename (i.e. time/date stamp I ask it to.)
This was resolved by implementing PictureCallback via a ImageCaptureCallback class, and Overriding the onPictureTaken where the file was being written via a file output stream. All you had to do was change the fileoutput stream to the filename you want.
it doesn't save image? in my app this code saves image, maybe you use variable "filaname" to get image from sdcard? to use image from sdcard is better to save in variable, for examople, "fileUri" value of uri.toString, end get from sdcard file with uri Uri.parse(fileUri)..
Hope this helps / Probably not the best way to go about it, but it worked.
Here you go:
This is the camera capture image callback.
public class ImageCaptureCallback implements PictureCallback {
private OutputStream filoutputStream;
public ImageCaptureCallback(OutputStream filoutputStream) {
this.filoutputStream = filoutputStream;
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
try {
Log.v(getClass().getSimpleName(), "onPictureTaken=" + data + " length = " + data.length);
FileOutputStream buf = new FileOutputStream("/sdcard/dcim/Camera/" + CameraActivity.filename + ".jpg");
buf.write(data);
buf.flush();
buf.close();
// filoutputStream.write(data);
filoutputStream.flush();
filoutputStream.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}