I'm trying to build an app which will periodically call the Camera to take a picture and save it.
My problem is that unless I put the 'takePictuce' call in the 'onCreate' the response to 'takePicture' (onPictureTaken) is never called.
I've broken down the app as simply as possible to illustrate.
if a class to handle the camera is partially defined as:
public class CameraHandler {
private Camera mCamera;
public CameraHandler(){
mCamera = Camera.open();
mCamera.setPreviewTexture(new SurfaceTexture(10));
mCamera.startPreview();
mCamera.takePicture(null, null, mPicture);
}
Camera.PictureCallback mPicture = new Camera.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();
} catch (FileNotFoundException e) {
} catch (IOException e) { }
}
};
Then when I put the following code into MainActivity.java, 'onPictureTaken' IS called when CameraHandler is instantiated.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CameraHandler cameraHandler = new CameraHandler();
}
However, putting the call to instantiate CameraHandler in a click event in the MainActivity.java will NOT call 'onPictureTaken' in response to the takePicture call.
(This snippet is located in MainACtivity.java)
public void onClickListener(View view){
CameraHandler cameraHandler = new CameraHandler();
}
So why is this occurring, and how can I get the call to take a picture in the class where it belongs and not in the 'main' of the program?
All help welcome
Finally figured out how to set the phone to take timed pics without any screen display.
There were 2 main issues I struggled with. First, I wanted to take the pics without displaying to screen. Along those lines, I found an example where they used :
mCamera.setPreviewTexture(new SurfaceTexture(10));
and nothing showed on the screen when using this preview method. It appears that some sort of preview is required. Another method was to set the preview to 1 pixel. This method had examples online which appeared to work as well, but I did not try it.
The second and bigger problem had to do with 'onPictureTaken' method. This method processes your picture after the 'takePicture' call.
It seemed that no matter what looping method I used, or where in the code the call to 'takePicture' was located, all of the 'onPictureTaken' methods were queued up and called one after another once the parent of the 'takePicture' caller ended.
Although the picture data processed by onPictureTaken were in a proper time sequence, I could see that having several hundred pics stored and waiting to process could cause problems, and a method needed to be found where on pic was processed and stored before the next pic was taken.
Along those lines, I stumbled upon the AlarmManager and coupled that with the BroadcastReceiver and Future classes to solve the problem.
What I've done is set the alarmManger to go off at a set time or time frequency. The BroadcaseReceiver captures this call & in turn calls a method which creates
a thread where a 'Future' object makes the call to take a picture.
'Future' object is nice, because it will wait for the physical camera to take the picture (takePicture) and then process it (onPictureTaken). This all occurs in one thread, then terminates. So no queuing of pics to process and each picture sequence is handled separately.
Code is contained below. Note that some of the default 'Overrides' have been left out to save space. Also, the visible screen was basically a button which captured the click event...very basic.
MainActivity.java:
package myTest.com.test;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class MainActivity extends Activity {
CameraHandler cameraHandler;
public BroadcastReceiver br;
public PendingIntent pi;
public AlarmManager am;
final static private long LOOPTIME = 20000;
private static final ExecutorService threadpool = Executors.newFixedThreadPool(3);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setup();
}
private void setup() {
try{
cameraHandler = new CameraHandler();
br = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent i) {
//Toast.makeText(c, "Taking a pic!", Toast.LENGTH_LONG).show();
TryAThread();
}
};
registerReceiver(br, new IntentFilter("com.timedActivity.activity") );
pi = PendingIntent.getBroadcast(this, 0, new Intent("com.timedActivity.activity"), 0);
am = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
}
catch (Exception e){ }
}
private void TryAThread() {
try{
CameraCaller cameraCaller = new CameraCaller(cameraHandler);
Future future = threadpool.submit(cameraCaller);
while (!future.isDone()) {
try {
Thread.sleep(5000);
} catch (Exception ex) { }
}
}
catch (Exception e){ }
}
#Override
protected void onDestroy() {
am.cancel(pi);
unregisterReceiver(br);
super.onDestroy();
}
public void onClickListener(View view){
try{
am.setRepeating(am.ELAPSED_REALTIME,SystemClock.elapsedRealtime(), LOOPTIME, pi);
}
catch (Exception e){ }
}
}
CameraCaller.java:.
package myTest.com.test;
import java.util.concurrent.Callable;
public class CameraCaller implements Callable {
private CameraHandler cameraHandler;
public CameraCaller(CameraHandler ch){
cameraHandler = ch;
}
#Override
public Object call() throws Exception {
cameraHandler.takeAPic();
return true;
}
}
CameraHandler.java:.
package myTest.com.test;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Environment;
import android.util.Log;
import junit.runner.Version;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CameraHandler implements Camera.PictureCallback{
private Camera mCamera;
public CameraHandler(){
}
public Boolean takeAPic(){
try{
if (mCamera == null){
mCamera = Camera.open();
mCamera.enableShutterSound(false);
try {
mCamera.setPreviewTexture(new SurfaceTexture(10));
}
catch (IOException e1) {Log.e(Version.id(), e1.getMessage());
}
}
mCamera.startPreview();
mCamera.takePicture(null, null, this);
}
catch (Exception ex){ }
return true;
}
#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();
} catch (FileNotFoundException e) {
} catch (IOException e) { }
try {
Thread.sleep(2000);
}catch (Exception ex){}
}
public static File getOutputMediaFile() {
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File mediaStorageDir = new File(file, "MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "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");
return mediaFile;
}
}
Related
I am very new to Java & Android but I need to write a txt file which contains sensor data in Environment.DIRECTORY_DOCUMENTS. I scanned questions about it and tried examples. Version used here is Android 5.1 (API 22). My final trial is here:
package com.example.accgy;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.TextView;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private static final String TAG = "MainActivity";
private SensorManager sensorManager;
Sensor accelerometer;
Sensor gyroscope;
FileWriter writer;
TextView Xa,Ya,Za,Xg,Yg,Zg;
float[] accel = new float[3];
float[] gyro = new float[3];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Xa = (TextView)findViewById(R.id.Xa);
Ya = (TextView)findViewById(R.id.Ya);
Za = (TextView)findViewById(R.id.Za);
Xg = (TextView)findViewById(R.id.Xg);
Yg = (TextView)findViewById(R.id.Yg);
Zg = (TextView)findViewById(R.id.Zg);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
gyroscope = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
public void onStart(View view){
super.onStart();
sensorManager.registerListener(this,accelerometer,SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(this,gyroscope,SensorManager.SENSOR_DELAY_NORMAL);
String savedirect = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).toString();
try {
File folder = new File(savedirect,"/example.txt");
folder.mkdir();
writer = new FileWriter(folder);
} catch (IOException e) {
e.printStackTrace();
}
}
public void onStop(View view) {
super.onStop();
sensorManager.unregisterListener(this);
try {
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
accel = sensorEvent.values;
Xa.setText("Xa: " + accel[0]);
Ya.setText("Ya: " + accel[1]);
Za.setText("Za: " + accel[2]);
}
if (sensorEvent.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
gyro = sensorEvent.values;
Xg.setText("Xg: " + gyro[0]);
Yg.setText("Yg: " + gyro[1]);
Zg.setText("Zg: " + gyro[2]);
}
try {
writer.write(accel[0]+" "+accel[1]+" "+accel[2]+" "+gyro[0]+" "+gyro[1]+" "+gyro[2]+"\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
But when I run the code over a physical device and touch the start button, the app crashes. Is there a way to prevent this?
Note: I also provide permission for writing external storages in manifest file.
EDIT: I checked logcat and found:
Java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.FileWriter.write(java.lang.String)' on a null object reference
at:
try {
writer.write(accel[0]+" "+accel[1]+" "+accel[2]+" "+gyro[0]+" "+gyro[1]+" "+gyro[2]+"\n");
} catch (IOException e) {
e.printStackTrace();
}
When I change this line:
writer = new FileWriter(folder);
to this:
writer = new FileWriter(folder+"example.txt",true);
App succesfully writes the data. But the name of file becomes "Documentsexample.txt". But my desire is "example.txt". I tried to remove "folder+" part from the line, tried to create folder in different ways. But same error returns after re-run. It seems no way other than above.
Here is my Android Media player code. I don't know what I am missing in this code, when I run with breakpoint at line MediaPlayer mp = new MediaPlayer() in Debug mode. All the files in zip folder is played. But when I run the application in normal mode the first file is played and then I get this error:
android.app.SuperNotCalledException: Activity {com.example.mediaplayer/com.example.mediaplayer.MainActivity} did not call through to super.onCreate()
Code:
package com.example.mediaplayer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.io.IOUtils;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Button;
public class MainActivity extends Activity {
private MediaPlayer mp;
private static final String MAIN_TAG ="ERROR";
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
//final String file_loc= Environment.getExternalStorageDirectory().toString();
//Log.i("location",file_loc);
ZipFile zip = new ZipFile("/storage/emulated/0/AjeshDocument/sample.zip");
for(int i=1;i<7;i++){
ZipEntry entry = zip.getEntry("sample/rihanna_"+i+".mp3");
if (entry != null) {
InputStream in = zip.getInputStream(entry);
// see Note #3.
File tempFile = File.createTempFile("_AUDIO_", ".wav");
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(in, out);
// do something with tempFile (like play it)
File f = tempFile;
try {
if (f.exists())
{
Log.i(MAIN_TAG,"Audio file found!");
MediaPlayer mp = new MediaPlayer();
FileInputStream fis = new FileInputStream(f);
mp.setDataSource(fis.getFD());
mp.prepare();
//mp.setLooping(false);
mp.start();
//mp.stop();
// mp.release();
Log.i(MAIN_TAG,"Pronounciation finished!");
}
else
{
Log.i(MAIN_TAG,"File doesn't exist!!");
}
}
catch (IOException e)
{
Log.i(MAIN_TAG,e.toString());
}
}
else {
// no such entry in the zip
}
} //for end
mp.release();
}
catch (Exception e) {
// handle your exception cases...
Log.i(MAIN_TAG,e.toString());
}
}
#Override
protected void onResume() {
Log.w("Info", "App Resume");
super.onResume();
}
#Override
protected void onStop() {
Log.w("Info", "App stopped");
super.onStop();
}
#Override
protected void onDestroy() {
Log.w("Info", "App destoryed");
super.onDestroy();
}
}
You didn't call the Activity's onCreate() method, i.e the super class' one. Add the call to MainActivity's onCreate() method:
public class MainActivity extends Activity {
private MediaPlayer mp;
private static final String MAIN_TAG ="ERROR";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // this line is missing
// your code below ...
I am new to android app and I am trying Camera using SurfaceTexture. The call back for OnFrameAvailable() is not being called... Please suggest me a solution. The code is below.
What is missing in this? I am not sure if I have made the correct call to setOnFrameListener().
package com.example.cameratest;
import com.example.test.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.graphics.SurfaceTexture;
import android.graphics.SurfaceTexture.OnFrameAvailableListener;
import android.hardware.Camera;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.media.MediaMuxer;
import android.opengl.*;
import android.util.Log;
import android.view.Surface;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.concurrent.locks.ReentrantLock;
public class MainActivity extends Activity implements OnFrameAvailableListener {
private static final String TAG = "CameraToMpegTest";
private static final boolean VERBOSE = true; // lots of logging
// where to put the output file (note: /sdcard requires WRITE_EXTERNAL_STORAGE permission)
private static final long DURATION_SEC = 8;
// camera state
private Camera mCamera;
private static SurfaceTexture mSurfaceTexture;
private int[] mGlTextures = null;
private Object mFrameSyncObject = new Object();
private boolean mFrameAvailable = false;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startCamera(View v) {
try {
this.initCamera(0);
this.StartCamera();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
private void StartCamera() {
try {
mCamera.startPreview();
long startWhen = System.nanoTime();
long desiredEnd = startWhen + DURATION_SEC * 1000000000L;
int frameCount = 0;
while (System.nanoTime() < desiredEnd) {
// Feed any pending encoder output into the muxer.
awaitNewImage();
}
} finally {
// release everything we grabbed
releaseCamera();
}
}
/**
* Stops camera preview, and releases the camera to the system.
*/
private void releaseCamera() {
if (VERBOSE) Log.d(TAG, "releasing camera");
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
private void initCamera(int cameraId) {
mCamera = Camera.open(cameraId);
if (mCamera == null) {
Log.d(TAG, "No front-facing camera found; opening default");
mCamera = Camera.open(); // opens first back-facing camera
}
if (mCamera == null) {
throw new RuntimeException("Unable to open camera");
}
Camera.Parameters parms = mCamera.getParameters();
parms.setPreviewSize(640, 480);
mGlTextures = new int[1];
GLES20.glGenTextures(1, mGlTextures, 0);
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mGlTextures[0]);
GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER,
GLES20.GL_NEAREST);
GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER,
GLES20.GL_LINEAR);
GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S,
GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T,
GLES20.GL_CLAMP_TO_EDGE);
mSurfaceTexture = new SurfaceTexture(mGlTextures[0]);
try {
mCamera.setPreviewTexture(mSurfaceTexture);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mSurfaceTexture.setOnFrameAvailableListener(MainActivity.this);
}
public void awaitNewImage() {
final int TIMEOUT_MS = 4500;
synchronized (mFrameSyncObject) {
while (!mFrameAvailable) {
try {
// Wait for onFrameAvailable() to signal us. Use a timeout to avoid
// stalling the test if it doesn't arrive.
if (VERBOSE) Log.i(TAG, "Waiting for Frame in Thread");
mFrameSyncObject.wait(TIMEOUT_MS);
if (!mFrameAvailable) {
// TODO: if "spurious wakeup", continue while loop
throw new RuntimeException("Camera frame wait timed out");
}
} catch (InterruptedException ie) {
// shouldn't happen
throw new RuntimeException(ie);
}
}
mFrameAvailable = false;
}
}
#Override
public void onFrameAvailable(SurfaceTexture st) {
if (VERBOSE) Log.d(TAG, "new frame available");
synchronized (mFrameSyncObject) {
if (mFrameAvailable) {
throw new RuntimeException("mFrameAvailable already set, frame could be dropped");
}
mFrameAvailable = true;
mFrameSyncObject.notifyAll();
}
}
}
I think you have to call SurfaceTeture.updateTextImage() after your OnFrameAvailable() Callback to tell the camera "I've used your last frame, give me another one".
(Sorry but my English cannot provide a better explanation)
#Override
public void onFrameAvailable(SurfaceTexture surfaceTexture) {
...
surfaceTexture.updateTexImage();
}
had the same problem, seems like I forgot to call for the updateTexImage()
use method setOnFrameAvailableListener(#Nullable final OnFrameAvailableListener listener, #Nullable Handler handler) replace setOnFrameAvailableListener(#Nullable OnFrameAvailableListener listener).
in your case, you can modify the code as:
frameUpdateThread = new HandlerThread("frameUpdateThread");
frameUpdateThread.start();
mSurfaceTexture.setOnFrameAvailableListener(MainActivity.this, Handler(frameUpdateThread.getLooper()));
In my understanding onFrameAvailable should be used with thread. With that i am not facing the issue and also make sure updatetextImage is called after receiving the frames
Getting this exception while executing on emulator.
I think this is related to some memory issue.
Because its working fine when am trying it on my phone.
Anyone help me to find the real reason for this problem?
Galleryview.java
package example.hitwallhd;
import example.hitwallhd.ImageDownloader;
import example.hitwallhd.ImageDownloader.ImageLoaderListener;
import example.hitwallhd.R;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;
public class Galleryview extends Activity {
private ProgressBar pb;
private Button save,bnxt,bprv;
private ImageView img;
private static Bitmap bmp;
private TextView percent;
private FileOutputStream fos;
private ImageDownloader mDownloader;
TextView t1,t2;
String num,cate,addrs,urladdrs,pviews,pdown,sele;
int savecount=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_galleryview);
save.setEnabled(false);
initViews();
Bundle extras = getIntent().getExtras();
num = extras.getString("num");
cate = extras.getString("category");
sele = extras.getString("sele");
addrs= extras.getString("picno");
t1 =(TextView) findViewById(R.id.textView2);
t2 =(TextView) findViewById(R.id.textView3);
//t1.setText(pviews);
//t2.setText(pdown);
urladdrs="http://someaddrs.com/wallpapers/"+cate+"/"+addrs;
/*--- instantiate our downloader passing it required components ---*/
mDownloader = new ImageDownloader(urladdrs, pb, save, img, percent, Galleryview.this, bmp, new ImageLoaderListener() {
#Override
public void onImageDownloaded(Bitmap bmp) {
Galleryview.bmp = bmp;
/*--- here we assign the value of bmp field in our Loader class
* to the bmp field of the current class ---*/
}
});
/*--- we need to call execute() since nothing will happen otherwise ---*/
mDownloader.execute();
save.setEnabled(true);
}
private void initViews() {
save = (Button) findViewById(R.id.save);
//bnxt=(Button) findViewById(R.id.bnext);
//bprv=(Button) findViewById(R.id.bprev);
/*--- we are using 'this' because our class implements the OnClickListener ---*/
img = (ImageView) findViewById(R.id.imageView1);
img.setScaleType(ScaleType.CENTER_CROP);
pb = (ProgressBar) findViewById(R.id.pbDownload);
pb.setVisibility(View.INVISIBLE);
percent = (TextView) findViewById(R.id.textView1);
percent.setVisibility(View.INVISIBLE);
}
public void onclick_next(View v)
{
bprv.setEnabled(true);
GetData obj = new GetData();
int nxt=Integer.parseInt(num)+1;
num=String.valueOf(nxt);
String urls="http://someaddrs.com/wallpapers/newlist.php?cate="+cate+"&no="+num+"&prev=0";
obj.execute(urls);
}
public void onclick_prev(View v)
{
bnxt.setEnabled(true);
GetData obj = new GetData();
int nxt=Integer.parseInt(num)-1;
num=String.valueOf(nxt);
String urls="http://someaddrs.com/wallpapers/newlist.php?cate="+cate+"&no="+num+"&prev=1";
obj.execute(urls);
}
public void onclick_save(View v)
{
saveImageToSD();
String cnum;
if(urladdrs.equals("nexterror"))
{
int nxt=Integer.parseInt(num)-1;
cnum=String.valueOf(nxt);
}
else if(urladdrs.equals("preverror"))
{
int nxt=Integer.parseInt(num)+1;
cnum=String.valueOf(nxt);
}
else
cnum=num;
savecount=1;
GetData obj = new GetData();
String urls="http://someaddrs.com/wallpapers/downloadcount.php?no="+cnum;
obj.execute(urls);
}
private void saveImageToSD() {
/*--- this method will save your downloaded image to SD card ---*/
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
/*--- you can select your preferred CompressFormat and quality.
* I'm going to use JPEG and 100% quality ---*/
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
/*--- create a new file on SD card ---*/
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + num+"Image.jpg");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
/*--- create a new FileOutputStream and write bytes to file ---*/
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write(bytes.toByteArray());
fos.close();
Toast.makeText(this, "Image saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
Intent pview = new Intent(Galleryview.this,HitWall.class);
startActivity(pview);
}
public void looperfn()
{
t1 =(TextView) findViewById(R.id.textView2);
t2 =(TextView) findViewById(R.id.textView3);
t1.setText(pviews);
t2.setText(pdown);
if(urladdrs.equals("nexterror"))
{
int nxt=Integer.parseInt(num)-1;
num=String.valueOf(nxt);
bnxt.setEnabled(false);
}
else if(urladdrs.equals("preverror"))
{
int nxt=Integer.parseInt(num)+1;
num=String.valueOf(nxt);
bprv.setEnabled(false);
}
else
{
//t1.setText(urladdrs);
urladdrs="http://someaddrs.com/wallpapers/"+cate+"/"+urladdrs;
mDownloader = new ImageDownloader(urladdrs, pb, save, img, percent, Galleryview.this, bmp, new ImageLoaderListener() {
#Override
public void onImageDownloaded(Bitmap bmp) {
Galleryview.bmp = bmp;
/*--- here we assign the value of bmp field in our Loader class
* to the bmp field of the current class ---*/
}
});
/*--- we need to call execute() since nothing will happen otherwise ---*/
mDownloader.execute();
}
}
public class GetData extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
BufferedReader reader =null;
String data =null;
try{
HttpClient client = new DefaultHttpClient();
URI uri=new URI(params[0]);
HttpGet get =new HttpGet(uri);
HttpResponse response= client.execute(get);
InputStream stream=response.getEntity().getContent();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer =new StringBuffer("");
String line="";
while((line=reader.readLine())!=null){
buffer.append(line);
}
reader.close();
data = buffer.toString();
if(data.equals("preverror")||data.equals("nexterror"))
{
return data;
}
else
{
pviews=data.substring(data.indexOf("|")+1,data.indexOf(":"));
pviews=" Views : "+pviews;
pdown=data.substring(data.indexOf(":")+1, data.length());
pdown=" Downloads : "+pdown;
data=data.substring(0, data.indexOf("|"));
return data;
}
//data=data.substring(0, data.indexOf("|"));
//t1.setText(data);
}
catch(URISyntaxException e){
e.printStackTrace();
}
catch(ClientProtocolException f){
f.printStackTrace();
}
catch(IOException g){
g.printStackTrace();
}
finally{
if(reader!=null){
try{
reader.close();
}
catch(Exception e){
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
urladdrs=result;
if(savecount==0)
{
looperfn();
}
else
savecount=0;
}
}
}
This type of issue is arrived due to memory leakage.
the main problem is that there is Java.lang.NullPointerException and this type of exception arrives when there is low virtual memory.
As there is low virtual memory in emulator so it is getting the error and the phone has the sufficient virtual memory to display and load the image in the memory.
You have an exception in Galleryview.java at line 57. Please provide the peace of code around line 57 or the whole Galleryview.java.
I am trying to build a small photo app with a burst mode for camera. The main idea is to shoot a picture every 0,3sec and to store the pictures in an Array until the last picture is taken. The number of pictures to shoot should specified.
I can only shoot a picture every 2sec. as shortest interval. Then, when the pictures should be written to storage, the applications chrashes.
Does someone know how to implement this? Here is my code:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
public class CamaeaView extends Activity implements SurfaceHolder.Callback, OnClickListener {
static final int FOTO_MODE = 1;
private static final String TAG = "Test";
Camera mCamera;
boolean mPreviewRunning = false;
private Context mContext = this;
ArrayList<Object> listImage = null;
public static ArrayList<Object> List1[];
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Log.e(TAG, "onCreate");
#SuppressWarnings("unused")
Bundle extras = getIntent().getExtras();
getWindow().setFormat(PixelFormat.TRANSLUCENT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
mSurfaceView.setOnClickListener(this);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
public void onPictureTaken(byte[] imageData, Camera c) {
Log.d("Start: ","Imagelist");
Intent mIntent = new Intent();
listImage.add(StoreByteImage(imageData));
SaveImage(listImage);
mCamera.startPreview();
setResult(FOTO_MODE, mIntent);
finish();
}
};
protected void onResume() {
Log.d(TAG, "onResume");
super.onResume();
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
protected void onStop() {
Log.e(TAG, "onStop");
super.onStop();
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated");
mCamera = Camera.open();
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
Log.d(TAG, "surfaceChanged");
// XXX stopPreview() will crash if preview is not running
if (mPreviewRunning) {
mCamera.stopPreview();
}
Camera.Parameters p = mCamera.getParameters();
p.setPreviewSize(w, h);
p.setPictureSize(1024, 768);
p.getSupportedPictureFormats();
p.setPictureFormat(PixelFormat.JPEG);
mCamera.setParameters(p);
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mCamera.startPreview();
mPreviewRunning = true;
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.e(TAG, "surfaceDestroyed");
mCamera.stopPreview();
mPreviewRunning = false;
mCamera.release();
}
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
public void onClick(View arg0) {
int i = 0;
while (i < 4) {
mCamera.takePicture(null, mPictureCallback, mPictureCallback);
i = i + 1;
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static Object StoreByteImage(byte[] imageData) {
Object obj = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(imageData);
ObjectInputStream objImageData = new ObjectInputStream(bis);
obj = objImageData.readObject();
} catch (IOException ex) {
// TODO: Handle the exception
} catch (ClassNotFoundException ex) {
// TODO: Handle the exception
}
return obj;
}
public static Object createImagesArray(byte[] imageData) {
Object obj = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(imageData);
ObjectInputStream objImageData = new ObjectInputStream(bis);
obj = objImageData.readObject();
} catch (IOException ex) {
// TODO: Handle the exception
} catch (ClassNotFoundException ex) {
// TODO: Handle the exception
}
return obj;
}
public static boolean SaveImage(List<Object> listImage) {
FileOutputStream outStream = null;
Log.d("ListSize: ", Integer.toString(listImage.size()));
Iterator<Object> itList = listImage.iterator();
byte[] imageBytes = null;
while (itList.hasNext()) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(listImage);
oos.flush();
oos.close();
bos.close();
imageBytes = bos.toByteArray();
} catch (IOException ex) {
// TODO: Handle the exception
}
try {
// Write to SD Card
outStream = new FileOutputStream(String.format(
"/sdcard/DCIM/%d.jpg", System.currentTimeMillis())); // <9>
outStream.write(imageBytes);
outStream.close();
} catch (FileNotFoundException e) { // <10>
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
Log.d(TAG, "onPictureTaken - jpeg");
return true;
}
}
Error from the comments:
ERROR/MemoryHeapBase(1382): error opening /dev/pmem_camera: No such file or directory
ERROR/QualcommCameraHardware(1382): failed to construct master heap for pmem pool /dev/pmem_camera
ERROR/QualcommCameraHardware(1382): initRaw X failed with pmem_camera, trying with pmem_adsp
AFAIK, you cannot take another picture until the first one is complete. Eliminate your for loop and Thread.sleep(). Take the next picture in mPictureCallback.
The main idea is to shoot a picture every 0,3sec and to store the pictures in an Array until the last picture is taken.
The "0,3sec" objective is faster than most devices can process an image, and you may not have enough heap space for your array of images. I suspect that you will have to write each image out to disk as it comes in via an AsyncTask, so you can free up the heap space while also not tying up the main application thread.
You can try capturing subsequent preview frames in preallocated byte arrays.
See the following methods:
http://developer.android.com/reference/android/hardware/Camera.html#addCallbackBuffer(byte[])
http://developer.android.com/reference/android/hardware/Camera.html#setPreviewCallbackWithBuffer(android.hardware.Camera.PreviewCallback)
...or http://developer.android.com/reference/android/hardware/Camera.html#setOneShotPreviewCallback(android.hardware.Camera.PreviewCallback) for better control over timing.