why wont my Gyroscope app in android fire off any events? - java

alright so I'm new to programming for android, and I think I did something wrong, but I don't know what. I've looked at 3 different tutorials and my code seems to look like theirs. Can anyone tell me what I'm doing wrong? here is my src (altered from a android nehe tutorial).
package cypri.games;
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.opengl.GLSurfaceView;
import android.os.Bundle;
import android.util.Log;
/**
* The initial Android Activity, setting and initiating
* the OpenGL ES Renderer Class #see Lesson02.java
*
* #author Savas Ziplies (nea/INsanityDesign)
*/
public class DGearActivity extends Activity {
/** The OpenGL View */
private GLSurfaceView glSurface;
DGear dGear = new DGear();
private static final String TAG = "DEBUG";
SensorManager sensorManager;
private final SensorEventListener sensorListener = new SensorEventListener(){
public void onSensorChanged(SensorEvent se) {
if (se.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
dGear.playerX = se.values[0];
Log.v(TAG, "se.values[0] =" + se.values[0]);
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
/**
* Initiate the OpenGL View and set our own
* Renderer (#see Lesson02.java)
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorManager.registerListener(sensorListener, sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE), SensorManager.SENSOR_DELAY_GAME);
//Create an Instance with this Activity
glSurface = new GLSurfaceView(this);
//Set our own Renderer
glSurface.setRenderer(dGear);
//Set the GLSurface as View to this Activity
setContentView(glSurface);
}
/**
* Remember to resume the glSurface
*/
#Override
protected void onResume() {
Log.v(TAG, "or");
super.onResume();
glSurface.onResume();
sensorManager.registerListener(sensorListener, sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE), SensorManager.SENSOR_DELAY_GAME);
}
/**
* Also pause the glSurface
*/
#Override
protected void onPause() {
super.onPause();
glSurface.onPause();
Log.v(TAG, "op");
sensorManager.unregisterListener(sensorListener);
}
}

Are you running this in the emulator or on an actual device?
If you're running it on an actual device are you sure it has a gyroscope? There are lots of different sensor types and the gyroscope is only one of them. It could very well be one of the others.
Instead of only writing to the log if it's a gyroscope type, try writing the name of the se.sensor when that event fires. That way you'll at least know the event is firing.

Related

Multiple songs are playing,

Hello Every One I am trying to make music app in Android Studio. When I select a song in a recycler view, the song start playing in the new activity but when I go back to the songs list and select the new song both the songs start playing,I want that the previous song which was selected in the first place stop playing and new song start playing, How can I do it?
package com.recycler.hp.navigationbar;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
public class Revival_Activity extends Activity implements
OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener {
private ImageButton buttonPlayPause;
private SeekBar seekBarProgress;
String editTextSongURL;
private MediaPlayer mediaPlayer;
private int mediaFileLengthInMilliseconds; // this value contains the song duration in milliseconds. Look at getDuration() method in MediaPlayer class
private final Handler handler = new Handler();
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_revival_);
editTextSongURL=getIntent().getStringExtra("url");
initView();
}
/**
* This method initialise all the views in project
*/
#SuppressLint("ClickableViewAccessibility")
private void initView() {
buttonPlayPause = (ImageButton) findViewById(R.id.ButtonTestPlayPause);
buttonPlayPause.setOnClickListener(this);
seekBarProgress = (SeekBar) findViewById(R.id.SeekBarTestPlay);
seekBarProgress.setMax(99); // It means 100% .0-99
seekBarProgress.setOnTouchListener(this);
// editTextSongURL = getString(R.string.testsong_20_sec);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
/**
* Method which updates the SeekBar primary progress by current song playing position
*/
private void primarySeekBarProgressUpdater() {
seekBarProgress.setProgress((int) (((float) mediaPlayer.getCurrentPosition() / mediaFileLengthInMilliseconds) * 100)); // This math construction give a percentage of "was playing"/"song length"
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
primarySeekBarProgressUpdater();
}
};
handler.postDelayed(notification, 1000);
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.ButtonTestPlayPause) {
/** ImageButton onClick event handler. Method which start/pause mediaplayer playing */
try {
mediaPlayer.setDataSource(editTextSongURL); // setup song from http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3 URL to mediaplayer data source
mediaPlayer.prepare(); // you must call this method after setup the datasource in setDataSource method. After calling prepare() the instance of MediaPlayer starts load data from URL to internal buffer.
} catch (Exception e) {
e.printStackTrace();
}
mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets the song length in milliseconds from URL
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
buttonPlayPause.setImageResource(R.drawable.pause);
} else {
mediaPlayer.pause();
buttonPlayPause.setImageResource(R.drawable.play);
}
primarySeekBarProgressUpdater();
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (v.getId() == R.id.SeekBarTestPlay) {
/** Seekbar onTouch event handler. Method which seeks MediaPlayer to seekBar primary progress position*/
if (mediaPlayer.isPlaying()) {
SeekBar sb = (SeekBar) v;
int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100) * sb.getProgress();
mediaPlayer.seekTo(playPositionInMillisecconds);
}
}
return false;
}
#Override
public void onCompletion(MediaPlayer mp) {
/** MediaPlayer onCompletion event handler. Method which calls then song playing is complete*/
buttonPlayPause.setImageResource(R.drawable.play);
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
/** Method which updates the SeekBar secondary progress by current song loading from URL position*/
seekBarProgress.setSecondaryProgress(percent);
}
}
It’s possible that you’re creating multiple media player objects during your selections in your recyclerview. Try creating a singleton instance of media player that’s shared throughout your app and call mediaplayer.release() and then recreate before playing a new song.

Simple OpenGL ES 2.0 app on Android displaying blank screen: why?

So I'm following the book Open GL ES 2 for Android by Kevin Brothaler and I'm trying out the first chapter's project, which is basically coloring the screen red. I set up by Samsung Galaxy Note 3 so I can debug my app on there, and also set up an emulator that uses the host GPU for rendering. Also, I forced GPU rendering on my phone. I copied the code he had exactly into my eclipse project. Here's the code for reference:
package com.firstopenglproject.android;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ConfigurationInfo;
import android.opengl.GLSurfaceView;
//import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class FirstOpenGLProjectActivity extends Activity {
private static final String TAG = FirstOpenGLProjectActivity.class.getSimpleName();
private GLSurfaceView glSurfaceView;
private boolean rendererSet = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "Before calling super.onCreate()");
super.onCreate(savedInstanceState);
Log.d(TAG, "Before creating a new GLSurfaceView");
glSurfaceView = new GLSurfaceView(this);
Log.d(TAG, "Creating activity manager");
final ActivityManager activityManager =
(ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
Log.d(TAG, "Creating configuration info");
final ConfigurationInfo configurationInfo =
activityManager.getDeviceConfigurationInfo();
Log.d(TAG, "Getting supportsEs2 boolean");
final boolean supportsEs2 = configurationInfo.reqGlEsVersion >= 0x20000;
// || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1
// && (Build.FINGERPRINT.startsWith("generic")
// || Build.FINGERPRINT.startsWith("unknown")
// || Build.MODEL.contains("google_sdk")
// || Build.MODEL.contains("Emulator")
// || Build.MODEL.contains("Android SDK built for x86")));
Log.d(TAG, "supportsEs2 = " + supportsEs2);
if (supportsEs2) {
// Request an OpenGLES2 compatible context
glSurfaceView.setEGLContextClientVersion(2);
glSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0);
// Assign our renderer
glSurfaceView.setRenderer(new FirstOpenGLProjectRenderer());
rendererSet = true;
Toast.makeText(this, "Device supports OpenGL ES 2.0", Toast.LENGTH_LONG).show();
Log.d(TAG, "rendererSet is true");
} else {
Log.d(TAG, "OGLES2.0 not supported");
Toast.makeText(this, "This device does not support OpenGL ES 2.0", Toast.LENGTH_LONG).show();
return;
}
}
#Override
protected void onPause() {
super.onPause();
if (rendererSet) {
glSurfaceView.onPause();
}
}
#Override
protected void onResume() {
super.onResume();
if (rendererSet) {
glSurfaceView.onResume();
}
}
}
The logging tasks were ones that I added so that I can see whether the code is executing properly, and it is: I see all these log messages in LogCat. Here's the code for the renderer:
package com.firstopenglproject.android;
import static android.opengl.GLES20.GL_COLOR_BUFFER_BIT;
import static android.opengl.GLES20.glClear;
import static android.opengl.GLES20.glClearColor;
import static android.opengl.GLES20.glViewport;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLSurfaceView.Renderer;
public class FirstOpenGLProjectRenderer implements Renderer {
private static final String TAG = FirstOpenGLProjectRenderer.class.getSimpleName();
/*
* GLSurfaceView calls this when its time to draw a frame. We must
* draw something, even if its only to clear the screen. The rendering buffer
* will be swapped and displayed on the screen after this method returns,
* so if we don't draw anything, we'll probably get a bad flickering effect.
* */
#Override
public void onDrawFrame(GL10 arg0) {
// clear the rendering surface
glClear(GL_COLOR_BUFFER_BIT);
}
/*
* GLSurfaceView calls this after the surface is created and whenever the size has
* changed. A size change can occur when switcheing from portrait to landscape
* and vice versa.
*/
#Override
public void onSurfaceChanged(GL10 glUnused, int width, int height) {
// set the openGL viewport to fill the entire surface
glViewport(0, 0, width, height);
}
/*
* GLSurfaceView calls this when the surface is created. This happens the first
* time our application is run, and it may also be called when the device wakes
* up or when the user switches back to our activity. In practice, this means that
* this method may be called multiple times while our application is still running.
*/
#Override
public void onSurfaceCreated(GL10 arg0, EGLConfig arg1) {
glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
}
}
As you can see, I only use 3 calls to static methods in the GLES20 package. When I run this app on my phone and on my emulator I get a blank screen: what is going on? I've been banging my head on the table for the last 2 hours about this, and this is as simple as it could possibly get. It's supposed to display a red screen. Thanks a bunch!
you are not setting the view in your OnCreate() method at the end of that method add:
setContentView(glSurfaceView);

TYPE_ROTATION_VECTOR not working on certain devices

i have made a program that uses TYPE_ROTATION_VECTOR to get orientation of the mobile phone.. the program works on certain samsung galaxy s phone but not on sony xperia neo v.. all phones have android version with api >= 9.. what could be the problem ?
package com.example.sensortest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity implements SensorEventListener{
TextView t1,t2,t3;
private SensorManager mSensorManager;
private Sensor mRotVectSensor;
private float[] orientationVals=new float[3];
private float[] mRotationMatrix=new float[16];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1=(TextView)findViewById(R.id.TextView1);
t2=(TextView)findViewById(R.id.TextView2);
t3=(TextView)findViewById(R.id.TextView3);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mRotVectSensor=mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onSensorChanged(SensorEvent event)
{
if(event.sensor.getType()==Sensor.TYPE_ROTATION_VECTOR)
{
SensorManager.getRotationMatrixFromVector(mRotationMatrix,event.values);
SensorManager.remapCoordinateSystem(mRotationMatrix,SensorManager.AXIS_X, SensorManager.AXIS_Z, mRotationMatrix);
SensorManager.getOrientation(mRotationMatrix, orientationVals);
orientationVals[0]=(float)Math.toDegrees(orientationVals[0]);
orientationVals[1]=(float)Math.toDegrees(orientationVals[1]);
orientationVals[2]=(float)Math.toDegrees(orientationVals[2]);
t1.setText(String.valueOf(orientationVals[0]));
t2.setText(String.valueOf(orientationVals[1]));
t3.setText(String.valueOf(orientationVals[2]));
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
protected void onResume() {
super.onResume();
// register this class as a listener for the orientation and
// accelerometer sensors
mSensorManager.registerListener(this,
mRotVectSensor,
10000);
}
#Override
protected void onPause() {
// unregister listener
super.onPause();
mSensorManager.unregisterListener(this);
}
}
You have to check mRotVectSensor for null value. For Sensor.TYPE_ROTATION_VECTOR the device has to have a gyroscope.
I may not solve your problem, but make sure you're using different matrices in SensorManager.remapCoordinateSystem (see Documentation). There it says: (Parameter) outR- the transformed rotation matrix. inR and outR should not be the same array.

unable to get touched x and y positions back

I just started learning how to program for android and cant seem to get the x positions for when someone clicks on the screen to appear in log cat. (im using an emulator if that has to do with anything) when i do click on the screen nothing happens. Here is my program on startup i get no errors. also using a relative layout
package com.practice;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class PracticeActivity extends Activity implements OnTouchListener{
int touchX;
int touchY;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
onTouchEvent(event);
touchX = (int) event.getX();
touchY = (int) event.getY();
Log.d( "MOUSE", String.valueOf(touchX) );
return true;
}
}
Your OnTouchListener won't get called until you register it with a view. For example:
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Find a view in the layout
View view = findViewById(android.id.content);
// register the listener
view.setOnTouchListener(this);
}
Try using Integer.toString(touchX) and return false instead of true, other than that your code seems fine.
Emulator do register the touch events.
Also there is a utility called as DDMS, located in the tools folder of the SDK. When your emulator is running, use this utility to get the graphical logcat. You can filter messages as well.

Overlays not working in Google MapView Tutorial Android

Got some errors following the tutorial for MapView when i was going to integrate overlays.
TravelBuddy.java
package com.jappapps.android.travelbuddy;
import java.util.List;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
public class TravelBuddy extends MapActivity {
List<Overlay> mapOverlays;
Drawable drawable;
Overlays itemizedOverlay;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // changed to lowercase
MapView mapView = (MapView) findViewById(R.id.mapview); // match id in main.xml
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
drawable = this.getResources().getDrawable(R.drawable.androidmarker);
itemizedOverlay = new Overlays(drawable);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
Overlays.java
package com.jappapps.android.travelbuddy;
import java.util.ArrayList;
import android.graphics.drawable.Drawable;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class Overlays extends ItemizedOverlay {
public Overlays(Drawable arg0) {
super(arg0);
Object overlayitem;
ItemizedOverlay.addOverlay(overlayitem);
Object itemizedoverlay;
ArrayList<OverlayItem> mapOverlays;
mapoverlays.add(itemizedOverlay);
}
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
super(boundCenterBottom(defaultMarker));
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
#Override
public int size() {
return 0;
}
}
Sorry if i look like a complete newbie, but i am trying to learn and i got an awesome app idea which needs mapview, webview, overlays and tabs.
#Override
public int size() {
return mOverlays.size();
}
I was using androidmarker.png from the "official" google mapview tutorial and was stuck with the overlays not showing up. I tried several other people's working examples and still same problem. I switched out androidmarker.png with a smaller png and it worked. So the code was fine, but something to do with the marker asset.

Categories