getting gps position after taking photo - android

I tried to get the gps position when i taking a photo. i saved the position of the location-listener when the LocationChanged method is running in a variable and want to show it when i take a photo. Is this the right way? I use android 2.3.6.
Here my code:
package com.exercise;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
public class AndroidCamera extends Activity implements SurfaceHolder.Callback{
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
Button buttonTakePicture;
final int RESULT_SAVEIMAGE = 0;
public Location test;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.control, null);
LayoutParams layoutParamsControl
= new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);
buttonTakePicture = (Button)findViewById(R.id.takepicture);
buttonTakePicture.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback,
myPictureCallback_RAW, myPictureCallback_JPG);
}});
LinearLayout layoutBackground = (LinearLayout)findViewById(R.id.background);
layoutBackground.setOnClickListener(new LinearLayout.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
buttonTakePicture.setEnabled(false);
camera.autoFocus(myAutoFocusCallback);
}});
}
public class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location loc){
loc.getLatitude();
loc.getLongitude();
String Text = "Lat = " + loc.getLatitude() + "|Long = " + loc.getLongitude();
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
// final TextView tv = (TextView) findViewById(R.id.text);
// tv.setText(tv.getText()+ "||" + Text);
test = loc;
}
#Override
public void onProviderDisabled(String provider){
Toast.makeText( getApplicationContext(),"Gps Disabled", Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider){
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras){
}
}
AutoFocusCallback myAutoFocusCallback = new AutoFocusCallback(){
#Override
public void onAutoFocus(boolean arg0, Camera arg1) {
// TODO Auto-generated method stub
buttonTakePicture.setEnabled(true);
}};
ShutterCallback myShutterCallback = new ShutterCallback(){
#Override
public void onShutter() {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_RAW = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
/*Bitmap bitmapPicture
= BitmapFactory.decodeByteArray(arg0, 0, arg0.length); */
Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
// Toast.makeText(AndroidCamera.this,
// "Image saved: " + uriTarget.toString(),
// Toast.LENGTH_LONG).show();
// test.getLatitude();
// test.getLongitude();
// String Text = "Lat = " + test.getLatitude() + "|Long = " + test.getLongitude();
// Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
if (test==null){
Toast.makeText(AndroidCamera.this, "null", Toast.LENGTH_SHORT).show();
}
else{
test.getLatitude();
String ausgabe = String.valueOf(test.getLatitude());
Toast.makeText(AndroidCamera.this, ausgabe, Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
}};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}

Yes, this is a fair way to do it. By the way, you can instead .requestSingleUpdate(), since you'll be wanting only one update. You should also probably not wait until the GPS information arrives (and, you can also specify something different than a gps provider, like, any provider, which may respond quicker -- as opposed to a possible cold start from GPS). If none of that works, you can always query for the last known location. Since the update may not arrive for a while, you should probably save the image data somewhere lazily (without location information), and then update the information when location becomes available.

Related

Android camera startPreview failed error

I want to simply take a photo in android (actually with an overlay image....but do it later, I am now failing in the first step...), the log catch an error of 'start preview failed'. The following is my code:
package com.example.camera_test;
import java.io.IOException;
import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CameraFilming extends Activity implements SurfaceHolder.Callback{
private Camera camera = null;
private SurfaceView preview;
private SurfaceHolder holder;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
((Setting)getApplication()).getDeviceDisplaySize();
preview = (SurfaceView)findViewById(R.id.camera_surface);
holder = preview.getHolder();
holder.addCallback(this);
}
private void startCamera(){
camera = Camera.open();
}
#Override
public void onBackPressed(){
super.onBackPressed();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
try {
startCamera();
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera.release();
camera = null;
}
}
I run it on a real device and then it gets no problem...conclusion: don't do camera simulation on an AVD emulator!!!

Android camera app gives error on back and home button

My Application gives error "Unfortunately PhotoComment has stopped" when I am pressing back or home button. But when I am reopening app from task manager it works.
this is my mainactivity.java
package com.cameratag;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity{
private CameraSurfaceView cameraView;
private ImageView imageResult;
private ImageView imageResult2;
private FrameLayout framenew;
private TextView snapPhoto;
private boolean takePicture = true;
private Bitmap image = null;
private String lastPreviewImgPath = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupcamera();
}
public void setupcamera(){
cameraView = new CameraSurfaceView(getApplicationContext());
imageResult = new ImageView(getApplicationContext());
imageResult.setBackgroundColor(Color.GRAY);
framenew = (FrameLayout) findViewById(R.id.frame);
snapPhoto = (TextView) findViewById(R.id.textView1);
framenew.addView(imageResult);
framenew.addView(cameraView);
}
public void captureHandler(View view){
if(takePicture){
cameraView.capture(jpegHandler);
}
else{
takePicture = true;
cameraView.preview();
framenew.bringChildToFront(cameraView);
imageResult.setImageBitmap(null);
snapPhoto.setText("Capture");
}
}
public void zoomMinusHandler(View view){
cameraView.zoomMinus();
}
public void zoomPilusHandler(View view){
cameraView.zoomPilus();
}
public Camera.PictureCallback jpegHandler = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
image = BitmapFactory.decodeByteArray(data, 0, data.length);
imageResult.setImageBitmap(image);
imageResult2 = imageResult;
LayoutParams params = imageResult.getLayoutParams();
params.width = framenew.getWidth();
params.height = framenew.getHeight();
imageResult2.setLayoutParams(params);
//framenew.bringChildToFront(imageResult);
//snapPhoto.setText("Take Picture");
//takePicture = false;
File directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "NNCam");
if (!directory.exists()) {
if (!directory.mkdirs()) {
//Log.e(TAG, "Failed to create storage directory.");
}
}
String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss").format(new Date(System.currentTimeMillis()));
String filename = "/IMG_" + timeStamp + ".jpg";
if(image!=null){
saveImage(directory.getPath(),filename,image);
cameraView.preview();
}
}
};
public void saveImage(String path, String imgname, Bitmap image){
try{
FileOutputStream fos = new FileOutputStream(path+imgname);
BufferedOutputStream stream = new BufferedOutputStream(fos);
image.compress(CompressFormat.JPEG, 100, stream);
stream.flush();
stream.close();
}
catch(FileNotFoundException e){
}
catch(IOException e){
}
lastPreviewImgPath = path+imgname;
Bitmap bitmap = BitmapFactory.decodeFile(lastPreviewImgPath);
ImageView myImageView = (ImageView)findViewById(R.id.lastPreview);
myImageView.setImageBitmap(bitmap);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
cameraView.release();
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
cameraView.reconnect();
}
#Override
public void onPause() {
super.onPause();
cameraView.release();
}
}
and this is surfaceview class
package com.cameratag;
import java.io.IOException;
import java.util.List;
import android.content.Context;
import android.content.res.Configuration;
import android.hardware.Camera;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
public class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{
private Context context;
private SurfaceHolder mHolder;
public Camera camera = null;
public int zoomValue = 0;
public CameraSurfaceView(Context context) {
super(context);
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// TODO Auto-generated constructor stub
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
Camera.Parameters parameters = camera.getParameters();
List<Camera.Size> sizes = parameters.getSupportedPictureSizes();
Camera.Size cs = sizes.get(0);
List<Camera.Size> sizes2 = parameters.getSupportedPreviewSizes();
Camera.Size cs2 = sizes2.get(0);
parameters.setPreviewSize(cs2.width, cs2.height);
parameters.setPictureSize(cs.width, cs.height);
camera.setParameters(parameters);
camera.startPreview();
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
// TODO Auto-generated method stub
camera = Camera.open();
try {
camera.setPreviewDisplay(mHolder);
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
int rrr = 0;
Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();
if(rotation==0)rrr=90;
else if(rotation==1)rrr=0;
else if(rotation==3)rrr=180;
else rrr=270;
camera.setDisplayOrientation(rrr);
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
camera.stopPreview();
camera = null;
}
public void capture(Camera.PictureCallback jpegHandler){
camera.takePicture(null, null, jpegHandler);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int rrr = 0;
Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();
if(rotation==0)rrr=90;
else if(rotation==1)rrr=0;
else if(rotation==3)rrr=180;
else rrr=270;
//camera.stopPreview();
camera.setDisplayOrientation(rrr);
//camera.startPreview();
}
public void preview(){
camera.startPreview();
}
public void reconnect(){
try {
camera.reconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
}
public void zoomMinus() {
Camera.Parameters parameters = camera.getParameters();
// TODO Auto-generated method stub
if(parameters.isZoomSupported()){
if(zoomValue>0){
zoomValue-=2;
parameters.setZoom(zoomValue);
if(parameters.isSmoothZoomSupported()){
camera.startSmoothZoom(zoomValue);
}
else{
camera.setParameters(parameters);
}
}
}
}
public void zoomPilus() {
Camera.Parameters parameters = camera.getParameters();
// TODO Auto-generated method stub
if(parameters.isZoomSupported()){
if(zoomValue<parameters.getMaxZoom()){
zoomValue+=2;
parameters.setZoom(zoomValue);
if(parameters.isSmoothZoomSupported()){
camera.startSmoothZoom(zoomValue);
}
else{
camera.setParameters(parameters);
}
}
}
}
public void release() {
// TODO Auto-generated method stub
camera.setPreviewCallback(null);
camera.stopPreview();
camera.release();
}
}
Please help.
#Override
protected void onPause() {
super.onPause();
// if (inPreview) {
// mCamera.stopPreview();
// }
// mCamera.release();
// mCamera = null;
// inPreview = false;
mCamera.setPreviewCallback(null);
super.onPause();
// mCamera.stopPreview();
}
I was having a similar issue, the trick is to also setup the camera inside of onResume().
The issue was that the app does not call onCreate() every time you go to an activity with the back button, sometimes it simply pauses the activity. onResume() is called whenever the activity returns to the foreground and is a more reliable place to set up the camera.
#Override
protected void onResume()
{
super.onResume();
if( camera == null )
{
camera = Camera.open();
}
}
try to put your release code in try catch block
try{
if (camera != null){
camera.setPreviewCallback(null);
camera.stopPreview();
camera.release();
}
}
I have found the solution for my own. You only need to change surfaceDestroyed method to this.
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
try{
camera.stopPreview();
camera.release();
camera = null;
}
catch(NullPointerException e){
//e.printStackTrace();
}
}
and on onRestoreInstanceState to this.
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
cameraView = null;
setupcamera();
//cameraView.reconnect();
}

MediaPlayer: start called in state 0 error

This is what the code looks like, logcat keeps stating "start called in state 0"
I tried different ways to start the video. What am I missing? I also tried a OnPreparedListener but it kept giving me the same errors.
package com.example.videoplaybacktests;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity implements SurfaceHolder.Callback{
MediaPlayer mediaPlayer;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean pausing = false;;
String stringPath = "/drawable/visource.mp4";
public String RTSP = "rtsp://v2.cache7.c.youtube.com/CjYLENy73wIaLQkFPOlBtC4qExMYDSANFEIJbXYtZ29vZ2xlSARSBXdhdGNoYJeOw_HjwJ6bUQw=/0/0/0/video.3gp";
public Uri vidURI = Uri.parse(RTSP);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonPlayVideo = (Button)findViewById(R.id.playvideoplayer);
Button buttonPauseVideo = (Button)findViewById(R.id.pausevideoplayer);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.surfaceview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setFixedSize(176, 144);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mediaPlayer = new MediaPlayer();
buttonPlayVideo.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
pausing = false;
if(mediaPlayer.isPlaying()){
mediaPlayer.reset();
}
mediaPlayer.setDisplay(surfaceHolder);
try {
mediaPlayer.setDataSource(RTSP);
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
}});
buttonPauseVideo.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(pausing){
pausing = false;
mediaPlayer.start();
}
else{
pausing = true;
mediaPlayer.pause();
}
}});
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
You can not call start without the mediaPlayer being prepared! Thats the reason you get the error
Use prepareAsync instead
try {
mediaPlayer.setDataSource(RTSP);
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and start playback on onPrepared():
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
If it still doesnt start on onVideoSizeChanged
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
mediaPlayer.start();
}
package com.example.videoplaybacktests;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity implements SurfaceHolder.Callback{
MediaPlayer mediaPlayer;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean pausing = false;;
String stringPath = "/drawable/visource.mp4";
public String RTSP = "rtsp://v2.cache7.c.youtube.com/CjYLENy73wIaLQkFPOlBtC4qExMYDSANFEIJbXYtZ29vZ2xlSARSBXdhdGNoYJeOw_HjwJ6bUQw=/0/0/0/video.3gp";
public Uri vidURI = Uri.parse(RTSP);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonPlayVideo = (Button)findViewById(R.id.playvideoplayer);
Button buttonPauseVideo = (Button)findViewById(R.id.pausevideoplayer);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.surfaceview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setFixedSize(176, 144);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mediaPlayer = new MediaPlayer();
buttonPlayVideo.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
}
mediaPlayer.setDisplay(surfaceHolder);
try {
mediaPlayer.setDataSource(RTSP);
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}});
buttonPauseVideo.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mediaPlayer==null)
return;
else if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
}else{
mediaPlayer.start();
}
}});
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
mediaPlayer.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}

Updating a EditText after camera take photo

i have 2 activity. activity saveData and activity androidCamera
first, i have a form in saveData. when form is already inputed except EditText "Upload Photo". then, i click button camera to take a uri/path image. when finish() the camera activity send value uri/path back to SaveData form Activity. the question is how to updating EditText "Upload Photo" in SaveData so when i take picture, the camera send path/uri inside EditText "Upload Photo"?
this is my Activity AndroidCamera
package com.app.databasesample;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.Toast;
public class AndroidCamera extends Activity implements SurfaceHolder.Callback{
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
final int RESULT_SAVEIMAGE = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_camera);
//
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.control, null);
LayoutParams layoutParamsControl
= new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);
Button buttonTakePicture = (Button)findViewById(R.id.takepicture);
buttonTakePicture.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback,
myPictureCallback_RAW, myPictureCallback_JPG);
}});
}
ShutterCallback myShutterCallback = new ShutterCallback(){
#Override
public void onShutter() {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_RAW = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
/*Bitmap bitmapPicture
= BitmapFactory.decodeByteArray(arg0, 0, arg0.length); */
Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(AndroidCamera.this,
"Image Tersimpan: " + uriTarget.toString(),
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String sFilename="image";
Bundle bundle = new Bundle();
bundle.putString("path", uriTarget.toString());
Intent newIntent = new Intent(AndroidCamera.this, SaveData.class);
newIntent.putExtras(bundle);
startActivityForResult(newIntent, 0);
//
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}
this is my Activity SaveData
package com.app.databasesample;
import java.io.File;
import java.util.Date;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
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.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class SaveData extends Activity implements OnClickListener {
private DataManipulator dh;
static final int DIALOG_ID = 0;
private static final boolean TEST_ONLY_NO_FOTO=false;
private static final boolean TAKE_FOTO_HIRES=false;
private Uri outputFileUri;
File outputFile;
private String sDirectory="";
//String sFilename="";
public static final int SHOW_SUB_ACTIVITY_TAKE_PICTURE=5;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.save);
View add = findViewById(R.id.Button01add);
add.setOnClickListener(this);
View home = findViewById(R.id.Button01home);
home.setOnClickListener(this);
View kamera = findViewById(R.id.kamera);
kamera.setOnClickListener(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (SHOW_SUB_ACTIVITY_TAKE_PICTURE) : {
if (resultCode == Activity.RESULT_OK) {
String newText = data.getStringExtra("image");
// TODO Update your TextView.
//EditText edt = (newText) findViewById(R.id.txtStatus);
//edt.setText(uriTarget.toString());
EditText edt = (EditText) findViewById(R.id.txtStatus);
edt.setText(newText);
}
break;
}
}
}
public void onClick(View v){
switch(v.getId()){
case R.id.Button01home:
Intent i = new Intent(this, DatabaseSample.class);
startActivity(i);
break;
case R.id.Button01add:
View editText1 = (EditText) findViewById(R.id.idHandheld);
View editText2 = (EditText) findViewById(R.id.namaHama);
View editText3 = (EditText) findViewById(R.id.jumlahHama);
String myEditText1=((TextView) editText1).getText().toString();
String myEditText2=((TextView) editText2).getText().toString();
String myEditText3=((TextView) editText3).getText().toString();
this.dh = new DataManipulator(this);
this.dh.insert(myEditText1,myEditText2,myEditText3);
showDialog(DIALOG_ID);
break;
case R.id.kamera:
Intent i1 = new Intent(this, AndroidCamera.class);
startActivityForResult(i1,SHOW_SUB_ACTIVITY_TAKE_PICTURE);
break;
}
}
private void SaveDatas(){
Date dt=new Date();
View editText4 = (EditText) findViewById(R.id.idHandheld);
View editText5 = (EditText) findViewById(R.id.namaHama);
View editText6 = (EditText) findViewById(R.id.jumlahHama);
String myEditText4=((TextView) editText4).getText().toString();
String myEditText5=((TextView) editText5).getText().toString();
String myEditText6=((TextView) editText6).getText().toString();
this.dh = new DataManipulator(this);
this.dh.insert(myEditText4,myEditText5,myEditText6);
showDialog(DIALOG_ID);
}//SaveData
protected final Dialog onCreateDialog(final int id) {
Dialog dialog = null;
switch(id){
case DIALOG_ID:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("input data hama sukses disave | Tambah Input ?").setCancelable(false).setPositiveButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id){
SaveData.this.finish();
}
}).setNegativeButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
dialog = alert;
break;
default:
}
return dialog;
}
}
Write below line before setContentView(R.layout.save); in onCreate() method of SaveData Activity, it will solve your problem.
EditText edt = (EditText) findViewById(R.id.txtStatus);
You should call the method "setResult" to submit your result to the calling Activity and then check the result in "onResume".
But a general hint for you. In Android you can leverage the Intent system for the benefit of the user. One example would be to let the user choose his camera app to take the picture instead of writing your own activity for this. This saves you a lot of time and the user is happy he can use the specific camera app which suits his needs and that he hunted down for hours and paid for it.
This is you have done in AndroidCamera activity :
Bundle bundle = new Bundle();
bundle.putString("path", uriTarget.toString());
Intent newIntent = new Intent(AndroidCamera.this, SaveData.class);
newIntent.putExtras(bundle);
startActivityForResult(newIntent, 0);
Change this line
startActivityForResult(newIntent, 0);
to
startActivity(newIntent);
Now, Just call this code to your SaveData Activity :
UPDATE :
String imagePath="";
if(getIntent().getExtras() != null){
imagePath = getIntent().getExtras().getString("path");
your_editText.setText(imagePath);
}
Hope this helps you.
Thanks.

Android Camera Program

I am new to Android I have written a small program to take pictures and save them in the internal memory disk. My program is successfully launched but when I take pictures no data is written to the memory disk.
Below is my code. What am I missing?
package com.lab2;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.os.Environment;
public class Lab2_cameraActivity extends Activity implements SurfaceHolder.Callback {
/** Called when the activity is first created. */
private Camera mCamera;
private SurfaceHolder mHolder;
private SurfaceView mSurfaceView;
private Button mbutton1;
private ShutterCallback shutter;
private PictureCallback raw;
private PictureCallback postview;
AutoFocusCallback AFCallback = new AutoFocusCallback(){
#Override
public void onAutoFocus(boolean success, Camera camera) {
// TODO Auto-generated method stub
if (success){
mCamera.takePicture(shutter, raw, postview, jpeg);//take photo
}else{
Toast.makeText(Lab2_cameraActivity.this, "in else...",Toast.LENGTH_LONG).show();
}
}
};
/*jpeg callback occurs when the compressed image is available*/
PictureCallback jpeg = new PictureCallback(){
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
FileOutputStream outStream = null;
File file = new File("/mnt/sdcard/");
try {
outStream = new FileOutputStream(file.toString()+"photo.jpg");
outStream.write(data);
outStream.close();
Toast.makeText(Lab2_cameraActivity.this, "Photo Saved...",Toast.LENGTH_LONG).show();
mCamera.startPreview();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
/*when surface destroyed, stop preview*/
if(mCamera != null){
mCamera.stopPreview();
mCamera.release();//release camera resources
mCamera = null;
}
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
mCamera = Camera.open();//open camera
try {
mCamera.setPreviewDisplay(holder);//set surface to display
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
/*when surface changed, reset camera parameters for preview*/
mCamera.getParameters();//get default parameters
Camera.Parameters parameters= mCamera.getParameters();
/*you can set your own parameters in there*/
mCamera.setParameters(parameters);//set parameters if parameters has been changed
mCamera.startPreview();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mbutton1 = (Button)findViewById(R.id.button1);
mSurfaceView = (SurfaceView)findViewById(R.id.surfaceView);
mHolder = mSurfaceView.getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mbutton1.setOnClickListener(new Button.OnClickListener()
{
#Override
public void onClick(View v) {
mCamera.autoFocus(AFCallback);
}
});
}
}
you should not specify '/mnt/whatever/' path to your sdcard, use getExternalFilesDir() to get the correct path.
your callback is not called, unless you specify it in mCamera.takePicture(null, null, jpeg);
do you really have
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
in your AndroidManifest.xml file?

Categories

Resources