I made a simple video recorder app in which the video starts recording on Button click. This is my code:
package com.example.videocapture2;
import java.io.IOException;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements SurfaceHolder.Callback,android.media.MediaRecorder.OnInfoListener{
MediaRecorder recorder;
SurfaceHolder holder;
Button Rec = null;
boolean recording = false;
int count =1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
recorder = new MediaRecorder();
initRecorder();
setContentView(R.layout.activity_main);
SurfaceView cameraView = (SurfaceView) findViewById(R.id.videoview);
holder = cameraView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
recorder.start(); //This is the line pointed to by the IllegalStateException
//cameraView.setClickable(true);
// cameraView.setOnClickListener(this);
Rec = (Button)findViewById(R.id.mybutton);
Rec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (recording) {
recorder.stop();
recording = false;
// Let's initRecorder so we can record again
initRecorder();
prepareRecorder();
} else {
recording = true;
recorder.start();
}
}
});
}
private void initRecorder() {
recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
CamcorderProfile cpHigh = CamcorderProfile
.get(CamcorderProfile.QUALITY_HIGH);
recorder.setProfile(cpHigh);
recorder.setOutputFile("/sdcard/videocapture_example"+count+".mp4");
recorder.setMaxDuration(50000); // 50 seconds
recorder.setMaxFileSize(2*1048576); // Approximately 5 megabytes
count++;
}
private void prepareRecorder() {
recorder.setPreviewDisplay(holder.getSurface());
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
finish();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}
public void surfaceCreated(SurfaceHolder holder) {
prepareRecorder();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
public void surfaceDestroyed(SurfaceHolder holder) {
if (recording) {
recorder.stop();
recording = false;
}
recorder.release();
//Toast.makeText(getApplicationContext(), "Video is saved", Toast.LENGTH_LONG).show();
//finish();
}
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
// TODO Auto-generated method stub
System.out.println("Reached onInfoListener");
if(what==android.media.MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED)
{
Toast.makeText(getApplicationContext(), "Video clip recorded", Toast.LENGTH_LONG).show();
}
}
}
What changes should I make to call the
recorder.start();
from onCreate, or rather immediately after I launch my app, instead of in the OnClick method? Moreover, if I try to call it directly from the OnCreate, it throws the IllegalStateException in the line of the recorder.start() statement.
Logcat:
04-03 12:48:51.005: E/Trace(26160): error opening trace file: No such file or directory (2)
04-03 12:48:51.025: V/ActivityThread(26160): Class path: /data/app/com.example.videocapture2-2.apk, JNI path: /data/data/com.example.videocapture2/lib
04-03 12:48:51.174: I/System.out(26160): In surface view:false
04-03 12:48:51.174: E/MediaRecorder(26160): start called in an invalid state: 4
04-03 12:48:51.175: D/AndroidRuntime(26160): Shutting down VM
04-03 12:48:51.175: W/dalvikvm(26160): threadid=1: thread exiting with uncaught exception (group=0x41bd88a8)
04-03 12:48:51.178: E/AndroidRuntime(26160): FATAL EXCEPTION: main
04-03 12:48:51.178: E/AndroidRuntime(26160): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.videocapture2/com.example.videocapture2.MainActivity}: java.lang.IllegalStateException
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2225)
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.app.ActivityThread.access$600(ActivityThread.java:151)
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1301)
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.os.Handler.dispatchMessage(Handler.java:99)
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.os.Looper.loop(Looper.java:153)
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.app.ActivityThread.main(ActivityThread.java:5096)
04-03 12:48:51.178: E/AndroidRuntime(26160): at java.lang.reflect.Method.invokeNative(Native Method)
04-03 12:48:51.178: E/AndroidRuntime(26160): at java.lang.reflect.Method.invoke(Method.java:511)
04-03 12:48:51.178: E/AndroidRuntime(26160): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
04-03 12:48:51.178: E/AndroidRuntime(26160): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
04-03 12:48:51.178: E/AndroidRuntime(26160): at dalvik.system.NativeStart.main(Native Method)
04-03 12:48:51.178: E/AndroidRuntime(26160): Caused by: java.lang.IllegalStateException
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.media.MediaRecorder.native_start(Native Method)
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.media.MediaRecorder.start(MediaRecorder.java:728)
04-03 12:48:51.178: E/AndroidRuntime(26160): at com.example.videocapture2.MainActivity.onCreate(MainActivity.java:51)
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.app.Activity.performCreate(Activity.java:5244)
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1082)
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)
04-03 12:48:51.178: E/AndroidRuntime(26160): ... 11 more
Attempts at solving this:
1) It does not work if I keep it in onCreate
2) It does not work if I keep it in a new thread called from onCreate.
3) It also does not work if I keep it in the onClick, and simulate a click through code, using myButton.performClick()
All above scenarios gives same exception error.
But funnily enough, if the recorder.start() mentioned there is kept within buttonClick event, it works fine.
I am not able to understand why. I need the video to be recorded and saved as soon as the activity is launched.
Because It takes some time to load recorder object into memory. so it will show illegal state exception.
If you want to use this in onCreate use Handler for make some delay.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
recorder.start();
}
}, 1000);
Update:
put recorder.start(); in prepareRecorder() method
private void prepareRecorder() {
recorder.setPreviewDisplay(holder.getSurface());
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
finish();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}
Related
I want my program to record audio for 10 seconds and then stop and store my record in file storage, everything works fine on my Nexus 4 and Galaxy S 5, but when i test it in Galaxy S3 it crushes and raise error
10-02 02:13:44.942 1279-1279/com.taptester.tappapp E/AudioCaptureDemo﹕ prepare() failed
10-02 02:13:44.942 1279-1279/com.taptester.tappapp E/MediaRecorder﹕ start called in an invalid state: 4
10-02 02:13:44.942 1279-1279/com.taptester.tappapp D/AndroidRuntime﹕ Shutting down VM
10-02 02:13:44.942 1279-1279/com.taptester.tappapp W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb1a12ba8)
10-02 02:13:44.952 1279-1279/com.taptester.tappapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.taptester.tappapp, PID: 1279
java.lang.IllegalStateException
at android.media.MediaRecorder.start(Native Method)
at com.taptester.tappapp.MainActivity.startRecording(MainActivity.java:203)
at com.taptester.tappapp.MainActivity.access$300(MainActivity.java:62)
at com.taptester.tappapp.MainActivity$6.onFinish(MainActivity.java:825)
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:118)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
First i thought the error is in the file name, I'm declaring it like this:
public MainActivity() {
mFileName = Environment.getExternalStorageDirectory() + File.separator
+ Environment.DIRECTORY_DCIM + File.separator + "MyMemo.3gp";
//Environment.getExternalStorageDirectory().getAbsolutePath();
//mFileName += "/MyMemo.3gp";
}
Then i make a record like this:
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
try {
mRecorder.prepare();
mRecorder.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
Then i call the "StartRecording" method like this:
else if(command.equals("2")) {
startRecording();
Toast.makeText(getApplicationContext(), "Start recording...",
Toast.LENGTH_SHORT).show();
CountDownTimer start = new CountDownTimer(timer, 1000) {
#Override
public void onTick(long l) {
Toast.makeText(getApplicationContext(), "Recording!!!",
Toast.LENGTH_SHORT).show();
}
#Override
public void onFinish() {
stopRecording();
}
}.start();
you are not supposed to call mRecorder.start(); when mRecorder.prepare(); fails.
this is what caused the Illegal State Exception to be thrown.
Not all devices support all the encoding formats.
try changing these mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
and mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
change the format and Encoder to a file format and encoding format your s3 device supports.
for a start, change your encoding setting to default settings as follows and try if it works.
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
public static MediaPlayer mp=null;
public static void playGeneric(int name, final ImageButton button,final ImageButton pervious,Context context) {
button.setEnabled(false);
button.setClickable(false);
pervious.setEnabled(false);
pervious.setClickable(false);
try{
if(mp != null && mp.isPlaying())
{
mp.stop();
mp.release();
mp = null;
mp=MediaPlayer.create(context, name);
mp.start();
}
else
{
mp = MediaPlayer.create(context, name);
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer arg0) {
//mp.prepare();
mp.start();
}
});
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
System.out.println("Object released");
button.setEnabled(true);
button.setClickable(true);
pervious.setEnabled(true);
pervious.setClickable(true);
}
});
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
e.getMessage();
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
e.getMessage();
}
}
give me java.lang.IllegalStateException on mp.isplaying() method.
I want to stop music if it's playing and play another song one after another.
logcat:
10-14 15:12:05.474: E/MediaPlayer(15411): prepareAsync called in state 8
10-14 15:12:05.474: W/System.err(15411): java.lang.IllegalStateException
10-14 15:12:05.474: W/System.err(15411): at android.media.MediaPlayer.prepare(Native Method)
10-14 15:12:05.474: W/System.err(15411): at com.rogerscenter.LearnReadWriteSpell.Utility.Music.playGeneric(Music.java:93)
10-14 15:12:05.474: W/System.err(15411): at com.rogerscenter.LearnReadWriteSpell.LetterCategory.Letter_Lesson1_activity.onCreate(Letter_Lesson1_activity.java:140)
10-14 15:12:05.474: W/System.err(15411): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
10-14 15:12:05.474: W/System.err(15411): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1586)
10-14 15:12:05.474: W/System.err(15411): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
10-14 15:12:05.474: W/System.err(15411): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
10-14 15:12:05.474: W/System.err(15411): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
10-14 15:12:05.484: W/System.err(15411): at android.os.Handler.dispatchMessage(Handler.java:99)
10-14 15:12:05.484: W/System.err(15411): at android.os.Looper.loop(Looper.java:123)
10-14 15:12:05.484: W/System.err(15411): at android.app.ActivityThread.main(ActivityThread.java:3647)
10-14 15:12:05.484: W/System.err(15411): at java.lang.reflect.Method.invokeNative(Native Method)
10-14 15:12:05.484: W/System.err(15411): at java.lang.reflect.Method.invoke(Method.java:507)
10-14 15:12:05.484: W/System.err(15411): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-14 15:12:05.484: W/System.err(15411): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-14 15:12:05.484: W/System.err(15411): at dalvik.system.NativeStart.main(Native Method)
Try changing mp.release() into reset(). that could help you.
As android docs suggest that if mp is if has not been initialized at that time java.lang.IllegalStateException will be thrown so you have to initilize first or you have to write
check out the docs http://developer.android.com/reference/android/media/MediaPlayer.html#isPlaying()
try like this
mp=MediaPlayer.create(context, name);
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp=MediaPlayer.create(context, name);
}
mp.start();
} catch (Exception e) {
}
Ok i am here with my solution, hope it will help others.
(i) if you are using videoView and mediaPlayer.isPlaying() (isNative) error occurs
on activity stop
Add this onStop() method:
if (videoView != null && videoView.isPlaying()) {
videoView.pause();
videoView.stopPlayback();
}
Note: Don't use mediaPlayer.stop() or mediaPlayer.release() here when you work with videoView, it will throw IllegalException
(ii) If you are using mediaPlayer to play only audio
Add this onStop() method:
try {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
Note: This is only for those who get error when your activity is in stop or in resume state.
This could happen if you are trying to stop audio when the player hasn't started playing yet. Hence the IllegalStateException
See if you can prevent that. You can also putting a try catch around the isPlaying()
fun isPlaying(): Boolean {
return try {
mediaPlayer?.isPlaying == true
} catch (illegalStateException: IllegalStateException) {
DebugLog.d(TAG, illegalStateException.message)
DebugLog.d(TAG, illegalStateException.stackTraceToString())
false
}
}
use runOnUiThread for mediaRecorder prepare.
private boolean prepareMediaRecorder() {
mediaRecorder = new MediaRecorder();
runOnUiThread(new Runnable() {
#Override
public void run() {
mediaRecorder.reset();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setOutputFile(filePath);
try {
mediaRecorder.prepare();
} catch (IOException e) {
mediaRecorder = null;
return;
}
mediaRecorder.start();
recording = true;
}
});
return true;
}
I created an overlay "always on top button", which is a service HUD, and I can't start an activity screen from there, it gives the error: "Unfortunately App has stopped". In the beginning, all I used to know if there was any TouchEventwas a toast, and that toast was created, but it was created several times, so I don't know if it gives that error because this code, which is on TouchEvent body , is repeated several times too.
here is my code:
public class HUD extends Service implements OnClickListener, OnTouchListener, OnLongClickListener {
Button mButton;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
//mView = new HUDView(this);
mButton = new Button(this);
mButton.setId(1);
mButton.setText("Button");
mButton.setClickable(true);
mButton.setOnTouchListener(this);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.OPAQUE);
params.gravity = Gravity.LEFT | Gravity.TOP;
params.setTitle("Load Average");
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.addView(mButton, params);
}
#Override
public void onDestroy() {
super.onDestroy();
if(mButton != null)
{
((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(mButton);
mButton = null;
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getX()<mButton.getWidth() & event.getY()>0)
{
Toast.makeText(this,"Overlay button event", Toast.LENGTH_SHORT).show(); //this my toast
Intent i = new Intent(); //this is my new acivity (intent)
i.setClass(HUD.this, screen.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
HUD.this.stopSelf();
}
return false;
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(this,"Click", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
System.exit(1);
return false;
}
}
So my question is, is this code on TouchEvent body being repeated several times? If it is, is that the cause of the error?
log cat:
07-20 22:11:06.962: I/Choreographer(1620): Skipped 52 frames! The application may be doing too much work on its main thread.
07-20 22:11:08.062: D/AndroidRuntime(1620): Shutting down VM
07-20 22:11:08.062: W/dalvikvm(1620): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
07-20 22:11:08.132: E/AndroidRuntime(1620): FATAL EXCEPTION: main
07-20 22:11:08.132: E/AndroidRuntime(1620): android.app.SuperNotCalledException: Activity {com.example.screenshot/com.example.screenshot.screen} did not call through to super.onCreate()
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2146)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.os.Handler.dispatchMessage(Handler.java:99)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.os.Looper.loop(Looper.java:137)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-20 22:11:08.132: E/AndroidRuntime(1620): at java.lang.reflect.Method.invokeNative(Native Method)
07-20 22:11:08.132: E/AndroidRuntime(1620): at java.lang.reflect.Method.invoke(Method.java:511)
07-20 22:11:08.132: E/AndroidRuntime(1620): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-20 22:11:08.132: E/AndroidRuntime(1620): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-20 22:11:08.132: E/AndroidRuntime(1620): at dalvik.system.NativeStart.main(Native Method)
screen.java:
public class screen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
Toast.makeText(getApplicationContext(), "Made it", 0).show();
finish();
}
}
See android start activity from service
Intent i= new Intent(getBaseContext(), screen.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(i);
You error seems to be inside screen activity. There are many thread which might help to figure out the error that you are getting for the activity:
Error in Android "SuperNotCalledException:Activity did not call through to super.OnCreate()"
android.app.SuperNotCalledException: Activity did not call through to super.onStop()
Update
The error is because you haven't called: super.onCreate(savedInstanceState); in your screen activity's onCreate(). That should be the first thing to be called in onCreate(). Do something like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//.... other stuff
}
Hope this helps.
Pretty new on this android stuff and gets a NullPointException that I can't seem to figure out. I am trying to implement an onResume() method in my CameraActivity and have moved almost all of the orginal code in onCreate() to onResume() and then call onResume() in onCreate(). The activity worked fine when the code was in onCreate(), but when placed in onResume() the exception arsises. What is causing it?
package com.example.tensioncamapp_project;
import java.io.IOException;
import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "PreviewAactivity";
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
this.mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
this.mHolder = getHolder();
this.mHolder.addCallback(this);
}
/**Displays the picture on the camera */
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
this.mCamera.setPreviewDisplay(holder);
this.mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
this.mCamera.release();
this.mCamera = null;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
//add things here
}
}
and my CameraActivityClass
package com.example.tensioncamapp_project;
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.content.Intent;
import android.app.Activity;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
public class CameraActivity extends Activity {
private ImageButton captureButton;
private Camera mCamera;
private CameraPreview mPreview;
private PictureCallback mPicture;
private ImageView imageView;
private static final int STD_DELAY = 400;
private static final int MEDIA_TYPE_IMAGE = 1;
protected static final String TAG = "CameraActivity";
/**Starts up the camera */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
onResume();
}
/**Connects the capture button on the view to a listener
* and redirects the client to a preview of the captures image*/
private void addListenerOnButton() {
this.captureButton = (ImageButton) findViewById(R.id.button_capture_symbol);
this.captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View capturebutton) {
mCamera.takePicture(null, null, mPicture);
delay();
Intent viewPic = new Intent(CameraActivity.this, ViewPicActivity.class);
startActivity(viewPic);
}
});
}
/** A safe way to get an instance of the Camera object. Code collected from elsewhere */
public static Camera getCameraInstance(){
Camera c = null;
try {
// attempt to get a Camera instance
c = Camera.open();
//getting current parameters
Camera.Parameters params = c.getParameters();
//setting new parameters with flash
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
c.setParameters(params);
}
catch (Exception e){
// camera is not available (in use or does not exist)
}
// returns null if camera is unavailable
return c;
}
/**Generates a delay needed for application to save new pictures */
private void delay(){
try {
//Makes the program inactive for a specific amout of time
Thread.sleep(STD_DELAY);
} catch (Exception e) {
e.getStackTrace();
}
}
/**Method for releasing the camera immediately on pause event*/
#Override
protected void onPause() {
super.onPause();
//Shuts down the preview shown on the screen
mCamera.stopPreview();
//Calls an internal help method to restore the camera
releaseCamera();
}
/**Help method to release the camera */
private void releaseCamera(){
//Checks if there is a camera object active
if (this.mCamera != null){
//Releases the camera
this.mCamera.release();
//Restore the camera object to its initial state
this.mCamera = null;
}
}
/**Activates the camera and makes it appear on the screen */
protected void onResume() {
// TODO Auto-generated method stub
// deleting image from external storage
FileHandler.deleteFromExternalStorage();
// Create an instance of Camera.
this.mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
this.mPreview = new CameraPreview(this, this.mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(this.mPreview);
//add the capture button
addListenerOnButton();
// In order to receive data in JPEG format
this.mPicture = new PictureCallback() {
/**Creates a file when a image is taken, if the file doesn't already exists*/
#Override
public void onPictureTaken(byte[] data, Camera mCamera) {
File pictureFile = FileHandler.getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d(TAG, "Error creating media file, check storage permissions");
return;
}
try {
//Writes the image to the disc
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
};
super.onResume();
}
}
Log cat:
05-21 14:32:05.424: D/OpenGLRenderer(1030): Enabling debug mode 0
05-21 14:32:10.986: E/CameraActivity(1030): camera not availableFail to connect to camera service
05-21 14:32:11.033: I/Choreographer(1030): Skipped 66 frames! The application may be doing too much work on its main thread.
05-21 14:32:11.203: W/EGL_emulation(1030): eglSurfaceAttrib not implemented
05-21 14:32:13.013: D/AndroidRuntime(1030): Shutting down VM
05-21 14:32:13.013: W/dalvikvm(1030): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
05-21 14:32:13.083: E/AndroidRuntime(1030): FATAL EXCEPTION: main
05-21 14:32:13.083: E/AndroidRuntime(1030): java.lang.NullPointerException
05-21 14:32:13.083: E/AndroidRuntime(1030): at com.example.tensioncamapp_project.CameraPreview.surfaceCreated(CameraPreview.java:33)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.SurfaceView.updateWindow(SurfaceView.java:569)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.SurfaceView.access$000(SurfaceView.java:86)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:174)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:680)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1842)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.Choreographer.doCallbacks(Choreographer.java:562)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.Choreographer.doFrame(Choreographer.java:532)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.os.Handler.handleCallback(Handler.java:725)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.os.Handler.dispatchMessage(Handler.java:92)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.os.Looper.loop(Looper.java:137)
05-21 14:32:13.083: E/AndroidRuntime(1030): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-21 14:32:13.083: E/AndroidRuntime(1030): at java.lang.reflect.Method.invokeNative(Native Method)
05-21 14:32:13.083: E/AndroidRuntime(1030): at java.lang.reflect.Method.invoke(Method.java:511)
05-21 14:32:13.083: E/AndroidRuntime(1030): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-21 14:32:13.083: E/AndroidRuntime(1030): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-21 14:32:13.083: E/AndroidRuntime(1030): at dalvik.system.NativeStart.main(Native Method)
The solution was to call the getCameraInstancemethod() in onResume() in an if-statement
protected void onResume() {
// TODO Auto-generated method stub
// deleting image from external storage
FileHandler.deleteFromExternalStorage();
// Create an instance of Camera.
if (this.mCamera == null){
this.mCamera = getCameraInstance();}
I think your problem is here
this.mPreview = new CameraPreview(this, this.mCamera);
this.mCamera seems to be null, it's not be set a new instance of the class, this needs to be done in the getCameraInstance() method.
getCameraInstance() returns null if an exception was thrown.
This cause the NPE as this.mCamera is null.
You should check if an exception was thrown in getCameraInstance and handle it correctly. The most basic thing is to log it and try to understand the reason.
i am try to make back up feature in my app but it give force close error
can any one give some idea whats wrong in my code
pls help me out
here is my code
public class Mydatabase {
private String appName = "";
private String packageName = "";
public static final String DATABASE_NAME = "data.db";
public boolean backup() {
boolean rc = false;
boolean writeable = isSDCardWriteable();
if (writeable) {
File file = new File(Environment.getDataDirectory() + "/data/" + packageName + "/databases/" + DATABASE_NAME);
File fileBackupDir = new File(Environment.getExternalStorageDirectory(), appName + "/backup");
if (!fileBackupDir.exists()) {
fileBackupDir.mkdirs();
}
if (file.exists()) {
File fileBackup = new File(fileBackupDir, DATABASE_NAME);
try {
fileBackup.createNewFile();
FileUtils..copyFile(file, fileBackup);
rc = true;
} catch (IOException ioException) {
//
} catch (Exception exception) {
//
}
}
}
return rc;
}
private boolean isSDCardWriteable() {
boolean rc = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
rc = true;
}
return rc;
}
public Mydatabase(final Context context, final String appName) {
this.appName = appName;
packageName = context.getPackageName();
}
}
this is my log
04-03 00:39:18.595: E/AndroidRuntime(674): FATAL EXCEPTION: main
04-03 00:39:18.595: E/AndroidRuntime(674): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.neelrazin.noteit/com.neelrazin.noteit.Mydatabase}: java.lang.InstantiationException: com.neelrazin.noteit.Mydatabase
04-03 00:39:18.595: E/AndroidRuntime(674): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
04-03 00:39:18.595: E/AndroidRuntime(674): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
04-03 00:39:18.595: E/AndroidRuntime(674): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
04-03 00:39:18.595: E/AndroidRuntime(674): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
04-03 00:39:18.595: E/AndroidRuntime(674): at android.os.Handler.dispatchMessage(Handler.java:99)
04-03 00:39:18.595: E/AndroidRuntime(674): at android.os.Looper.loop(Looper.java:123)
04-03 00:39:18.595: E/AndroidRuntime(674): at android.app.ActivityThread.main(ActivityThread.java:3683)
04-03 00:39:18.595: E/AndroidRuntime(674): at java.lang.reflect.Method.invokeNative(Native Method)
04-03 00:39:18.595: E/AndroidRuntime(674): at java.lang.reflect.Method.invoke(Method.java:507)
04-03 00:39:18.595: E/AndroidRuntime(674): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-03 00:39:18.595: E/AndroidRuntime(674): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-03 00:39:18.595: E/AndroidRuntime(674): at dalvik.system.NativeStart.main(Native Method)
04-03 00:39:18.595: E/AndroidRuntime(674): Caused by: java.lang.InstantiationException: com.neelrazin.noteit.Mydatabase
04-03 00:39:18.595: E/AndroidRuntime(674): at java.lang.Class.newInstanceImpl(Native Method)
04-03 00:39:18.595: E/AndroidRuntime(674): at java.lang.Class.newInstance(Class.java:1409)
04-03 00:39:18.595: E/AndroidRuntime(674): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
04-03 00:39:18.595: E/AndroidRuntime(674): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)
04-03 00:39:18.595: E/AndroidRuntime(674): ... 11 more
You seem a bit lost.
Here is a functional method to backup your database, you can place it in any class.
public static void backupDatabase() throws IOException {
//Open your local db as the input stream
String inFileName = "/data/data/com.android.exemple/databases/databename.db";
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory()+"/database.db";
//Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer))>0){
output.write(buffer, 0, length);
}
//Close the streams
output.flush();
output.close();
fis.close();
}
You need to add this line in your manifest before the application element
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Don't forget to change the package name in the inFileName variable and the databasename at both place.
The trace points the finger at the fact that you're trying to launch an Activity called Mydatabase. As we can see from your code snippet, Mydatabase doesn't extend Activity. The system is looking for an Activity to launch, not a class that just derives from Object.