Android Wear Step Counter crashing app - java

I was writing an app to read heart rate and step count using an android wear device. The heart rate sensor works properly but the step count is causing an issue. However, on commenting the listener for Step Counter and registering a null in onResume() the app works with heart rate sensor. I'm not getting any log regarding this otherwise I would have posted it here. Here's the code that I'm using
import android.app.Activity;
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.support.wearable.view.WatchViewStub;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.Wearable;
import java.nio.ByteBuffer;
import java.util.List;
public class MainActivity extends Activity {
private SensorManager mSensorManager;
private TextView mTextViewHeart, mTextViewStep;
private Sensor mHeartRateSensor, mStepCounterSensor;
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mTextViewHeart = (TextView) stub.findViewById(R.id.value_heart);
mTextViewStep = (TextView) stub.findViewById(R.id.value_step);
}
});
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mHeartRateSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
mStepCounterSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Wearable.API).build();
mGoogleApiClient.connect();
}
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(heartListener, mHeartRateSensor, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(stepListener, mStepCounterSensor, SensorManager.SENSOR_DELAY_FASTEST);
}
#Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(heartListener, mHeartRateSensor);
}
SensorEventListener heartListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_HEART_RATE) {
if (event.values.length > 0) {
if (event.values[0] > 0.0f) {
mTextViewHeart.setBackgroundResource(android.R.color.holo_green_light);
mTextViewHeart.setText(Float.toString(event.values[0]));
sendToHandheld(Math.round(event.values[0]), Sensor.TYPE_HEART_RATE);
}
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
SensorEventListener stepListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
if (event.values.length > 0) {
mTextViewStep.setBackgroundResource(android.R.color.holo_green_light);
mTextViewStep.setText(Float.toString(event.values[0]));
sendToHandheld(Math.round(event.values[0]), Sensor.TYPE_STEP_COUNTER);
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
private void sendToHandheld(final int val, final int type) {
final PendingResult<NodeApi.GetConnectedNodesResult> nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient);
nodes.setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
#Override
public void onResult(NodeApi.GetConnectedNodesResult result) {
final List<Node> nodes = result.getNodes();
if (nodes != null) {
for (int i = 0; i < nodes.size(); i++) {
final Node node = nodes.get(i);
Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), "/" + type, ByteBuffer.allocate(4).putInt(val).array());
Log.d("Sending", type + ":" + val);
}
}
}
});
}
}
Update
Got the log somehow
06-15 11:46:02.342 3355-3355/com.hsc.fit E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.hsc.fit, PID: 3355
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setBackgroundResource(int)' on a null object reference
at com.hsc.fit.MainActivity$3.onSensorChanged(MainActivity.java:92)
at android.hardware.SystemSensorManager$SensorEventQueue.dispatchSensorEvent(SystemSensorManager.java:405)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:143)
at android.os.Looper.loop(Looper.java:122)
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)

Fixed it. The WatchViewStub's setOnLayoutInflatedListener() is called after onResume(), and my Sensor gets registered in onResume(). Since my text view is used in the listener of the sensor, and it wasn't assigned a refrence yet, I was getting a NullPointerException. I moved the sensor registertion inside WatchViewStub's listener and it works now.

Related

Google maps and Java. I need to get a device's long/lat and then put it into a variable

Currently working on a location-based AR game. I have some code which compiles which doesn't work (I am working with Android Studio but the code is Java).
Essentially, I am new to the maps API and I need help fixing what is wrong. How do I add my API key, which Google location API should I use, and how do I actually put this into variables? Thank you so much. (Ignore, some of the code won't cast into the coding box, sorry. All the import stuff right after this sentence).
import android.content.IntentSender;
import java.util.*;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class getLocation extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
public static final String TAG = getLocation.class.getSimpleName();
private GoogleMap mMap;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST=9000;
private LocationManager locationManager;
//This is readily being processed
public double [] handleNewLocation(Location location){
Log.d(TAG, location.toString());
double locLatitude = location.getLatitude();
double locLongitude = location.getLongitude();
double [] output = {locLatitude, locLongitude};
return output;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
while (true) {
double [] coor = handleNewLocation(LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient));
areaDefiner(coor);
}
}
//This is done three times based on original location
public static double [] areaDefiner(double [] input) { //input coordinates
double lat = input[0];
double lon = input[1];
//Creates an area
double size = 135.5;
double poop = Math.random() * size;
double pm = Math.random();
if(pm >= 0.5) {
poop *= - 1;
}
double outLat = lat + poop;
double outLon = lon + poop;
double [] output = {outLat, outLon};
return output;
}
#Override
protected void onResume() {
super.onResume();
//setUpMapIfNeeded();
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.i(TAG, "Location services connected.");
try {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null){}
else{
handleNewLocation(location);
}
} catch(SecurityException e) { // HAVE NO IDEA IF THIS IS RIGHT
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Location services suspended. Please reconnect.");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
}

mLastLocation value is getting null while creating Android Location API using GPS

I'm trying to create an Android Location API using Google Play Services. But I keep on getting " mLastLocation value as null " with a message " Couldn't get the location. Make sure location is enabled on the device " which I have given to display for the null value of mLastLocation. Can anyone tell me what I am doing wrong? Here's the code which I have been trying. Thanks in Advance.
CODE:
package com.example.jamshi.locationapi;
import android.app.Activity;
import android.location.Location;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends Activity implements ConnectionCallbacks,OnConnectionFailedListener {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
private TextView tvLocation;
private Button btnShowLocation,btnLocationUpdates;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvLocation = (TextView) findViewById(R.id.tvLocation);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
btnLocationUpdates = (Button) findViewById(R.id.btnLocationUpdates);
if(checkPlayServices()){
buildGoogleApiClient();
}
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displayLocation();
}
});
}
private void displayLocation() {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
tvLocation.setText(latitude + ", " + longitude);
} else {
tvLocation.setText("(Couldn't get the location. Make sure location is enabled on the device)");
}
}
private boolean checkPlayServices(){
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(resultCode != ConnectionResult.SUCCESS){
if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)){
GooglePlayServicesUtil.getErrorDialog(resultCode,this,PLAY_SERVICES_RESOLUTION_REQUEST).show();
}else{
Toast.makeText(getApplicationContext(),"This device is not supported",Toast.LENGTH_LONG).show();
finish();
}
return false;
}
return true;
}
protected synchronized void buildGoogleApiClient() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
}
#Override
protected void onStart() {
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
super.onStart();
}
#Override
protected void onResume() {
super.onResume();
checkPlayServices();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
public void onConnected(Bundle arg0) {
displayLocation();
}
#Override
public void onConnectionSuspended(int arg0)
{
mGoogleApiClient.connect();
}
}
If you are running on emulator then open google maps application first and then try your app
Test in device if you want to get data in first time and for genymotion emulator set location from side menus and then try. and if you are using android studio emulator set mock location and then try.
For more check this - How to emulate GPS location in the Android Emulator?

Android SeekBar NullPointerException

I have a probleme with my code. When I lunch my program i have a crash.
On the Android monitor i can see :
04-04 20:21:10.369 2042-2042/com.led.led E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.led.led, PID: 2042
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.led.led/com.led.led.ledControlSeekBar}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SeekBar.setOnSeekBarChangeListener(android.widget.SeekBar$OnSeekBarChangeListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5294)
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:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SeekBar.setOnSeekBarChangeListener(android.widget.SeekBar$OnSeekBarChangeListener)' on a null object reference
at com.led.led.ledControlSeekBar.onCreate(ledControlSeekBar.java:76)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420) 
at android.app.ActivityThread.access$900(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5294) 
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:904) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 
And there is my class :
package com.led.led;
import android.bluetooth.BluetoothDevice;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.SeekBar;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.os.AsyncTask;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View.OnClickListener;
import java.io.IOException;
import java.util.UUID;
import java.lang.String;
public class ledControlSeekBar extends AppCompatActivity {
Button btnDis;
SeekBar seek_r, seek_g, seek_b;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
ConnectBT bt = new ConnectBT();
String phraseAEnvoyer = "000000000";
String phraseTemp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//receive the address of the bluetooth device
Intent newint = getIntent();
address = newint.getStringExtra(DeviceList.EXTRA_ADDRESS);
bt.execute();
//view of the ledControl layout
setContentView(R.layout.activity_led_control);
//call the widgtes
btnDis = (Button)findViewById(R.id.button_disconnect);
seek_r = (SeekBar)findViewById(R.id.seekBar_r);
seek_g = (SeekBar)findViewById(R.id.seekBar_g);
seek_b = (SeekBar)findViewById(R.id.seekBar_b);
seek_r.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
msg("Rouge : " + progressChanged);
phraseTemp = phraseAEnvoyer.substring(3, 9);
phraseAEnvoyer = progressChanged + phraseTemp;
envoyerPhrase(phraseAEnvoyer);
}
});
seek_g.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
msg("Vert : " + progressChanged);
phraseTemp = phraseAEnvoyer.substring(6, 9);
phraseAEnvoyer = phraseAEnvoyer.substring(0, 3);
phraseAEnvoyer = phraseAEnvoyer + progressChanged + phraseTemp;
envoyerPhrase(phraseAEnvoyer);
}
});
seek_b.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
msg("Bleu : " + progressChanged);
phraseTemp = phraseAEnvoyer.substring(0, 6);
phraseAEnvoyer = phraseTemp + progressChanged;
envoyerPhrase(phraseAEnvoyer);
}
});
btnDis.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Disconnect(); //close connection
}
});
}
private void Disconnect()
{
if (btSocket!=null) //If the btSocket is busy
{
try
{
btSocket.close(); //close connection
}
catch (IOException e)
{ msg("Error");}
}
finish(); //return to the first layout
}
private void envoyerPhrase(String phrase)
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write(phraseAEnvoyer.getBytes());
msg(phraseAEnvoyer);
}
catch (IOException e)
{
msg("Error");
}
}
}
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(ledControlSeekBar.this, "Connecting...", "Please wait!"); //show a progress dialog
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
}
else
{
msg("Connected.");
isBtConnected = true;
}
progress.dismiss();
}
}
}
I don't finish and some lines are useful sorry.
If someone can help me I will happy.
Thank you.
I have also the same error . I resolved this error by defining a function outside the onCreate() method. Inside that function you need to call the different seek bar findViewByid method . Like this
private void initializeVariables() {
// Showing progress dialog
pDialog = new ProgressDialog(Search.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
seekBar = (SeekBar) findViewById(R.id.seekBarprice);
seekBarKilometer = (SeekBar) findViewById(R.id.seekBarDis);
}
Declare pDialog first private ProgressDialog pDialog;
call the initializeVariables() method inside the oncreate method , here i mention my seekbar names replace these names with your code .
`

Application Crashes when resuming the app

I am creating a simple Flashlight App, but every time I leave the app and reopen it, it crashes. Am I missing something in my code, because I am not sure what, below is an error when it crashes. Please let me know what I need to do in order to fix this resume issue:
package com.example.gkvxm.materiallight;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Toast;
import com.dd.CircularProgressButton;
import java.io.IOException;
public class FlashLightActivity extends Activity implements SurfaceHolder.Callback {
private boolean isLigtOn = false;
private Camera camera;
#Override
protected void onStart(){
super.onStart();
SurfaceView preview = (SurfaceView)findViewById(R.id.PREVIEW);
SurfaceHolder mHolder = preview.getHolder();
mHolder.addCallback(this);
}
#Override
protected void onStop(){
super.onStop();
if(camera!=null){
camera.release();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flash_light);
Context context = this;
PackageManager pm = context.getPackageManager();
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Toast.makeText(FlashLightActivity.this, "Your Device is not supported", Toast.LENGTH_SHORT).show();
Log.e("err", "Device is not supported");
return;
}
camera = Camera.open();
final Camera.Parameters p = camera.getParameters();
final CircularProgressButton circularButton1 = (CircularProgressButton) findViewById(R.id.btnWithText);
circularButton1.setIndeterminateProgressMode(true);
circularButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isLigtOn) {
turnOffFlash(p);
Toast.makeText(FlashLightActivity.this, "Lights Off!", Toast.LENGTH_SHORT).show();
} else {
turnOnFlash(p);
Toast.makeText(FlashLightActivity.this, "Lights On!", Toast.LENGTH_SHORT).show();
}
if (circularButton1.getProgress() == 0) {
simulateSuccessProgress(circularButton1);
} else {
circularButton1.setProgress(0);
}
}
});
}
private void turnOnFlash(Camera.Parameters p){
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
isLigtOn = true;
}
private void turnOffFlash(Camera.Parameters p){
p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
isLigtOn = false;
}
#Override
public void surfaceChanged(SurfaceHolder holder,int format,int width,int height){
}
#Override
public void surfaceCreated(SurfaceHolder holder){
try{
Log.i("SurfaceHolder","Setting preview");
camera.setPreviewDisplay(holder);
} catch (IOException e){
e.printStackTrace();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder){
Log.i("SurfaceHOlder", "stopping preview");
camera.stopPreview();
holder = null;
}
private void simulateSuccessProgress(final CircularProgressButton button) {
ValueAnimator widthAnimation = ValueAnimator.ofInt(1, 100);
widthAnimation.setDuration(1500);
widthAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
widthAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
Integer value = (Integer) animation.getAnimatedValue();
button.setProgress(value);
}
});
widthAnimation.start();
}
private void simulateErrorProgress(final CircularProgressButton button) {
ValueAnimator widthAnimation = ValueAnimator.ofInt(1, 99);
widthAnimation.setDuration(1500);
widthAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
widthAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
Integer value = (Integer) animation.getAnimatedValue();
button.setProgress(value);
if (value == 99) {
button.setProgress(-1);
}
}
});
widthAnimation.start();
}
}
Error :
05-22 03:08:35.646 13909-13909/com.example.gkvxm.materiallight E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.gkvxm.materiallight, PID: 13909
java.lang.RuntimeException: Camera is being used after Camera.release() was called
at android.hardware.Camera._stopPreview(Native Method)
at android.hardware.Camera.stopPreview(Camera.java:732)
at com.example.gkvxm.materiallight.FlashLightActivity.surfaceDestroyed(FlashLightActivity.java:129)
at android.view.SurfaceView.updateWindow(SurfaceView.java:564)
at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:238)
at android.view.View.dispatchWindowVisibilityChanged(View.java:8785)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1164)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1164)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1164)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1164)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1318)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5885)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:550)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
Camera is being used after Camera.release() was called. So, looking at the activity lifecycle, you need to open the camera in onStart() or in onRestart(). So Maybe this code will work fine ...
package com.example.gkvxm.materiallight;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Toast;
import com.dd.CircularProgressButton;
import java.io.IOException;
public class FlashLightActivity extends Activity implements SurfaceHolder.Callback {
private boolean isLigtOn = false;
private Camera camera;
#Override
protected void onStart(){
super.onStart();
camera = Camera.open();
final Camera.Parameters p = camera.getParameters();
SurfaceView preview = (SurfaceView)findViewById(R.id.PREVIEW);
SurfaceHolder mHolder = preview.getHolder();
mHolder.addCallback(this);
}
#Override
protected void onStop(){
super.onStop();
if(camera!=null){
camera.release();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flash_light);
Context context = this;
PackageManager pm = context.getPackageManager();
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Toast.makeText(FlashLightActivity.this, "Your Device is not supported", Toast.LENGTH_SHORT).show();
Log.e("err", "Device is not supported");
return;
}
camera = Camera.open();
final Camera.Parameters p = camera.getParameters();
final CircularProgressButton circularButton1 = (CircularProgressButton) findViewById(R.id.btnWithText);
circularButton1.setIndeterminateProgressMode(true);
circularButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isLigtOn) {
turnOffFlash(p);
Toast.makeText(FlashLightActivity.this, "Lights Off!", Toast.LENGTH_SHORT).show();
} else {
turnOnFlash(p);
Toast.makeText(FlashLightActivity.this, "Lights On!", Toast.LENGTH_SHORT).show();
}
if (circularButton1.getProgress() == 0) {
simulateSuccessProgress(circularButton1);
} else {
circularButton1.setProgress(0);
}
}
});
}
private void turnOnFlash(Camera.Parameters p){
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
isLigtOn = true;
}
private void turnOffFlash(Camera.Parameters p){
p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
isLigtOn = false;
}
#Override
public void surfaceChanged(SurfaceHolder holder,int format,int width,int height){
}
#Override
public void surfaceCreated(SurfaceHolder holder){
try{
Log.i("SurfaceHolder","Setting preview");
camera.setPreviewDisplay(holder);
} catch (IOException e){
e.printStackTrace();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder){
Log.i("SurfaceHOlder", "stopping preview");
camera.stopPreview();
holder = null;
}
private void simulateSuccessProgress(final CircularProgressButton button) {
ValueAnimator widthAnimation = ValueAnimator.ofInt(1, 100);
widthAnimation.setDuration(1500);
widthAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
widthAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
Integer value = (Integer) animation.getAnimatedValue();
button.setProgress(value);
}
});
widthAnimation.start();
}
private void simulateErrorProgress(final CircularProgressButton button) {
ValueAnimator widthAnimation = ValueAnimator.ofInt(1, 99);
widthAnimation.setDuration(1500);
widthAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
widthAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
Integer value = (Integer) animation.getAnimatedValue();
button.setProgress(value);
if (value == 99) {
button.setProgress(-1);
}
}
});
widthAnimation.start();
}
}
As the Log says Camera is being used after Camera.release() was called. So, looking at the activity lifecycle you need to open camera in onStart() or in onRestart()
This exception is because of camera.release(); is called in the onStop() method of your activity. After releasing the camera instance you are reusing the released instance.
camera = Camera.open();
move the above line from OnCreate() to onStart()
You are releasing the camera instance in onPause() which is correct due to documentation:
public final void release ()
Added in API level 1 Disconnects and releases the Camera object
resources.
You must call this as soon as you're done with the Camera object.
But you also need to re-open it in onResume(), like you do in onCreate, since onCreate() not always is called when you resume the app.
As they state here:
Important: Call release() to release the camera for use by other
applications. Applications should release the camera immediately in
onPause() (and re-open() it in onResume()).
See this for more information about the android app lifecycle.
Good luck!
It may be you are camera.release(); on onStop(). And when surfaceDestroyed call you have used camera.stopPreview();
so camera is alredy release and you are going to stopePreview. thats way you are geting Camera is being used after Camera.release() was called this error.
so you have to cange that.
#Override
protected void onStop(){
super.onStop();
}
and on surfaceDestroyed
#Override
public void surfaceDestroyed(SurfaceHolder holder){
Log.i("SurfaceHOlder", "stopping preview");
camera.stopPreview();
camera.release();
holder = null;
}
I have same problem with camera class. Use this line onResume()
mCameraPreview.getHolder().removeCallback(mCameraPreview);
and its work now.
I had an app with the same issue,
when I removed "on click listener" inside my on create function, the problem was solved.
I think we should never insert any implementation function or other things inside our onCreate method...
It's better to use onCreate only for declaring and instantiating variables.

fatal exception: main java.lang.RuntimeException in android map,

i'm currently working on android maps by following this tutorial http://developer.android.com/training/location/retrieve-current.html, and i keep getting error.there are 4 warnings and i tried to fix it but when i run it again the error message fatal exception still showing
here's the warning messages:
1. the message servicesConnected() from the type LokasiKampus is never used locally
2. the value of local variable kampus is not used
3. the value of local variable laboratorium is not used
4.the value of local variable myCurrentLocation is not used
here's my Java code
package ninth.example.dteinformationcenter;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class LokasiKampus extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener{
static final LatLng Kampus = new LatLng (-7.775038, 110.373253);
static final LatLng Laboratorium = new LatLng (-7.765437, 110.374496);
private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap map;
private GooglePlayServicesClient myLocationClient;
public static class ErrorDialogFragment extends DialogFragment {
private Dialog mDialog;
public ErrorDialogFragment() {
super();
mDialog = null;
}
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
public void show(FragmentManager supportFragmentManager, String tag) {
// TODO Auto-generated method stub
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case CONNECTION_FAILURE_RESOLUTION_REQUEST :
switch(resultCode) {
case Activity.RESULT_OK : break;
}
}
}
**private boolean servicesConnected()** {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == resultCode) {
Log.d("Location Updated", "Google Play Services is available");
return true;
} else {
Dialog ErrorDialog = GooglePlayServicesUtil
.getErrorDialog(resultCode, this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
if (ErrorDialog != null) {
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
errorFragment.setDialog(ErrorDialog);
errorFragment.show(getSupportFragmentManager(), "Location Updates");
}
return false;
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lokasi_kampus);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.lokasikampus)).getMap();
if (map != null) {
**Marker kampus = map.addMarker(new MarkerOptions().position(Kampus)
.title("Kampus "));
Marker laboratorium = map.addMarker(new MarkerOptions().position(Laboratorium)
.position(Laboratorium)
.title("Laboratorium")
);**
map.moveCamera(CameraUpdateFactory.newLatLngZoom(Kampus, 18));
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}
LocationClient myLocationClient = new LocationClient(this,this,this);
**Location myCurrentLocation;
myCurrentLocation = myLocationClient.getLastLocation();**
}
#Override
public void onConnected(Bundle dataBundle) {
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
}
#Override
public void onDisconnected() {
Toast.makeText(this, "Disconnected, please re-connect", Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if(connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch(IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, "Connection Failed", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onStart() {
super.onStart();
myLocationClient.connect();
}
#Override
protected void onStop() {
myLocationClient.disconnect();
super.onStop();
}
}
this is the error message
FATAL EXCEPTION: main
Process: ninth.example.dteinformationcenter, PID: 1443
java.lang.RuntimeException: Unable to start activity ComponentInfo{ninth.example.dteinformationcenter/ninth.example.dteinformationcenter.LokasiKampus}: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
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)
Caused by: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
at com.google.android.gms.internal.hb.cn(Unknown Source)
at com.google.android.gms.internal.jg.b(Unknown Source)
at com.google.android.gms.internal.jg$c.cn(Unknown Source)
at com.google.android.gms.internal.jf.getLastLocation(Unknown Source)
at com.google.android.gms.internal.jg.getLastLocation(Unknown Source)
at com.google.android.gms.location.LocationClient.getLastLocation(Unknown Source)
at ninth.example.dteinformationcenter.LokasiKampus.onCreate(LokasiKampus.java:112)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)

Categories