takePicture failed when running a Camera Service - java

im trying to run a Camera Service in the Background, as soon after the Service has started i get an error takePicture failed. I'm new to Android,new to Stackoverflow and also not a good programmer.
I've added the right permissions and the service has been declared in the manifest file too.
package com.example.nevii.camera;
import android.app.Service;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.IBinder;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;
import java.io.IOException;
public class CameraService extends Service
{
//Camera variables
//a surface holder
private SurfaceHolder sHolder;
//a variable to control the camera
private Camera mCamera;
//the camera parameters
private Parameters parameters;
private boolean safeToTakePicture = false;
/** Called when the activity is first created. */
#Override
public void onCreate()
{
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
super.onStartCommand(intent, flags, startId);
Toast.makeText(getBaseContext(), "onStartCommand", Toast.LENGTH_SHORT).show();
mCamera = Camera.open(1);
mCamera.setDisplayOrientation(90);
SurfaceView sv = new SurfaceView(getApplicationContext());
try {
mCamera.setPreviewDisplay(sv.getHolder());
parameters = mCamera.getParameters();
//set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
safeToTakePicture = true;
takePic();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//stop the preview
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
//release the camera
mCamera.release();
//unbind the camera from this object
mCamera = null;
}
//Get a surface
sHolder = sv.getHolder();
//tells Android that this surface will have its data constantly replaced
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
return START_STICKY;
}
public void takePic(){
Camera.PictureCallback mCall = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
//decode the data obtained by the camera into a Bitmap
MyCamera myCamera = new MyCamera();
myCamera.SavePicture(data);
//stop the preview
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
//release the camera
mCamera.release();
//unbind the camera from this object
mCamera = null;
}
};
mCamera.takePicture(null, null, mCall);
Toast.makeText(getApplicationContext(),"Pic taken",Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
I got the SourceCode from here:http://androideasylessons.blogspot.ch/2012/09/capture-image-without-surface-view-as.html
In the MainActivity i started the Service using:
startService(new Intent(this, CameraService.class));
myCamera.SavePicture is just an Asynchtask, which saves the Picture, i don't think there's a problem with that.
I hope you guys can help me.
Happy Coding!
UPDATE Logcat Error:
03-03 09:04:46.150 27530-27530/com.example.nevii.videocam D/Camera﹕ app passed NULL surface
03-03 09:04:46.153 27530-27530/com.example.nevii.videocam D/AndroidRuntime﹕ Shutting down VM
03-03 09:04:46.154 27530-27530/com.example.nevii.videocam E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.nevii.videocam, PID: 27530
java.lang.RuntimeException: Unable to start service com.example.nevii.videocam.CameraService#3f53f37f with Intent { cmp=com.example.nevii.videocam/.CameraService }: java.lang.RuntimeException: takePicture failed
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2881)
at android.app.ActivityThread.access$2100(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1376)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.RuntimeException: takePicture failed
at android.hardware.Camera.native_takePicture(Native Method)
at android.hardware.Camera.takePicture(Camera.java:1436)
at android.hardware.Camera.takePicture(Camera.java:1381)
at com.example.nevii.videocam.CameraService.takePic(CameraService.java:101)
at com.example.nevii.videocam.CameraService.onStartCommand(CameraService.java:57)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2864)
            at android.app.ActivityThread.access$2100(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1376)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

just add SurfaceTexture st = new SurfaceTexture(MODE_PRIVATE); mCamera.setPreviewTexture(st);
before mCamera.startPreview();

Related

Bluetooth Android app keeps crashing on startup [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I tried to build an app that lets you send data over bluetooth to an
arduino. But I got stuck while creating the socket. The app keeps
crashing on startup, but I don't know why.
package de.lutherschule.bled.bluetoothled;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.icu.util.Output;
import android.support.annotation.WorkerThread;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
BluetoothAdapter bAdapter;
BluetoothDevice device;
Boolean found;
BluetoothSocket btSocket;
OutputStream outputStream;
InputStream inputStream;
public static final String DEVICE_ADRESS = "";
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final String TAG = "MainActvity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bAdapter = BluetoothAdapter.getDefaultAdapter();
found = false;
btSocket = null;
Log.v(TAG, "Funst");
if (bAdapter == null) {
Toast.makeText(getApplicationContext(),"Funst net",Toast.LENGTH_SHORT).show();
}
if(!bAdapter.isEnabled()) {
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
}
Set<BluetoothDevice> bondedDevices = bAdapter.getBondedDevices();
if(bondedDevices.isEmpty()) {
Toast.makeText(getApplicationContext(),"Muss gepaired werden",Toast.LENGTH_SHORT).show();
} else {
for (BluetoothDevice iter : bondedDevices) {
if(iter.getAddress().equals(DEVICE_ADRESS)) { // oder iter.getName() wenn Name bekannt muessen dann aendern
device=iter;
found=true;
break;
}
}
}
When I delete the section under this quote. The app starts just fine.
try{
btSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
}catch(IOException ioe){
Log.v(TAG, "socket nit erstellt");
}
}
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
device = bAdapter.getRemoteDevice(DEVICE_ADRESS);
try {
btSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Socket nit erstellt", Toast.LENGTH_LONG).show();
}
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
}
}
}
#Override
public void onPause() {
super.onPause();
try {
btSocket.close();
} catch (IOException e2) {
}
}
}
I'd appreciate any help. By the way sorry for my formatting... I'm a newbie in creating posts.
Android Monitor:
08-27 17:56:51.857 3071-3071/? E/libprocessgroup: failed to make and chown /acct/uid_10058: Read-only file system
08-27 17:56:51.857 3071-3071/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
08-27 17:56:51.857 3071-3071/? I/art: Not late-enabling -Xcheck:jni (already on)
08-27 17:56:52.086 3071-3071/de.lutherschule.bled.bluetoothled I/InstantRun: Starting Instant Run Server for de.lutherschule.bled.bluetoothled
08-27 17:56:52.288 3071-3071/de.lutherschule.bled.bluetoothled W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
[ 08-27 17:56:52.386 1162: 2146 D/ ]
HostConnection::get() New Host Connection established 0xb68aea60, tid 2146
08-27 17:56:52.429 3071-3079/de.lutherschule.bled.bluetoothled W/art: Suspending all threads took: 17.085ms
08-27 17:56:52.442 3071-3071/de.lutherschule.bled.bluetoothled E/BluetoothAdapter: Bluetooth binder is null
08-27 17:56:52.442 3071-3071/de.lutherschule.bled.bluetoothled V/MainActvity: Funst
08-27 17:56:52.452 3071-3071/de.lutherschule.bled.bluetoothled D/AndroidRuntime: Shutting down VM
--------- beginning of crash
08-27 17:56:52.453 3071-3071/de.lutherschule.bled.bluetoothled E/AndroidRuntime: FATAL EXCEPTION: main
Process: de.lutherschule.bled.bluetoothled, PID: 3071
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.lutherschule.bled.bluetoothled/de.lutherschule.bled.bluetoothled.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference
at de.lutherschule.bled.bluetoothled.MainActivity.onCreate(MainActivity.java:59)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
Try to use
BluetoothDevice device = mAdapter.getRemoteDevice(address);
btsocket = device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
Here is my code.
try {
socket = connect_device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
h.sendEmptyMessage(0);
} catch (IOException e) {
// TODO Auto-generated catch block
h.sendEmptyMessage(1);
e.printStackTrace();
try {
socket.close();
} catch (IOException e2) {
}
}

How can I change the volume properly?

I have been stuck on this for way too long (4 hours yesterday, 3 hours today!) now. In my main menu screen, I have a mute button. I want it to call a method in my background service, which mutes all of the MediaPlayer audio that would be played in the background of my game.
Full code here
Here is something that might be causing the issue:
I am getting the error whenever the audio plays (which plays fine):
QCMediaPlayer mediaplayer NOT present
E/MediaPlayer﹕ Should have subtitle controller already set
package com.example.USERNAME.buttonsmasher;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
public class TwentySeconds extends Service {
static MediaPlayer ten;
static MediaPlayer three;
final String TAG = "MyCountdown";
static CountDownTimer cdt;
double millisUntilFinishedRounded;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Context context = this;
three = MediaPlayer.create(TwentySeconds.this, R.raw.threetwoone);
ten = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
// ten = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
// three = MediaPlayer.create(TwentySeconds.this, R.raw.threetwoone);
Log.v(TAG, "In start command");
cdt = new CountDownTimer(20000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.v(TAG, millisUntilFinished + "left");
millisUntilFinishedRounded = (millisUntilFinished / 1000) * 1000;
if (millisUntilFinishedRounded == 10000) { //TEN SECONDS
// ten = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
// while(ten == null){
ten = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
// }
ten.start();
}
if (millisUntilFinishedRounded == 3000) {
/* Context context = this;
three = MediaPlayer.create(TwentySeconds.this, R.raw.threetwoone);
*/
// while(three == null){
three = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
//}
three.start();
}
}
#Override
public void onFinish() {
Log.v(TAG, "Finished");
Intent intent = new Intent(TwentySeconds.this, GameOver.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.v(TAG, "About to start activity");
startActivity(intent);
}
};
cdt.start();
return START_STICKY;
}
public static void stopTimer() {
cdt.cancel();
}
public static void myMute() {
ten.setVolume(0, 0);
three.setVolume(0, 0);
}
public static void unMute() {
ten.setVolume(1, 1);
three.setVolume(1, 1);
}
#Override
public void onDestroy() {
stopSelf();
super.onDestroy();
}
}
_______________________________________________________________________________________________________________________________
Here is the method in Main_Menu (x starts as zero)
if ((x%2) == 0) { //If it's even
TwentySeconds.unMute();
Toast.makeText(Main_Menu.this, "UNMUTED", Toast.LENGTH_SHORT).show();
x++;
} else { //If its odd
TwentySeconds.myMute();
Toast.makeText(Main_Menu.this, "MUTED", Toast.LENGTH_SHORT).show();
x++;
}
__________________________________________________________________
Here is the stack trace:
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3842)
at android.view.View.performClick(View.java:4457)
at android.view.View$PerformClick.run(View.java:18491)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5272)
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:883)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3837)
at android.view.View.performClick(View.java:4457)
at android.view.View$PerformClick.run(View.java:18491)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5272)
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:883)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.USERNAME.buttonsmasher.TwentySeconds.myMute(TwentySeconds.java:106)
at com.example.USERNAME.buttonsmasher.Main_Menu.mute(Main_Menu.java:103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3837)
at android.view.View.performClick(View.java:4457)
at android.view.View$PerformClick.run(View.java:18491)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5272)
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:883)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at dalvik.system.NativeStart.main(Native Method)
I would really appreciate any feedback (positive or negative)!
Let me know if you need any thing else. Thanks so much for everything, I hope I can solve this issue... :)

Android camera preview freezes suddenly

I have implemented an android camera with the help of official developer.android.com tutorial. The app is working fine sometimes but about 3/5 of times the preview of the camera freezes after some rotation and clicking the buttons or even without these works (other elements don't freeze). The cutest part is that when I debug the application the preview doesn't stuck but when I want to run the app normally sometimes the problem happens.
Here is my fullScreen Class which is consist of the codes that android studio generated for fullScreen activity and the codes for implementing surfaceHolder.Callback and camera stuff.
public class CameraActivity extends Activity implements SurfaceHolder.Callback {
... // some constants here
private Camera mCamera;
private SurfaceHolder mHolder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
SurfaceView cameraSufaceView = (SurfaceView) findViewById(R.id.camera_preview);
// Accessing front camera to take picture
mCamera = openFrontFacingCameraGingerbread();
if (mCamera != null) {
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = cameraSufaceView.getHolder();
mHolder.addCallback(this);
} else {
// Alter user
}
/**
* Gets an instance of front facing camera if available
*/
#SuppressWarnings("deprecation")
private Camera openFrontFacingCameraGingerbread() {
int cameraCount;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
try {
cam = Camera.open(camIdx);
} catch (RuntimeException e) {
Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
}
}
}
return cam;
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null) {
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
// start preview with new settings
try {
// mCamera.setDisplayOrientation(needs degree here);
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e) {
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
releaseCamera();
}
#Override
protected void onPause() {
super.onPause();
releaseCamera();
}
#Override
protected void onResume() {
super.onResume();
if (mCamera == null)
mCamera = openFrontFacingCameraGingerbread();
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
When this problem happens some errors appear in the LogCat but they are not really informative. here are they:
26893-26893/com.naviiid.retinaflash E/art﹕ No implementation found for void java.lang.Runtime.appStartupEnd() (tried Java_java_lang_Runtime_appStartupEnd and Java_java_lang_Runtime_appStartupEnd__)
09-16 01:34:09.336 26893-26893/com.naviiid.retinaflash E/ActivityThread﹕ appStartupEnd :
java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at android.app.ActivityThread.appStartupEnd(ActivityThread.java:305)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2819)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
Caused by: java.lang.UnsatisfiedLinkError: No implementation found for void java.lang.Runtime.appStartupEnd() (tried Java_java_lang_Runtime_appStartupEnd and Java_java_lang_Runtime_appStartupEnd__)
at java.lang.Runtime.appStartupEnd(Native Method)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java)
            at android.app.ActivityThread.appStartupEnd(ActivityThread.java:305)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2819)
            at android.app.ActivityThread.access$900(ActivityThread.java:177)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5942)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
The only clue that I have found so far is that sometimes android calls onPause method even if the activity isn't paused. For getting instance of the camera again I call openFrontFacingCameraGingerbread() in onResume method.

How do I pull a string from an array in Android?

I have an android app that is a streaming radio.
To change the radio stations, there is a drop down menu (based on a spinner) that allows the user to select the radio station and then it will load.
Problem: when I leave it as default, the first channel plays fine ...
when I try to chose another station, the app crashes.
I am using the new Android Studio.
I think that I am not getting the string for the URL from the array.
Can someone help me see what my mistake is??
Here is my code:
import android.annotation.TargetApi;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class AndroidMediaPlayerExample extends Activity {
private MediaPlayer mediaPlayer;
public TextView songName, duration;
private double timeElapsed = 0, finalTime = 0;
private int forwardTime = 2000, backwardTime = 2000;
private Handler durationHandler = new Handler();
private SeekBar seekbar;
//String url = "http://radio.miraath.net:7000";
//String url = new String[]{"http://radio.miraath.net:7000", "http://radio.miraath.net:7010", "http://radio.miraath.net:7020", "http://radio.miraath.net:7030","http://radio.miraath.net:7040", };
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set the layout of the Activity
setContentView(R.layout.activity_main);
Spinner dropdown = (Spinner)findViewById(R.id.spinner1);
String[] items = new String[]{"Radio 1: Arabic", "Radio 2: Live Arabic", "Radio 3: Qur'an", "Radio 4: English Radio", "Radio 5: Arabic Radio 2"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
dropdown.setAdapter(adapter);
//initialize views
initializeViews();
}
public void initializeViews(){
songName = (TextView) findViewById(R.id.songName);
mediaPlayer = MediaPlayer.create(this, R.raw.sample_song);
finalTime = mediaPlayer.getDuration();
duration = (TextView) findViewById(R.id.songDuration);
seekbar = (SeekBar) findViewById(R.id.seekBar);
songName.setText("Radio1 - Miraath.net");
seekbar.setMax((int) finalTime);
seekbar.setClickable(false);
}
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
mediaPlayer.release();
switch (position) {
case 0:
// Whatever you want to happen when the first item gets selected
url = "http://radio.miraath.net:7000";
break;
case 1:
// Whatever you want to happen when the second item gets selected
url = "http://radio.miraath.net:7010";
break;
case 2:
// Whatever you want to happen when the thrid item gets selected
url = "http://radio.miraath.net:7020";
break;
case 3:
// Whatever you want to happen when the thrid item gets selected
url = "http://radio.miraath.net:7030";
break;
case 4:
// Whatever you want to happen when the thrid item gets selected
url = "http://radio.miraath.net:7040";
break;
}
}
// play mp3 song
public void play(View view) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(url);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
mediaPlayer.start();
timeElapsed = mediaPlayer.getCurrentPosition();
seekbar.setProgress((int) timeElapsed);
durationHandler.postDelayed(updateSeekBarTime, 100);
}
//handler to change seekBarTime
private Runnable updateSeekBarTime = new Runnable() {
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void run() {
//get current position
timeElapsed = mediaPlayer.getCurrentPosition();
//set seekbar progress
seekbar.setProgress((int) timeElapsed);
//set time remaing
double timeRemaining = finalTime - timeElapsed;
duration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));
//repeat yourself that again in 100 miliseconds
durationHandler.postDelayed(this, 100);
}
};
// pause mp3 song
public void pause(View view) {
mediaPlayer.pause();
}
// go forward at forwardTime seconds
public void forward(View view) {
//check if we can go forward at forwardTime seconds before song endes
if ((timeElapsed + forwardTime) <= finalTime) {
timeElapsed = timeElapsed + forwardTime;
//seek to the exact second of the track
mediaPlayer.seekTo((int) timeElapsed);
}
}
// go backwards at backwardTime seconds
public void rewind(View view) {
//check if we can go back at backwardTime seconds after song starts
if ((timeElapsed - backwardTime) > 0) {
timeElapsed = timeElapsed - backwardTime;
//seek to the exact second of the track
mediaPlayer.seekTo((int) timeElapsed);
}
}
}
UPDATE!!!
Here is the error from the log:
03-14 19:20:10.413 1191-1284/system_process W/AudioTrack﹕ AUDIO_OUTPUT_FLAG_FAST denied by client
03-14 19:20:10.422 1191-1416/system_process I/ActivityManager﹕ START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.javacodegeeks.androidmediaplayerexample/.AndroidMediaPlayerExample (has extras)} from uid 10008 on display 0
03-14 19:20:10.457 4043-4043/? E/libprocessgroup﹕ failed to make and chown /acct/uid_10065: Read-only file system
03-14 19:20:10.457 4043-4043/? W/Zygote﹕ createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
03-14 19:20:10.457 4043-4043/? I/art﹕ Not late-enabling -Xcheck:jni (already on)
03-14 19:20:10.461 1191-3310/system_process I/ActivityManager﹕ Start proc com.javacodegeeks.androidmediaplayerexample for activity com.javacodegeeks.androidmediaplayerexample/.AndroidMediaPlayerExample: pid=4043 uid=10065 gids={50065, 9997, 3003} abi=x86
03-14 19:20:10.493 4043-4050/? E/art﹕ Failed sending reply to debugger: Broken pipe
03-14 19:20:10.493 4043-4050/? I/art﹕ Debugger is no longer active
03-14 19:20:10.515 4043-4043/? D/AndroidRuntime﹕ Shutting down VM
03-14 19:20:10.515 4043-4043/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.javacodegeeks.androidmediaplayerexample, PID: 4043
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.javacodegeeks.androidmediaplayerexample/com.javacodegeeks.androidmediaplayerexample.AndroidMediaPlayerExample}: java.lang.ClassCastException: com.javacodegeeks.androidmediaplayerexample.AndroidMediaPlayerExample cannot be cast to android.widget.AdapterView$OnItemSelectedListener
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.ClassCastException: com.javacodegeeks.androidmediaplayerexample.AndroidMediaPlayerExample cannot be cast to android.widget.AdapterView$OnItemSelectedListener
at com.javacodegeeks.androidmediaplayerexample.AndroidMediaPlayerExample.onCreate(AndroidMediaPlayerExample.java:42)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Thanks!!
You have not added listener on your spinner. Do it in this manner after your adapter is set
dropdown.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
Also you activity has to implement OnItemSelectedListener
public class AndroidMediaPlayerExample extends Activity implements OnItemSelectedListener

NullPointerException in setPreviewDisplay(holder)

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.

Categories

Resources