Updating a EditText after camera take photo - android

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.

Related

Send Photo from activity to another activity

I need to take photo and send in MainActivity and send it to thirdActivity
this is the code of MainActivity
PS : I opened Main activity From ThirdActivity
package com.fakecamera.hassanechafai.fakacamera;
import java.io.File;
import com.fakecamera.hassanechafai.fakacamera.R;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import com.fakecamera.hassanechafai.fakacamera.CameraPreview;
import com.fakecamera.hassanechafai.fakacamera.MyAlertDialogs;
import com.fakecamera.hassanechafai.fakacamera.NoCameraPresentDialog;
public class MainActivity extends Activity {
private Camera mCamera;
private CameraPreview mCameraPreview;
public static Display display;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
mCamera = this.getCameraInstance();
if (mCamera == null) {
NoCameraPresentDialog noCamera = new NoCameraPresentDialog(
MainActivity.this);
noCamera.showDialog();
} else {
mCameraPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
ImageButton captureButton = (ImageButton) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
// mCamera.startPreview();
}
});
}
}
private Camera getCameraInstance() {
Camera camera = null;
Log.d("No of cameras", Camera.getNumberOfCameras() + "");
for (int camNo = 0; camNo < Camera.getNumberOfCameras(); camNo++) {
CameraInfo camInfo = new CameraInfo();
Camera.getCameraInfo(camNo, camInfo);
if (camInfo.facing == (Camera.CameraInfo.CAMERA_FACING_FRONT)) {
camera = Camera.open(camNo);
}
}
return camera;
}
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
notifyImageCapture(pictureFile.getPath());
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
public void notifyImageCapture(String filepath) {
Intent i = new Intent(this, ThirdActivity.class);
i.putExtra("path", "" + filepath);
startActivityForResult(i, 100);
}
public static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(), "Photos");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("Photos", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
Log.i("Mediapath", "" + mediaFile.getPath());
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 100) {
this.finish();
startActivity(new Intent(this, MainActivity.class));
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
MyAlertDialogs dialogs = new MyAlertDialogs(MainActivity.this);
dialogs.getRateMyAppDialog();
}
return super.onKeyDown(keyCode, event);
}
}
this is my code of thirdActivity
package com.fakecamera.hassanechafai.fakacamera;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.content.Intent;
import android.os.Handler;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.graphics.Bitmap;
import com.fakecamera.hassanechafai.fakacamera.LoadImageBitmap;
public class ThirdActivity extends ActionBarActivity {
private ImageView imageToEdit;
private Bitmap orignalBitmap;
private String CLICKED_IMAGE_FILE_PATH;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
ImageButton takeimage = (ImageButton)findViewById(R.id.imageButton3);
takeimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ThirdActivity.this,
MainActivity.class);
startActivity(intent);
}
});
imageToEdit = (ImageView) this.findViewById(R.id.item_click_image);
final EditText edittext = (EditText)findViewById(R.id.editText);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int time = Integer.parseInt(edittext.getText().toString());
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent startActivity = new Intent(ThirdActivity.this, FullscreenActivity.class);
startActivity(startActivity);
finish();
}
}, time * 1000);
}
});
CLICKED_IMAGE_FILE_PATH = getIntent().getStringExtra("path");
this.setUpImage(CLICKED_IMAGE_FILE_PATH);
}
public void setUpImage(String path) {
LoadImageBitmap imageLoader = new LoadImageBitmap();
orignalBitmap = imageLoader.displayFullImage(path);
if(CameraPreview.isPortrait){
orignalBitmap = ImageEffects.rotate(imageLoader.displayFullImage(path));
}else{
orignalBitmap=imageLoader.displayFullImage(path);
}
imageToEdit.setImageBitmap(orignalBitmap);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_third, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I have any error but when I trying to take a photo I get this message :
Unfortunately ,FirstCamera has stopped
what is my problem ?
You should call startActivityForResult from ThirdActivity and then set the photo as result in your MainActivity. For this you will need to make sure your photo model implements Parcelable.
You can then call setResult(RESULT_OK, Photo) in MainActivity and you will get the photo back in ThirdActivity in the method onActivityResult
If your photo is too large, you should convert it to bytes array to put it to Intent

GridView: Setting the selected image as a wallpaper

Right I've looked at a shed load of tutorials, questions and so on but none have worked, so I don't need more links, I just need a fix for my current code..
So far I have this:
public class FullscreenActivity extends Activity {
protected int[] mThumbIds;
#SuppressWarnings("unused")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fullscreen);
// get intent data
Intent i = getIntent();
// Selected image id
final int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
Button SetWallpaper = (Button)findViewById(R.id.setwallpaper);
imageView.setImageResource(imageAdapter.mThumbIds[position]);
}
private Object[] imageIDs;
private int position;
public void onClick(View arg0) {
try {
WallpaperManager.getInstance(this).setResource((Integer) imageIDs[position]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
But when I click the button once the picture has been selected, it doesn't do anything?
I also have the permission in the manifest but it still doesn't work, so any help would be hugely appreciated
Thank you
I'm not sure if this has anything to do with it or not but I'm testing the app on a Samsung Galaxy S4
May be it can relate..
package com.Engr.android;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
public class Camera extends Activity implements View.OnClickListener
{
ImageButton ib;
ImageView iv;
Button btn;
Intent i;
final static int cameraData = 0;
Bitmap bmp;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.photo);
Buttons();
InputStream is = getResources().openRawResource(R.drawable.ic_launcher);
bmp = BitmapFactory.decodeStream(is);
}
private void Buttons()
{
ib = (ImageButton) findViewById(R.id.ibtnTakePic);
iv = (ImageView) findViewById(R.id.ivReturnPic);
btn = (Button) findViewById(R.id.btnSetWall);
btn.setOnClickListener(this);
ib.setOnClickListener(this);
}
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.btnSetWall:
try {
getApplicationContext().setWallpaper(bmp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case R.id.ibtnTakePic:
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, cameraData);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK)
{
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
iv.setImageBitmap(bmp);
}
}
}

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();
}

Native method not found org.opencv.core.mat.n_mat-Android

I followed all steps when dealing with Mat including adding it to AsyncTask when calling but still the same error which is native method not found org.opencv.core.mat.n_mat
Here's the code:
package com.example.myfirstapp;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import org.json.JSONException;
import org.json.JSONObject;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.Mat;
import com.example.myfirstapp.RegisterMarkerMain.ProcessImage;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.Base64;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class CreateApp extends ListActivity {
boolean duplicate = false;
String userID = "";
Intent manage;
String image = "";
Intent refresh;
CandidatesListAdapter adapter;
ProcessImage process;
Mat mRgba;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
Log.i("loading libs", "OpenCV loading status " + status);
switch (status) {
case LoaderCallbackInterface.SUCCESS: {
Log.i("loading libs", "OpenCV loaded successfully");
// Load native library after(!) OpenCV initialization
System.loadLibrary("native_sample");
}
break;
default: {
super.onManagerConnected(status);
}
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_app);
manage = new Intent(this, ManageApps.class);
concurrentTasks();
Bundle extras = getIntent().getExtras();
if (extras != null) {
userID = extras.getString("user_id");
Toast.makeText(CreateApp.this, "User id " + userID,
Toast.LENGTH_LONG).show();
}
final Spinner spinner = (Spinner) findViewById(R.id.categories_spinner);
refresh = new Intent(this, ManageApps.class);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.categories_array,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView, int position, long id) {
// your code here
String category = spinner.getSelectedItem().toString();
Toast.makeText(CreateApp.this,
"Category " + category + " selected",
Toast.LENGTH_SHORT).show();
TextView tv = (TextView) findViewById(R.id.question_title);
tv.setText(category);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
ImageView iv = (ImageView) findViewById(R.id.application_logo);
registerForContextMenu(iv);
iv.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View arg0) {
// TODO Auto-generated method stub
return false;
}
});
iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(CreateApp.this, "Long click to add image",
Toast.LENGTH_LONG).show();
}
});
Button submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
EditText et = (EditText) findViewById(R.id.application_name_edit);
if (et.getText().toString().equals(null)
|| et.getText().toString().equals("")) {
Toast.makeText(CreateApp.this,
"App Name can not be empty.", Toast.LENGTH_SHORT)
.show();
} else {
if (spinner.getSelectedItem().toString().equals("Select")
|| spinner.getSelectedItem().toString().equals("")) {
Toast.makeText(CreateApp.this,
"Cateory must be selected.", Toast.LENGTH_SHORT)
.show();
} else {
new AsyncAppDuplicates().execute();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (duplicate == true) {
System.out
.println("Duplicate flag for App Creation inside if "
+ duplicate);
AlertDialog.Builder builder = new AlertDialog.Builder(
CreateApp.this);
builder.setTitle("Warning");
builder.setMessage("An application already exists with this name."
+ "\n" + "Please choose a different name.");
builder.setNegativeButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog, int id) {
// if this button is clicked, just
// close
// the dialog box and do nothing
dialog.cancel();
}
});
builder.show();
} else {
concurrentCreate();
Toast.makeText(CreateApp.this,
"Created Successfully", Toast.LENGTH_SHORT)
.show();
System.out.println("Done");
// EditText app = (EditText)
// findViewById(R.id.application_name_edit);
}
}
}
}
});
}
#SuppressLint("NewApi")
private void concurrentTasks() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
new AsyncGetCategories()
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
System.out.println("getting categories");
} else {
new AsyncGetCategories().execute();
}
}
#SuppressLint("NewApi")
private void concurrentCreate() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
new AsyncCreateApplication()
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
System.out.println("Creating app");
} else {
new AsyncCreateApplication().execute();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
finish();
manage.putExtra("user_id", userID);
startActivity(manage);
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.create_app, menu);
return true;
}
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.contextmenu, menu);
menu.setHeaderTitle("Select an Option");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_take:
Toast.makeText(CreateApp.this, "Opening the Camera",
Toast.LENGTH_SHORT).show();
Intent camera = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera, 0);
return true;
case R.id.menu_choose:
Toast.makeText(CreateApp.this, "Opening the Gallery",
Toast.LENGTH_SHORT).show();
Intent gallery = new Intent();
gallery.setType("image/*");
gallery.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(gallery, "Select Picture"), 1);
return true;
}
return super.onContextItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ImageView iv = new ImageView(this);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
// Uri selectedImage = data.getData();
Toast.makeText(this, "Adding Photo From Camera",
Toast.LENGTH_LONG).show();
iv = (ImageView) findViewById(R.id.application_logo);
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
iv.setImageBitmap(thumbnail);
Intent r = new Intent(this, RegisterMarkerMain.class);
//startActivity(r);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
image = Base64.encodeToString(b, Base64.DEFAULT);
//r.putExtra("BitmapImage", image);
//startActivityForResult(r, 13);
Toast.makeText(this, "Marker Valid", Toast.LENGTH_LONG).show();
adapter = new CandidatesListAdapter(this);
setListAdapter(adapter);
process = new ProcessImage(this, thumbnail);
process.execute();
//call the main layout from xml
//RelativeLayout mainLayout = (RelativeLayout)findViewById(R.id.create_layout_id);
//create a view to inflate the layout_item (the xml with the textView created before)
//View view = getLayoutInflater().inflate(R.layout.layout_item, mainLayout,false);
//add the view to the main layout
// mainLayout.addView(view);
}
break;
case 1:
if (resultCode == RESULT_OK) {
Toast.makeText(this, "Adding Photo From Gallery",
Toast.LENGTH_LONG).show();
Uri targetUri = data.getData();
iv = (ImageView) findViewById(R.id.application_logo);
Bitmap thumbnail = null;
try {
thumbnail = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(targetUri));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
iv.setImageBitmap(thumbnail);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG,100, baos);
byte [] b=baos.toByteArray();;
try{
System.gc();
image=Base64.encodeToString(b, Base64.DEFAULT);
}catch(Exception e){
e.printStackTrace();
}catch(OutOfMemoryError e){
baos=new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG,50, baos);
b=baos.toByteArray();
image=Base64.encodeToString(b, Base64.DEFAULT);
Log.e("EWN", "Out of memory error catched");
}
Toast.makeText(this, "Marker Valid", Toast.LENGTH_LONG).show();
}
break;
}
}
public void managePrivacy(View v) {
Intent privacyIntent = new Intent(this, ManagePrivactActivity.class);
startActivity(privacyIntent);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Marker o = (Marker) this.getListAdapter().getItem(position);
Toast.makeText(this, "strength " + o.descriptor.rows(),
Toast.LENGTH_SHORT).show();
// TODO: both Image and descriptor should be sent to server combined
// with location and other info.
// Descriptor of image is n rows * 64 numbers
}
public native void loadCand(long nativeObjAddr, long descriptoradd, int i);
public native int findMarkersNative(long imgAdd);
public class ProcessImage extends AsyncTask<Void, Void, ArrayList<Marker>> {
private Context mContext;
Bitmap bmp;
public ProcessImage(Context context, Bitmap bmp) {
mContext = context;
mRgba = new Mat();
this.bmp = bmp;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
getListView().setVisibility(View.GONE);
//loading.setVisibility(View.VISIBLE);
Utils.bitmapToMat(bmp, mRgba);
}
#Override
protected void onPostExecute(ArrayList<Marker> result) {
getListView().setVisibility(View.VISIBLE);
//loading.setVisibility(View.GONE);
adapter.updateData(result);
// display
Utils.matToBitmap(mRgba, bmp);
//imageView.setImageBitmap(bmp);
super.onPostExecute(result);
}
#Override
protected ArrayList<Marker> doInBackground(Void... params) {
ArrayList<Marker> imagesCand = new ArrayList<Marker>();
// process
int candCount = findMarkersNative(mRgba.getNativeObjAddr());
for (int i = 0; i < candCount; i++) {
Mat cand = new Mat();
Mat descriptor = new Mat();
loadCand(cand.getNativeObjAddr(),
descriptor.getNativeObjAddr(), i);
if (descriptor.rows() > 0) {
Bitmap bmp3 = Bitmap.createBitmap(cand.cols(), cand.rows(),
Bitmap.Config.ARGB_8888);
Utils.matToBitmap(cand, bmp3);
imagesCand.add(new Marker(bmp3, descriptor));
}
}
return imagesCand;
}
}
private class AsyncCreateApplication extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... arg0) {
EditText et = (EditText) findViewById(R.id.application_name_edit);
String s = et.getText().toString();
TextView tv = (TextView) findViewById(R.id.question_title);
String c = tv.getText().toString();
System.out.println("Category yafanan " + c);
ServerAPI.createApplication(s, c, userID, image);
System.out.println("in Background");
return null;
}
protected void onPostExecute(Void result) {
EditText et = (EditText) findViewById(R.id.application_name_edit);
refresh.putExtra("app_name", et.getText().toString());
System.out.println("App created " + et.getText().toString());
refresh.putExtra("user_id", userID);
setResult(RESULT_OK, refresh);
// startActivity(edit);
startActivity(refresh);
}
}
private class AsyncGetCategories extends AsyncTask<Void, Void, Void> {
ArrayList<String> al = null;
ArrayAdapter<String> dataAdapter;
Spinner category = (Spinner) findViewById(R.id.categories_spinner);
#Override
protected Void doInBackground(Void... params) {
System.out.println("do in background");
al = ServerAPI.getCategories();
System.out.println("ArrayList fetched");
return null;
}
#Override
protected void onPostExecute(Void result) {
dataAdapter = new ArrayAdapter<String>(CreateApp.this,
android.R.layout.simple_spinner_item,
new ArrayList<String>());
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
category.setAdapter(dataAdapter);
dataAdapter.add("Select");
for (int i = 0; i < al.size(); i++) {
dataAdapter.add(al.get(i));
// System.out.println(al.remove(i));
}
return;
}
}
private class AsyncAppDuplicates extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... arg0) {
EditText et = (EditText) findViewById(R.id.application_name_edit);
String name = et.getText().toString();
String s = ServerAPI.checkAppDuplicates(name, userID);
System.out.println("Checked and " + s);
if (s.equals("Already there")) {
duplicate = true;
} else {
duplicate = false;
}
return null;
}
}
}
I've googled so much but I can't figure out what's wrong.
Any help would be really appreciated.
I solved it writing the following lines where you declare everything for the activity, before onCreate:
static {
if (!OpenCVLoader.initDebug()) {
// Handle initialization error
}
}
confirm your native_sample.so file has been contained in your libs-->armeabi folder, and usually, the native lib should be loaded in a static code block outside of the activity's life circle methods.

getting gps position after taking photo

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.

Categories

Resources