Good day dear sirs. I have encountered a problem with the animation and controls of my character. My problem is whenever I tried to press the left and right arrow key my player moves up and down instead of going left and right. I did tried to debug my code by I still can't find out which part of the code is wrong. That's why I'm asking you guys to look up my code and could possibly tell which part of the code is wrong or needs improvement.
This is my code for my player:
public class DugmanPlayer {
public enum state
{
standby,
walking,
digging,
dying
}
public enum dir
{
left,
right,
up,
down
}
public static float WIDTH;
public static float HEIGHT;
static float speedmax = 30f;
static float damping = 0.9f;
dir d = dir.up;
public Vector2 position = new Vector2();
public Vector2 speed = new Vector2();
state st = state.walking;
public float statetime = 0;
public void UpdatePlayer(float deltatime)
{
if(deltatime==0)return;
statetime += deltatime;
//rightwalking
if(Math.abs(speed.x) > speedmax) {
speed.x = Math.signum(speed.x) * speedmax;
if(d != dir.left)d = dir.right;
st = state.walking;
}
if(Math.abs(speed.x) < 1) {
speed.x = 0;
if(st!=state.walking)st = state.standby;
d=dir.right;
}
//upwalking
if(Math.abs(speed.y) > speedmax) {
speed.y = Math.signum(speed.y) * speedmax;
if(d != dir.down)d = dir.up;
st = state.walking;
}
if(Math.abs(speed.y) < 1) {
speed.y = 0;
if(st != state.walking)st = state.standby;
d=dir.up;
}
if(Math.abs(-speed.x)>speedmax)
{
speed.x = Math.signum(-speed.x) * speedmax;
if(d != dir.right)d = dir.left;
st = state.walking;
}
if(Math.abs(-speed.x)<1)
{
speed.x = 0;
if(st!=state.walking)st = state.standby;
d=dir.up;
}
if(Math.abs(-speed.y)>speedmax){
speed.y = Math.signum(-speed.y) * speedmax;
if(d != dir.up)d = dir.down;
st = state.walking;
}
if(Math.abs(-speed.y)<1)
{
speed.y = 0;
if(st!=state.walking)st = state.standby;
d=dir.down;
}
speed.scl(deltatime);
position.add(speed);
speed.scl(1/deltatime);
// Apply damping to the velocity on the x-axis so we don't
// walk infinitely once a key was pressed
speed.x *= damping;
speed.y *= damping;
InputProcess();
}
TextureRegion left;
TextureRegion right;
TextureRegion up;
TextureRegion down;
TextureRegion standby;
Animation Walkingleft;
Animation WalkingRight;
Animation WalkingUp;
Animation WalkingDown;
Animation stndbyleft,stndbyright,stndbyup,stndbydown;
public void LoadPlayerTexture()
{
TextureAtlas dug = new TextureAtlas(Gdx.files.internal("character/walking.pack"));
left = dug.findRegion("faceleft");
right = dug.findRegion("faceright");
up = dug.findRegion("faceup");
down = dug.findRegion("facedown");
TextureRegion[] leftwalk = left.split(left.getRegionWidth()/3, left.getRegionHeight()/1)[0];
TextureRegion[] rightwalk = right.split(right.getRegionWidth()/3, right.getRegionHeight()/1)[0];
TextureRegion[] upwalk = up.split(up.getRegionWidth()/3, up.getRegionHeight()/1)[0];
TextureRegion[] downwalk = down.split(down.getRegionWidth()/3, down.getRegionHeight()/1)[0];
Walkingleft = new Animation(0.5f, leftwalk[0],leftwalk[1],leftwalk[2]);
WalkingRight = new Animation(0.5f, rightwalk[0],rightwalk[1],rightwalk[2]);
WalkingUp = new Animation(0.5f, upwalk[0],upwalk[1],upwalk[2]);
WalkingDown = new Animation(0.5f, downwalk[0],downwalk[1],downwalk[2]);
stndbyleft = new Animation(0, leftwalk[1]);
stndbyright = new Animation(0, rightwalk[1]);
stndbyup = new Animation(0, upwalk[1]);
stndbydown = new Animation(0, downwalk[1]);
DugmanPlayer.WIDTH = 1/16f * leftwalk[0].getRegionWidth();
DugmanPlayer.HEIGHT = 1/16f * leftwalk[0].getRegionHeight();
}
public void DrawPlayer(float deltatime, OrthogonalTiledMapRenderer r)
{
Animation fm = null;
boolean loop = true;
switch (st) {
case standby: if(speed.y == 0){
fm = stndbyup;
}
else if(-speed.y == 0){
fm = stndbydown;
}else if (speed.x == 0) {
fm = stndbyright;
}else if (-speed.x == 0) {
fm = stndbyleft;
}
break;
case walking: if(speed.y>speedmax){
fm = WalkingUp;
}else if(-speed.y>speedmax){
fm = WalkingDown;
}else if (speed.x>speedmax) {
fm = WalkingRight;
}else if (-speed.x>speedmax) {
fm = Walkingleft;
}
break;
case digging:
break;
case dying:
break;
default:
break;
}
SpriteBatch batch = r.getSpriteBatch();
batch.begin();
batch.draw(fm.getKeyFrame(statetime, loop), position.x, position.y, WIDTH, HEIGHT);
batch.end();
}
public void InputProcess()
{
if(Gdx.input.isKeyPressed(Keys.UP) || Gdx.input.isKeyPressed(Keys.W)) {
if(st != state.standby)st = state.walking;
speed.y += speedmax;
d = dir.up;
}
else if(Gdx.input.isKeyPressed(Keys.DOWN) || Gdx.input.isKeyPressed(Keys.S)) {
if(st!=state.standby)st = state.walking;
speed.y = -speedmax;
d = dir.down;
}
else if(Gdx.input.isKeyPressed(Keys.LEFT) || Gdx.input.isKeyPressed(Keys.A)) {
if(st!=state.standby)st = state.walking;
speed.y = -speedmax;
d = dir.left;
}
else if(Gdx.input.isKeyPressed(Keys.RIGHT) || Gdx.input.isKeyPressed(Keys.D)) {
if(st!=state.standby)st = state.walking;
speed.y += speedmax;
d = dir.right;
}
else
{
st = state.standby;
speed.x = 0;
speed.y = 0;
}
}
}
What I did with my character class is that it will contain all the inputs for my character, render the animation to specific states and direction.
else if(Gdx.input.isKeyPressed(Keys.LEFT) || Gdx.input.isKeyPressed(Keys.A)) {
if(st!=state.standby)st = state.walking;
speed.y = -speedmax;
d = dir.left;
}
else if(Gdx.input.isKeyPressed(Keys.RIGHT) || Gdx.input.isKeyPressed(Keys.D)) {
if(st!=state.standby)st = state.walking;
speed.y += speedmax;
d = dir.right;
}
dont you think that u shuld use speed.x instead of speed.y in this code :)
Related
I am following Maze game tutorial from youtube Android Programming - Maze Game Pt4
The tutor's code in the video generates random mazes. I have followed the code to the 'T' throughout but my emulator only gives the following output -
My emulator's output
Here is my code. Can anyone tell me what i missed from the tutorial I was following or if the tutorial itself has some coding errors? -
public class MazaGame extends View {
private Cell[][] cells;
private static final int COLS = 7, ROWS = 10;
private static final float WALL_THICKNESS = 4;
private float cellSize,hMargin,vMargin;
private Paint wallPaint;
private Random random;
public MazaGame(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
wallPaint = new Paint();
wallPaint.setColor(Color.BLACK);
wallPaint.setStrokeWidth(WALL_THICKNESS);
random = new Random();
createMaze();
}
private Cell getNeighbor(Cell cell){
ArrayList<Cell> neighbors = new ArrayList<>();
//left neighbor
if(cell.col >0)
if(!cells[cell.col-1][cell.row].visited)
neighbors.add(cells[cell.col-1][cell.row]);
//right neighbor
if(cell.col < COLS-1)
if(!cells[cell.col+1][cell.row].visited)
neighbors.add(cells[cell.col+1][cell.row]);
//top neighbor
if(cell.row >0)
if(!cells[cell.col][cell.row-1].visited)
neighbors.add(cells[cell.col][cell.row-1]);
//bottom neighbor
if(cell.row < ROWS-1)
if(!cells[cell.col][cell.row+1].visited)
neighbors.add(cells[cell.col][cell.row+1]);
if(neighbors.size()>0) {
int index = random.nextInt(neighbors.size());
return neighbors.get(index);
}
return null;
}
private void removeWall(Cell current, Cell next){
if(current.col == next.col && current.row == next.row+1){
current.topWall = false;
next.bottomWall = false;
}
if(current.col == next.col && current.row == next.row-1){
current.bottomWall = false;
next.topWall = false;
}
if(current.col == next.col+1 && current.row == next.row){
current.leftWall = false;
next.rightWall = false;
}
if(current.col == next.col-1 && current.row == next.row){
current.rightWall = false;
next.leftWall = false;
}
}
private void createMaze() {
Stack<Cell> stack = new Stack<>();
Cell current, next;
cells = new Cell[COLS][ROWS];
for (int x = 0; x < COLS; x++) {
for (int y = 0; y < ROWS; y++) {
cells[x][y] = new Cell(x, y);
}
}
do {
current = cells[0][0];
current.visited = true;
next = getNeighbor(current);
if (next != null) {
removeWall(current, next);
stack.push(current);
current = next;
current.visited = true;
} else
current = stack.pop();
}while (!stack.empty());
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.RED);
int width = getWidth();
int height = getHeight();
if(width/height < COLS/ROWS)
cellSize = width/(COLS+1);
else
cellSize = height/(ROWS+1);
hMargin = (width-COLS*cellSize)/2;
vMargin = (height-ROWS*cellSize)/2;
canvas.translate(hMargin,vMargin);
for(int x=0;x<COLS;x++){
for(int y=0;y<ROWS;y++){
if(cells[x][y].topWall)
canvas.drawLine(
x*cellSize,
y*cellSize,
(x+1)*cellSize,
y*cellSize,
wallPaint);
if(cells[x][y].leftWall)
canvas.drawLine(
x*cellSize,
y*cellSize,
x*cellSize,
(y+1)*cellSize,
wallPaint);
if(cells[x][y].bottomWall)
canvas.drawLine(
x*cellSize,
(y+1)*cellSize,
(x+1)*cellSize,
(y+1)*cellSize,
wallPaint);
if(cells[x][y].rightWall)
canvas.drawLine(
(x+1)*cellSize,
y*cellSize,
(x+1)*cellSize,
(y+1)*cellSize,
wallPaint);
}
}
}
private class Cell{
boolean
topWall = true,
rightWall = true,
bottomWall = true,
leftWall = true,
visited = false;
int col,row;
public Cell(int col, int row) {
this.col = col;
this.row = row;
}
}
}
I'm not going to take the time to fully internalize 100% of the code you posted, but this section looks suspicious:
do {
current = cells[0][0];
current.visited = true;
next = getNeighbor(current);
if (next != null) {
removeWall(current, next);
stack.push(current);
current = next;
current.visited = true;
} else
current = stack.pop();
}while (!stack.empty());
I suspect you want this to look like this instead:
current = cells[0][0];
current.visited = true;
do {
next = getNeighbor(current);
if (next != null) {
removeWall(current, next);
stack.push(current);
current = next;
current.visited = true;
} else
current = stack.pop();
}while (!stack.empty());
What you have right now will continuously reset current to be the cell at (0,0), because every time through the loop, you're executing
current = cells[0][0];
current.visited = true;
I suspect that this is just supposed to be the initial setup for the first cell, and you don't want this happening every time through the loop.
I want to make my character to move smoothly when I tilt my phone. How I can make it to move smoothly and the velocity and the speed increases as the slope of the phone?
void AccelerometerMove(){
float x = Input.acceleration.x;
Debug.Log("X = " + x);
if (x < -0.1f)
{
MoveLeft();
}
else if (x > 0.1f)
{
MoveRight();
}
else
{
SetVelocityZero();
}
}
public void SetVelocityZero()
{
rb.velocity = Vector2.zero;
}
public void MoveLeft()
{
rb.velocity = new Vector2(-speed, 0);
//transform.Translate(Vector2.right * speed * Time.deltaTime);
transform.eulerAngles = new Vector2(0, 180);
}
public void MoveRight()
{
rb.velocity = new Vector2(speed, 0);
//transform.Translate(Vector2.right * speed * Time.deltaTime);
transform.eulerAngles = new Vector2(0, 0);
}
You can directly use the input of the accelerometer to set the speed of your object :
void AccelerometerMove()
{
float x = Input.acceleration.x;
Debug.Log("X = " + x);
if (x < -0.1f)
{
MoveLeft(x);
}
else if (x > 0.1f)
{
MoveRight(x);
}
else
{
SetVelocityZero();
}
}
public void SetVelocityZero()
{
rb.velocity = Vector2.zero;
}
public void MoveLeft( float s )
{
rb.velocity = new Vector2(s, 0);
transform.eulerAngles = new Vector2(0, 180);
}
public void MoveRight( float s )
{
rb.velocity = new Vector2(s, 0);
transform.eulerAngles = new Vector2(0, 0);
}
And / or use the Mathf.Lerp function to compute the speed :
void AccelerometerMove()
{
float x = Input.acceleration.x;
Debug.Log("X = " + x);
if (x < -0.1f)
{
MoveLeft();
}
else if (x > 0.1f)
{
MoveRight();
}
else
{
SetVelocityZero();
}
}
public void SetVelocityZero()
{
rb.velocity = Vector2.zero;
}
public void MoveLeft()
{
rb.velocity = new Vector2( Mathf.Lerp( rb.velocity.x, -speed, Time.deltaTime ), 0);
transform.eulerAngles = new Vector2(0, 180);
}
public void MoveRight()
{
rb.velocity = new Vector2( Mathf.Lerp( rb.velocity.x, speed, Time.deltaTime ), 0);
transform.eulerAngles = new Vector2(0, 0);
}
I am having a WaveFormView on which I want to change the color of it while playing Audio file and as the Audio is paused it should be stopped coloring at that certain point and when resumed it should continue forward with coloring. I am not getting how to do it in my code..
This is the screen shot of my generated waveform. Now when I will click on Play button it should change the color of waveform gradually with red color (from start to end slowly).
Here is my code to draw waveform view.
WaveFormView.class
public class WaveformView extends View {
public interface WaveformListener {
public void waveformFling(float x);
public void waveformDraw();
}
;
// Colors
private Paint mGridPaint;
private Paint mSelectedLinePaint;
private Paint mUnselectedLinePaint;
private Paint mUnselectedBkgndLinePaint;
private Paint mBorderLinePaint;
private Paint mPlaybackLinePaint;
private Paint mTimecodePaint;
private SoundFile mSoundFile;
private int[] mLenByZoomLevel;
private double[][] mValuesByZoomLevel;
private double[] mZoomFactorByZoomLevel;
private int[] mHeightsAtThisZoomLevel;
private int mZoomLevel;
private int mNumZoomLevels;
private int mSampleRate;
private int mSamplesPerFrame;
private int mOffset;
private int mSelectionStart;
private int mSelectionEnd;
private int mPlaybackPos;
private float mDensity;
private float mInitialScaleSpan;
private WaveformListener mListener;
private GestureDetector mGestureDetector;
private ScaleGestureDetector mScaleGestureDetector;
private boolean mInitialized;
Color color;
public WaveformView(Context context, AttributeSet attrs) {
super(context, attrs);
// We don't want keys, the markers get these
setFocusable(false);
mGridPaint = new Paint();
mGridPaint.setAntiAlias(false);
mGridPaint.setColor(
getResources().getColor(R.color.grid_line));
mSelectedLinePaint = new Paint();
mSelectedLinePaint.setAntiAlias(false);
mSelectedLinePaint.setColor(
getResources().getColor(R.color.waveform_selected));
mUnselectedLinePaint = new Paint();
mUnselectedLinePaint.setAntiAlias(false);
mUnselectedLinePaint.setColor(
getResources().getColor(R.color.waveform_unselected));
mUnselectedBkgndLinePaint = new Paint();
mUnselectedBkgndLinePaint.setAntiAlias(false);
mUnselectedBkgndLinePaint.setColor(
getResources().getColor(
R.color.selection_border));
mBorderLinePaint = new Paint();
mBorderLinePaint.setAntiAlias(true);
mBorderLinePaint.setStrokeWidth(1.5f);
mBorderLinePaint.setPathEffect(
new DashPathEffect(new float[]{3.0f, 2.0f}, 0.0f));
mBorderLinePaint.setColor(
getResources().getColor(R.color.selection_border));
mPlaybackLinePaint = new Paint();
mPlaybackLinePaint.setAntiAlias(false);
mPlaybackLinePaint.setColor(
getResources().getColor(R.color.playback_indicator));
mTimecodePaint = new Paint();
mTimecodePaint.setTextSize(12);
mTimecodePaint.setAntiAlias(true);
mTimecodePaint.setColor(
getResources().getColor(R.color.timecode));
mTimecodePaint.setShadowLayer(
2, 1, 1,
getResources().getColor(R.color.timecode_shadow));
mGestureDetector = new GestureDetector(
context,
new GestureDetector.SimpleOnGestureListener() {
public boolean onFling(
MotionEvent e1, MotionEvent e2, float vx, float vy) {
mListener.waveformFling(vx);
return true;
}
});
mSoundFile = null;
mLenByZoomLevel = null;
mValuesByZoomLevel = null;
mHeightsAtThisZoomLevel = null;
mOffset = 0;
mPlaybackPos = -1;
mSelectionStart = 0;
mSelectionEnd = 0;
mDensity = 1.0f;
mInitialized = false;
}
public boolean hasSoundFile() {
return mSoundFile != null;
}
public void setSoundFile(SoundFile soundFile) {
mSoundFile = soundFile;
mSampleRate = mSoundFile.getSampleRate();
mSamplesPerFrame = mSoundFile.getSamplesPerFrame();
computeDoublesForAllZoomLevels();
mHeightsAtThisZoomLevel = null;
}
/**
* Called once when a new sound file is added
*/
private void computeDoublesForAllZoomLevels() {
int numFrames = mSoundFile.getNumFrames();
int[] frameGains = mSoundFile.getFrameGains();
double[] smoothedGains = new double[numFrames];
if (numFrames == 1) {
smoothedGains[0] = frameGains[0];
} else if (numFrames == 2) {
smoothedGains[0] = frameGains[0];
smoothedGains[1] = frameGains[1];
} else if (numFrames > 2) {
smoothedGains[0] = (double)(
(frameGains[0] / 2.0) +
(frameGains[1] / 2.0));
for (int i = 1; i < numFrames - 1; i++) {
smoothedGains[i] = (double)(
(frameGains[i - 1] / 3.0) +
(frameGains[i ] / 3.0) +
(frameGains[i + 1] / 3.0));
}
smoothedGains[numFrames - 1] = (double)(
(frameGains[numFrames - 2] / 2.0) +
(frameGains[numFrames - 1] / 2.0));
}
// Make sure the range is no more than 0 - 255
double maxGain = 1.0;
for (int i = 0; i < numFrames; i++) {
if (smoothedGains[i] > maxGain) {
maxGain = smoothedGains[i];
}
}
double scaleFactor = 1.0;
if (maxGain > 255.0) {
scaleFactor = 255 / maxGain;
}
// Build histogram of 256 bins and figure out the new scaled max
maxGain = 0;
int gainHist[] = new int[256];
for (int i = 0; i < numFrames; i++) {
int smoothedGain = (int)(smoothedGains[i] * scaleFactor);
if (smoothedGain < 0)
smoothedGain = 0;
if (smoothedGain > 255)
smoothedGain = 255;
if (smoothedGain > maxGain)
maxGain = smoothedGain;
gainHist[smoothedGain]++;
}
// Re-calibrate the min to be 5%
double minGain = 0;
int sum = 0;
while (minGain < 255 && sum < numFrames / 20) {
sum += gainHist[(int)minGain];
minGain++;
}
// Re-calibrate the max to be 99%
sum = 0;
while (maxGain > 2 && sum < numFrames / 100) {
sum += gainHist[(int)maxGain];
maxGain--;
}
// Compute the heights
double[] heights = new double[numFrames];
double range = maxGain - minGain;
for (int i = 0; i < numFrames; i++) {
double value = (smoothedGains[i] * scaleFactor - minGain) / range;
if (value < 0.0)
value = 0.0;
if (value > 1.0)
value = 1.0;
heights[i] = value * value;
}
mNumZoomLevels = 5;
mLenByZoomLevel = new int[5];
mZoomFactorByZoomLevel = new double[5];
mValuesByZoomLevel = new double[5][];
// Level 0 is doubled, with interpolated values
mLenByZoomLevel[0] = numFrames * 2;
mZoomFactorByZoomLevel[0] = 2.0;
mValuesByZoomLevel[0] = new double[mLenByZoomLevel[0]];
if (numFrames > 0) {
mValuesByZoomLevel[0][0] = 0.5 * heights[0];
mValuesByZoomLevel[0][1] = heights[0];
}
for (int i = 1; i < numFrames; i++) {
mValuesByZoomLevel[0][2 * i] = 0.5 * (heights[i - 1] + heights[i]);
mValuesByZoomLevel[0][2 * i + 1] = heights[i];
}
// Level 1 is normal
mLenByZoomLevel[1] = numFrames;
mValuesByZoomLevel[1] = new double[mLenByZoomLevel[1]];
mZoomFactorByZoomLevel[1] = 1.0;
for (int i = 0; i < mLenByZoomLevel[1]; i++) {
mValuesByZoomLevel[1][i] = heights[i];
}
// 3 more levels are each halved
for (int j = 2; j < 5; j++) {
mLenByZoomLevel[j] = mLenByZoomLevel[j - 1] / 2;
mValuesByZoomLevel[j] = new double[mLenByZoomLevel[j]];
mZoomFactorByZoomLevel[j] = mZoomFactorByZoomLevel[j - 1] / 2.0;
for (int i = 0; i < mLenByZoomLevel[j]; i++) {
mValuesByZoomLevel[j][i] =
0.5 * (mValuesByZoomLevel[j - 1][2 * i] +
mValuesByZoomLevel[j - 1][2 * i + 1]);
}
}
if (numFrames > 5000) {
mZoomLevel = 3;
} else if (numFrames > 1000) {
mZoomLevel = 2;
} else if (numFrames > 300) {
mZoomLevel = 1;
} else {
mZoomLevel = 0;
}
mInitialized = true;
}
public boolean canZoomIn() {
return (mZoomLevel > 0);
}
public void zoomIn() {
if (canZoomIn()) {
mZoomLevel--;
mSelectionStart *= 2;
mSelectionEnd *= 2;
mHeightsAtThisZoomLevel = null;
int offsetCenter = mOffset + getMeasuredWidth() / 2;
offsetCenter *= 2;
mOffset = offsetCenter - getMeasuredWidth() / 2;
if (mOffset < 0)
mOffset = 0;
invalidate();
}
}
public boolean canZoomOut() {
return (mZoomLevel < mNumZoomLevels - 1);
}
public void zoomOut() {
if (canZoomOut()) {
mZoomLevel++;
mSelectionStart /= 2;
mSelectionEnd /= 2;
int offsetCenter = mOffset + getMeasuredWidth() / 2;
offsetCenter /= 2;
mOffset = offsetCenter - getMeasuredWidth() / 2;
if (mOffset < 0)
mOffset = 0;
mHeightsAtThisZoomLevel = null;
invalidate();
}
}
public double pixelsToSeconds(int pixels) {
double z = mZoomFactorByZoomLevel[mZoomLevel];
return (pixels * (double)mSamplesPerFrame / (mSampleRate * z));
}
public void setListener(WaveformListener listener) {
mListener = listener;
}
public void recomputeHeights(float density) {
mHeightsAtThisZoomLevel = null;
mDensity = density;
mTimecodePaint.setTextSize((int)(12 * density));
invalidate();
}
protected void drawWaveformLine(Canvas canvas,
int x, int y0, int y1,
Paint paint) {
canvas.drawLine(x, y0, x, y1, paint);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mSoundFile == null)
return;
if (mHeightsAtThisZoomLevel == null)
computeIntsForThisZoomLevel();
DisplayMetrics displaymetrics = getContext().getResources().getDisplayMetrics();
int height = displaymetrics.heightPixels;
int widths = displaymetrics.widthPixels;
// Draw waveform
int measuredWidth = getMeasuredWidth();
int measuredHeight = getMeasuredHeight();
int start = mOffset;
int width = mHeightsAtThisZoomLevel.length - start;
int ctr = measuredHeight / 2;
Log.e("wid",String.valueOf(width));
Log.e("widCal",String.valueOf(mHeightsAtThisZoomLevel.length));
Log.e("widstart",String.valueOf(start));
if (width > measuredWidth)
width = measuredWidth;
Log.e("measured",String.valueOf(measuredWidth));
// Draw grid
double onePixelInSecs = pixelsToSeconds(1);
boolean onlyEveryFiveSecs = (onePixelInSecs > 1.0 / 50.0);
double fractionalSecs = mOffset * onePixelInSecs;
int integerSecs = (int) fractionalSecs;
int i = 0;
while (i < width) {
i++;
fractionalSecs += onePixelInSecs;
int integerSecsNew = (int) fractionalSecs;
if (integerSecsNew != integerSecs) {
integerSecs = integerSecsNew;
if (!onlyEveryFiveSecs || 0 == (integerSecs % 5)) {
canvas.drawLine(i, 0, i, measuredHeight, mGridPaint);
}
}
}
// Draw waveform
for ( i = 0; i < width; i++) {
Paint paint;
if (i + start >= mSelectionStart &&
i + start < mSelectionEnd) {
paint = mSelectedLinePaint;
// paint.setColor(color);
} else {
drawWaveformLine(canvas, ((widths/width)*i), 0, measuredHeight,
mUnselectedBkgndLinePaint);
paint = mUnselectedLinePaint;
}
drawWaveformLine(
canvas, ((widths/width)*i),
ctr - mHeightsAtThisZoomLevel[start + i],
ctr + 1 + mHeightsAtThisZoomLevel[start + i],
paint);
if (i + start == mPlaybackPos) {
canvas.drawLine(i, 0, i, measuredHeight, mPlaybackLinePaint);
}
}
if (mListener != null) {
mListener.waveformDraw();
}
}
private void computeIntsForThisZoomLevel() {
int halfHeight = (getMeasuredHeight() / 2) - 1;
mHeightsAtThisZoomLevel = new int[mLenByZoomLevel[mZoomLevel]];
for (int i = 0; i < mLenByZoomLevel[mZoomLevel]; i++) {
mHeightsAtThisZoomLevel[i] =
(int)(mValuesByZoomLevel[mZoomLevel][i] * halfHeight);
}
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity implements WaveformView.WaveformListener {
WaveformView mWaveformView;
SoundFile mSoundFile;
private float mDensity;
private File mFile;
private String mFilename;
private long mLoadingLastUpdateTime;
boolean mLoadingKeepGoing;
boolean mFinishActivity;
private ProgressDialog mProgressDialog;
String mTitle,mArtist;
private Thread mLoadSoundFileThread;
private Thread mRecordAudioThread;
private Thread mSaveSoundFileThread;
private boolean mIsPlaying;
private SamplePlayer mPlayer;
private String mInfoContent;
private int mWidth;
private int mMaxPos;
private int mStartPos;
private int mEndPos;
private boolean mStartVisible;
private boolean mEndVisible;
private int mLastDisplayedStartPos;
private int mLastDisplayedEndPos;
private int mOffset;
private int mOffsetGoal;
private int mFlingVelocity;
private int mPlayStartMsec;
private int mPlayEndMsec;
private Handler mHandler;
Button pla;
MediaPlayer mediaPlayer;
boolean ismIsPlaying;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pla = (Button)findViewById(R.id.play);
mWaveformView = (WaveformView)findViewById(R.id.waveform);
mWaveformView.setListener(this);
mHandler = new Handler();
Uri uri = Uri.parse("/sdcard/audio_file.mp3");
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(),uri);
loadGui();
loadFromFile();
}
/**
* Called from both onCreate and onConfigurationChanged
* (if the user switched layouts)
*/
private void loadGui() {
// Inflate our UI from its XML layout description.
setContentView(R.layout.activity_main);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mDensity = metrics.density;
mWaveformView = (WaveformView)findViewById(R.id.waveform);
mWaveformView.setListener(this);
if (mSoundFile != null && !mWaveformView.hasSoundFile()) {
mWaveformView.setSoundFile(mSoundFile);
mWaveformView.recomputeHeights(mDensity);
}
}
private void loadFromFile() {
mFilename = "/sdcard/audio_file.mp3";
mFile = new File(mFilename);
SongMetadataReader metadataReader = new SongMetadataReader(
this, mFilename);
mTitle = metadataReader.mTitle;
mArtist = metadataReader.mArtist;
String titleLabel = mTitle;
if (mArtist != null && mArtist.length() > 0) {
titleLabel += " - " + mArtist;
}
setTitle(titleLabel);
mLoadingLastUpdateTime = getCurrentTime();
mLoadingKeepGoing = true;
mFinishActivity = false;
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setTitle("Loading...");
mProgressDialog.setCancelable(true);
mProgressDialog.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
mLoadingKeepGoing = false;
mFinishActivity = true;
}
});
mProgressDialog.show();
final SoundFile.ProgressListener listener =
new SoundFile.ProgressListener() {
public boolean reportProgress(double fractionComplete) {
long now = getCurrentTime();
if (now - mLoadingLastUpdateTime > 100) {
mProgressDialog.setProgress(
(int) (mProgressDialog.getMax() * fractionComplete));
mLoadingLastUpdateTime = now;
}
return mLoadingKeepGoing;
}
};
// Load the sound file in a background thread
mLoadSoundFileThread = new Thread() {
public void run() {
try {
mSoundFile = SoundFile.create(mFile.getAbsolutePath(), listener);
if (mSoundFile == null) {
mProgressDialog.dismiss();
String name = mFile.getName().toLowerCase();
String[] components = name.split("\\.");
String err;
if (components.length < 2) {
err = getResources().getString(
R.string.no_extension_error);
} else {
err = getResources().getString(
R.string.bad_extension_error) + " " +
components[components.length - 1];
}
final String finalErr = err;
Runnable runnable = new Runnable() {
public void run() {
showFinalAlert(new Exception(), finalErr);
}
};
mHandler.post(runnable);
return;
}
mPlayer = new SamplePlayer(mSoundFile);
} catch (final Exception e) {
mProgressDialog.dismiss();
e.printStackTrace();
mInfoContent = e.toString();
runOnUiThread(new Runnable() {
public void run() {
}
});
Runnable runnable = new Runnable() {
public void run() {
showFinalAlert(e, getResources().getText(R.string.read_error));
}
};
mHandler.post(runnable);
return;
}
mProgressDialog.dismiss();
if (mLoadingKeepGoing) {
Runnable runnable = new Runnable() {
public void run() {
finishOpeningSoundFile();
}
};
mHandler.post(runnable);
} else if (mFinishActivity){
MainActivity.this.finish();
}
}
};
mLoadSoundFileThread.start();
}
private void finishOpeningSoundFile() {
mWaveformView.setSoundFile(mSoundFile);
mWaveformView.recomputeHeights(mDensity);
Log.e("sound file",mFilename);
Log.e("sound", String.valueOf(mSoundFile));
}
/**
* Show a "final" alert dialog that will exit the activity
* after the user clicks on the OK button. If an exception
* is passed, it's assumed to be an error condition, and the
* dialog is presented as an error, and the stack trace is
* logged. If there's no exception, it's a success message.
*/
private void showFinalAlert(Exception e, CharSequence message) {
CharSequence title;
if (e != null) {
Log.e("Ringdroid", "Error: " + message);
Log.e("Ringdroid", getStackTrace(e));
title = getResources().getText(R.string.alert_title_failure);
setResult(RESULT_CANCELED, new Intent());
} else {
Log.v("Ringdroid", "Success: " + message);
title = getResources().getText(R.string.alert_title_success);
}
new AlertDialog.Builder(MainActivity.this)
.setTitle(title)
.setMessage(message)
.setPositiveButton(
R.string.alert_ok_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
finish();
}
})
.setCancelable(false)
.show();
}
private void showFinalAlert(Exception e, int messageResourceId) {
showFinalAlert(e, getResources().getText(messageResourceId));
}
#Override
public void waveformTouchStart(float x) {
}
#Override
public void waveformTouchMove(float x) {
}
#Override
public void waveformTouchEnd() {
}
#Override
public void waveformFling(float x) {
}
#Override
public void waveformDraw() {
mWidth = mWaveformView.getMeasuredWidth();
if (mOffsetGoal != mOffset) {
// updateDisplay();
}
else if (mIsPlaying) {
// updateDisplay();
} else if (mFlingVelocity != 0) {
// updateDisplay();
}
}
private long getCurrentTime() {
return System.nanoTime() / 1000000;
}
private String getStackTrace(Exception e) {
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
return writer.toString();
}
public void buttonClick(View view) {
Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
mediaPlayer.start();
ismIsPlaying = true;
}
}
In your onDraw(Canvas canvas) add the following lines
if (i + start <= mPlaybackPos) {
Paint mPaint = new Paint(paint);
mPaint.setColor(Color.RED);
drawWaveformLine(
canvas, ((widths/width)*i),
ctr - mHeightsAtThisZoomLevel[start + i],
ctr + 1 + mHeightsAtThisZoomLevel[start + i],
mPaint);
}
add them above the line:
if (i + start == mPlaybackPos) {
And if this works, consider to allocate the Paint-object outside the onDraw() method.
I need to move circles along a circular path for that i am using Object Animator and Path evaluator.All the information is dynamic means it is changing when i receive response so that total number of circles can be changed at runtime.Here is the 1 part of method where all circles are positioning themselves according to their position on screen that is if user release the touch then this method gets called -:
public void slideDownSetToCenter() {
for (int i = 0; i < leftCurrentRunningAnimation.length; i++) {
Logger.i(TAG, "in slide down animation");
if (leftReadyToMove[i]) {
if (leftUpQueue.contains(i)) {
leftUpQueue.remove(i);
}
leftAngle = leftSlice * ++leftAllCirclesAngles[i];
Logger.i("circle leftAngle points of curve down", String.valueOf(leftAllCirclesAngles[i]));
if (leftAngle > leftAngleTop) {
if (i < leftCurrentRunningAnimation.length - 1) {
leftReadyToMove[i + 1] = true; // set next circle to
// move
}
}
Arrays.fill(leftCurrentRunningAnimation, false);
leftCurrentRunningAnimation[i] = true;
Logger.i(TAG, "leftAngle" + leftAngle);
if (leftReadyToMove[i] == true && leftAngle == leftAngleDownOut) {
leftReadyToMove[i] = false;
leftDownStack.add(i);
}
xPosition = (int) (leftCircleCenterX + leftCircleX * Math.cos(leftAngle));
yPosition = (int) (leftCircleCenterY + leftCircleY * Math.sin(leftAngle));
Path = new AnimatorPath();
Path.moveTo(xPosition, yPosition);
Path.lineTo(xPosition, yPosition);
while (true) {
if (leftAngle == leftAngleDownOut) {
break;
}
leftAngle = leftSlice * ++leftAllCirclesAngles[i];
xPosition = (int) (leftCircleCenterX + leftCircleX * Math.cos(leftAngle));
yPosition = (int) (leftCircleCenterY + leftCircleY * Math.sin(leftAngle));
Path.lineTo(xPosition, yPosition);
Logger.i(TAG, "path.........");
}
slideCircleAnimator = ObjectAnimator.ofObject(DynamicCircleSwipeAnimation.this, "leftButtonLocationDynamic", new PathEvaluator(), Path.getPoints().toArray());
slideCircleAnimator.setInterpolator(linearInterpolator);
slideCircleAnimator.setDuration(500);
context.runOnUiThread(new Runnable() {
#Override
public void run() {
slideCircleAnimator.start();
}
});
}
break;
}
}
Here is the Object animator's animation method -:
public void setLeftButtonLocationDynamic(final PathPoint newLoc) {
for (int i = 0; i < leftCurrentRunningAnimation.length; i++) {
if (leftCurrentRunningAnimation[i] == true) {
Logger.i("current button id", String.valueOf(i));
leftArrayOfButtons[i].setTranslationX(newLoc.mX);
leftArrayOfButtons[i].setTranslationY(newLoc.mY);
break;
}
}
}
Here my animation is not happening in correct way that' why i need to pass my view reference from Object.OfObject() method so that i can get it in setLeftButtonLocationDynamic(final PathPoint newLoc,View v).Is anyone has any idea how can i do this?I searched a lot and tried to develop custom class of ObjectAnimator,ValueAnimator and ProperyViewHolder classes but when i copied it from google open source then i get errors in that.Any help is appreciable?
Here to achieve this i changed the approach to move all circles.Previously, i was using ObjectAnimator to move circles one by one and now i am using Animator set for x position and y position.I play both animation together.
Here is the example -:
public void SlideDownFromRightAnimation() {
int rightArrayOfButtonsLength = rightArrayOfButtons.length;
Logger.i(TAG, "queue " + rightUpQueue.size() + "= stack " + rightDownStack.size());
if (rightUpQueue.size() == rtNumberOfButtons) {
Arrays.fill(rightReadyToMove, false);
rightReadyToMove[0] = true;
rightUpQueue.poll();
} else if (rightDownStack.size() == rtNumberOfButtons) {
rightUpQueue.clear();
for (int i = 0; i < rightArrayOfButtonsLength; i++) {
rightUpQueue.add(rightDownStack.pop());
rightAllCirclesAngles[i] = rightCircleUpOutPosition;
}
Arrays.fill(rightReadyToMove, false);
rightReadyToMove[0] = true;
}
for (int i = 0; i < rightArrayOfButtonsLength; i++) {
Logger.i(TAG, "in slide down animation");
if (rightReadyToMove[i]) {
if (rightUpQueue.contains(rightArrayOfButtons[i].getTag())) {
rightUpQueue.remove(i);
}
rightAngle = rightSlice * --rightAllCirclesAngles[i];
Logger.i("circle rightAngle points of curve down", String.valueOf(rightAllCirclesAngles[i]));
if (rightAngle <= rightAngleTop) {
if (i < rightArrayOfButtonsLength - 1) {
rightReadyToMove[i + 1] = true; // set next circle to
// move
}
}
Logger.i(TAG, "rightAngle" + rightAngle);
if (rightAngle <= rightAngleDownOut) {
rightReadyToMove[i] = false;
rightDownStack.add((Integer)rightArrayOfButtons[i].getTag());
rightAllCirclesAngles[i] = rightCircleDownOutPosition;
rightStartAnimation(rightAngle, null, i);
} else {
double rightAngleNext = rightSlice * rightAllCirclesAngles[i];
if (rightAngleNext <= rightAngleDownOut) {
rightReadyToMove[i] = false;
rightDownStack.add((Integer)rightArrayOfButtons[i].getTag());
}
rightStartAnimation(rightAngle, rightAngleNext, i);
}
}
}
}
and here is the right wheels animation function -:
public void rightStartAnimation(Double rightAngle, Double rightAngleNext, int bttnId) {
xPosition = (int) (rightCircleCenterX + rightCircleX * Math.cos(rightAngle));
yPosition = (int) (rightCircleCenterY + rightCircleY * Math.sin(rightAngle));
if (rightAngleNext != null) {
xPosition = (int) (rightCircleCenterX + rightCircleX * Math.cos(rightAngleNext));
yPosition = (int) (rightCircleCenterY + rightCircleY * Math.sin(rightAngleNext));
}
final ObjectAnimator animation1 = ObjectAnimator.ofFloat(rightArrayOfButtons[bttnId], "x", rightArrayOfButtons[bttnId].getX(), xPosition);
animation1.setDuration(0);
animation1.setInterpolator(linearInterpolator);
final ObjectAnimator animation2 = ObjectAnimator.ofFloat(rightArrayOfButtons[bttnId], "y", rightArrayOfButtons[bttnId].getY(), yPosition);
animation2.setDuration(0);
animation2.setInterpolator(linearInterpolator);
final AnimatorSet set = new AnimatorSet();
set.setInterpolator(linearInterpolator);
context.runOnUiThread(new Runnable() {
#Override
public void run() {
set.playTogether(animation1, animation2);
set.start();
}
});
}
class is RadarSceen then method ontouch method is crash is null pointer exception and this method use start radar and stop radar.then localRotateAnimation.setDuration(3000L) crash is null pointer exception
public class RadarScreen extends Activity implements View.OnTouchListener {
private static final String APP_TAG = "com.example.ghostsam";
private CountDownTimer countdownHideGhost = null;
private CountDownTimer countdownShowGhost = null;
private DisplayMetrics getDisplay = new DisplayMetrics();
private int getDisplayHeight;
private float getDisplayScale;
private int getDisplayWidth;
private Boolean hideGhosts = Boolean.valueOf(false);
private ImageView ivLogo = null;
private ImageView ivRadar = null;
private ImageView ivRadarGhosts = null;
private ImageView ivSignalButton = null;
private Typeface layoutFontFace;
private Boolean radarRun = Boolean.valueOf(false);
// private RotateAnimation rotateAnimation ;
private RotateAnimation localRotateAnimation;
private boolean settingsGeneralVibrate = true;
private Boolean showGhosts = Boolean.valueOf(false);
private int showGhostsZufallszahl = 0;
private Vibrator vib = null;
public Bitmap drawButton(String paramString1, String paramString2) {
Bitmap localBitmap = Bitmap
.createBitmap(this.getDisplayWidth - (int) (70.0F * this.getDisplayScale),
(int) (52.0F * this.getDisplayScale), Bitmap.Config.ARGB_8888);
Canvas localCanvas = new Canvas(localBitmap);
Paint localPaint = new Paint();
localPaint.setTypeface(this.layoutFontFace);
localPaint.setTextAlign(Paint.Align.CENTER);
localPaint.setAntiAlias(true);
localPaint.setColor(Color.parseColor(paramString2));
localCanvas.drawRoundRect(
new RectF(0.0F, 0.0F, localBitmap.getWidth(), localBitmap.getHeight()), 12.0F,
12.0F, localPaint);
localPaint.setColor(Color.parseColor("#000000"));
localCanvas.drawRoundRect(new RectF(2.0F, 2.0F, -2 + localBitmap.getWidth(),
-2 + localBitmap.getHeight()), 12.0F, 12.0F, localPaint);
localPaint.setColor(Color.parseColor(paramString2));
localPaint.setAlpha(200);
localPaint.setTextSize(32.0F * this.getDisplayScale);
localPaint.setTextScaleX(1.75F);
localPaint.setFakeBoldText(true);
localCanvas.drawText(paramString1, localBitmap.getWidth() / 2,
36.0F * this.getDisplayScale, localPaint);
return localBitmap;
}
public Bitmap drawRadar(Boolean paramBoolean) {
Bitmap localBitmap = Bitmap
.createBitmap(-50 + this.getDisplayWidth, -50 + this.getDisplayWidth,
Bitmap.Config.ARGB_8888);
Canvas localCanvas = new Canvas(localBitmap);
Paint localPaint = new Paint();
int i = (int) ((localBitmap.getWidth() - 10.0F * this.getDisplayScale) / 2.0F
+ 5.0F * this.getDisplayScale);
int j = (int) (i - 5.0F * this.getDisplayScale);
localPaint.setAntiAlias(true);
localPaint.setColor(Color.parseColor("#FFFFFF"));
localPaint.setStyle(Paint.Style.STROKE);
localPaint.setStrokeWidth(3.0F * this.getDisplayScale);
localPaint.setAlpha(75);
for (int k = 0; ; k++) {
if (k > 4) {
localPaint.setAlpha(100);
localPaint.setStyle(Paint.Style.FILL);
localPaint.setShader(new SweepGradient(i, i, 0, -16711936));
if (paramBoolean.booleanValue()) {
RectF localRectF = new RectF();
localRectF.set(i - j, i - j, i + j, i + j);
localCanvas.drawArc(localRectF, 0.0F, 360.0F, true, localPaint);
}
localPaint.setShader(null);
localPaint.setAlpha(255);
localPaint.setColor(Color.parseColor("#810003"));
localPaint.setStyle(Paint.Style.FILL);
localPaint.setStrokeWidth(0.0F);
localCanvas.drawCircle(i, i, 10.0F * this.getDisplayScale, localPaint);
return localBitmap;
}
localCanvas.drawCircle(i, i, j - k * 40 * this.getDisplayScale, localPaint);
}
}
public Bitmap drawRadarGhosts(Boolean paramBoolean) {
Bitmap localBitmap = Bitmap
.createBitmap(-50 + this.getDisplayWidth, -50 + this.getDisplayWidth,
Bitmap.Config.ARGB_8888);
Canvas localCanvas = new Canvas(localBitmap);
Paint localPaint = new Paint();
if (paramBoolean.booleanValue()) {
int i = (int) ((localBitmap.getWidth() - 10.0F * this.getDisplayScale) / 2.0F
+ 5.0F * this.getDisplayScale);
int j = (int) (i - 5.0F * this.getDisplayScale);
localPaint.setAntiAlias(true);
localPaint.setAlpha(255);
Random localRandom = new Random();
localPaint.setAlpha(150);
int k = localRandom.nextInt(180);
int m = localRandom.nextInt(j);
int n = i + (int) (Math.cos(3.141592653589793D * k / 180.0D) * m);
int i1 = i + (int) (Math.sin(3.141592653589793D * k / 180.0D) * m);
localPaint.setColor(-16711936);
localPaint.setShader(
new RadialGradient(n, i1, 22.0F * this.getDisplayScale, -16711936, 0,
TileMode.CLAMP));
localCanvas.drawCircle(n, i1, 15.0F * this.getDisplayScale, localPaint);
if (localRandom.nextInt(50) < 5) {
int i6 = localRandom.nextInt(180);
int i7 = localRandom.nextInt(j);
int i8 = i + (int) (Math.cos(3.141592653589793D * i6 / 180.0D) * i7);
int i9 = i + (int) (Math.sin(3.141592653589793D * i6 / 180.0D) * i7);
localPaint.setShader(
new RadialGradient(i8, i9, 22.0F * this.getDisplayScale, -16711936, 0,
TileMode.CLAMP));
localCanvas.drawCircle(i8, i9, 15.0F * this.getDisplayScale, localPaint);
}
if (localRandom.nextInt(75) < 5) {
int i2 = localRandom.nextInt(180);
int i3 = localRandom.nextInt(j);
int i4 = i + (int) (Math.cos(3.141592653589793D * i2 / 180.0D) * i3);
int i5 = i + (int) (Math.sin(3.141592653589793D * i2 / 180.0D) * i3);
localPaint.setShader(
new RadialGradient(i4, i5, 22.0F * this.getDisplayScale, -16711936, 0,
TileMode.CLAMP));
localCanvas.drawCircle(i4, i5, 15.0F * this.getDisplayScale, localPaint);
}
}
return localBitmap;
}
public void onCreate(Bundle paramBundle) {
Log.i("com.example.ghostsam", "onStart RadarScreen");
requestWindowFeature(1);
getWindow().setFlags(1024, 1024);
super.onCreate(paramBundle);
setContentView(R.layout.radarscreen);
SharedPreferences localSharedPreferences = getSharedPreferences("app_prefs", 0);
int i = localSharedPreferences.getInt("appStartCounter", 0);
int j = localSharedPreferences.getInt("appStartFirst", 0);
int k = i + 1;
SharedPreferences.Editor localEditor = localSharedPreferences.edit();
localEditor.putInt("appStartCounter", k);
if (j <= 0) {
localEditor.putInt("appStartFirst", (int) (System.currentTimeMillis() / 1000L));
}
localEditor.commit();
if ((k == 5) || (k == 10) || (k == 25)) {
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
localBuilder.setIcon(17301543);
Resources localResources1 = getResources();
Object[] arrayOfObject1 = new Object[1];
arrayOfObject1[0] = "name";
localBuilder.setTitle(localResources1.getString(R.string.app_name, arrayOfObject1));
Resources localResources2 = getResources();
Object[] arrayOfObject2 = new Object[1];
arrayOfObject2[0] = "name";
localBuilder.setMessage(localResources2
.getString(R.string.dialog_ratemarket_question, arrayOfObject2));
Resources localResources3 = getResources();
Object[] arrayOfObject3 = new Object[1];
arrayOfObject3[0] = "name";
localBuilder.setPositiveButton(
localResources3.getString(R.string.dialog_button_yes, arrayOfObject3),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface paramDialogInterface,
int paramInt) {
Resources localResources = RadarScreen.this.getResources();
Object[] arrayOfObject = new Object[1];
arrayOfObject[0] = "name";
Intent localIntent = new Intent("android.intent.action.VIEW",
Uri.parse(localResources.getString(R.string.app_marketlink,
arrayOfObject)));
RadarScreen.this.startActivity(localIntent);
paramDialogInterface.dismiss();
}
});
Resources localResources4 = getResources();
Object[] arrayOfObject4 = new Object[1];
arrayOfObject4[0] = "name";
localBuilder.setNegativeButton(
localResources4.getString(R.string.dialog_button_no, arrayOfObject4),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface paramDialogInterface,
int paramInt) {
paramDialogInterface.dismiss();
}
});
localBuilder.create().show();
}
}
public boolean onCreateOptionsMenu(Menu paramMenu) {
getMenuInflater().inflate(R.menu.radarscreen, paramMenu);
return true;
}
public void onError(Exception paramException) {
}
public void onIllegalHttpStatusCode(int paramInt, String paramString) {
}
public boolean onKeyDown(int paramInt, KeyEvent paramKeyEvent) {
if (paramInt == 4) {
quitApp();
}
for (int i = 1; ; i = 0) {
return true;
}
}
#SuppressLint("NewApi")
public boolean onOptionsItemSelected(MenuItem paramMenuItem) {
switch (paramMenuItem.getItemId()) {
default:
break;
case R.id.radarscreen_menu_moreapps:
Resources localResources2 = getResources();
Object[] arrayOfObject2 = new Object[1];
arrayOfObject2[0] = "name";
startActivity(new Intent("android.intent.action.VIEW", Uri.parse(localResources2
.getString(R.string.app_marketdeveloperlink, arrayOfObject2))));
break;
case R.id.radarscreen_menu_rateapp:
Resources localResources1 = getResources();
Object[] arrayOfObject1 = new Object[1];
arrayOfObject1[0] = "name";
startActivity(new Intent("android.intent.action.VIEW", Uri.parse(
localResources1.getString(R.string.app_marketlink, arrayOfObject1))));
break;
case R.id.radarscreen_menu_about:
startActivity(new Intent(this, About.class));
break;
case R.id.radarscreen_menu_settings:
startActivity(new Intent(this, Settings.class));
break;
case R.id.radarscreen_menu_quit:
quitApp();
}
return true;
}
public void onResume() {
super.onResume();
Log.i("com.example.ghostsam", "onResume RadarScreen");
getWindowManager().getDefaultDisplay().getMetrics(this.getDisplay);
this.getDisplayWidth = this.getDisplay.widthPixels;
this.getDisplayHeight = this.getDisplay.heightPixels;
this.getDisplayScale = (this.getDisplayWidth / 480.0F);
this.layoutFontFace = Typeface.createFromAsset(getAssets(), "Roboto-Regular.ttf");
this.settingsGeneralVibrate = PreferenceManager
.getDefaultSharedPreferences(getBaseContext())
.getBoolean("settings_general_vibrate", true);
this.vib = ((Vibrator) getSystemService("vibrator"));
this.ivLogo = ((ImageView) findViewById(R.id.ivLogo));
this.ivLogo.setImageBitmap(Bitmap.createScaledBitmap(
BitmapFactory.decodeResource(getResources(), R.drawable.logo),
(int) (460.0F * this.getDisplayScale), (int) (68.0F * this.getDisplayScale),
true));
this.ivSignalButton = ((ImageView) findViewById(R.id.ivSignalButton));
this.ivSignalButton.setImageBitmap(drawButton("start radar", "#005F21"));
this.ivSignalButton.setOnTouchListener(this);
this.ivRadar = ((ImageView) findViewById(R.id.ivRadar));
this.ivRadar.setImageBitmap(drawRadar(Boolean.valueOf(false)));
this.ivRadarGhosts = ((ImageView) findViewById(R.id.ivRadarGhosts));
if (this.ivRadarGhosts != null) {
this.ivRadarGhosts.setImageBitmap(drawRadarGhosts(Boolean.valueOf(false)));
}
this.countdownShowGhost = new CountDownTimer(15000L, 1000L) {
public void onFinish() {
RadarScreen.this.showGhosts = Boolean.valueOf(false);
RadarScreen.this.hideGhosts = Boolean.valueOf(false);
if (RadarScreen.this.countdownHideGhost != null) {
RadarScreen.this.countdownHideGhost.start();
}
}
public void onTick(long paramLong) {
Random localRandom = new Random();
if (!RadarScreen.this.showGhosts.booleanValue()) {
RadarScreen.this.showGhosts = Boolean.valueOf(true);
RadarScreen.this.showGhostsZufallszahl = (1000 + localRandom
.nextInt(10000));
if (localRandom.nextInt(50) >= 10) {
AlphaAnimation localAlphaAnimation2 = new AlphaAnimation(0.0F, 0.975F);
localAlphaAnimation2.setDuration(1000L);
localAlphaAnimation2.setFillAfter(true);
if (RadarScreen.this.ivRadarGhosts != null) {
RadarScreen.this.ivRadarGhosts.startAnimation(localAlphaAnimation2);
RadarScreen.this.ivRadarGhosts.setImageBitmap(
RadarScreen.this.drawRadarGhosts(Boolean.valueOf(true)));
if (RadarScreen.this.settingsGeneralVibrate) {
RadarScreen.this.vib.vibrate(20L);
}
}
}
}
if ((RadarScreen.this.showGhostsZufallszahl > paramLong) && (!RadarScreen.this
.hideGhosts.booleanValue())) {
RadarScreen.this.hideGhosts = Boolean.valueOf(true);
AlphaAnimation localAlphaAnimation1 = new AlphaAnimation(0.975F, 0.0F);
localAlphaAnimation1.setDuration(1000L);
localAlphaAnimation1.setFillAfter(true);
if (RadarScreen.this.ivRadarGhosts == null) {
return;
}
RadarScreen.this.ivRadarGhosts.startAnimation(localAlphaAnimation1);
}
}
};
this.countdownHideGhost = new CountDownTimer(12500L, 2250L) {
public void onFinish() {
RadarScreen.this.showGhosts = Boolean.valueOf(false);
RadarScreen.this.hideGhosts = Boolean.valueOf(false);
if (RadarScreen.this.countdownShowGhost != null) {
RadarScreen.this.countdownShowGhost.start();
}
}
public void onTick(long paramLong) {
}
};
}
public void onStop() {
super.onStop();
Log.i("com.example.ghostsam", "onStop RadarScreen");
BitmapDrawable localBitmapDrawable1 = (BitmapDrawable) this.ivLogo.getDrawable();
this.ivLogo.setImageBitmap(null);
this.ivLogo.setImageDrawable(null);
this.ivLogo = null;
Bitmap localBitmap1 = localBitmapDrawable1.getBitmap();
if ((localBitmap1 != null) && (!localBitmap1.isRecycled()))
{
localBitmap1.recycle();
}
BitmapDrawable localBitmapDrawable2 = (BitmapDrawable) this.ivRadar.getDrawable();
this.ivRadar.setImageBitmap(null);
this.ivRadar.setImageDrawable(null);
this.ivRadar = null;
Bitmap localBitmap2 = localBitmapDrawable2.getBitmap();
if ((localBitmap2 != null) && (!localBitmap2.isRecycled()))
{
localBitmap2.recycle();
}
BitmapDrawable localBitmapDrawable3 = (BitmapDrawable) this.ivRadarGhosts.getDrawable();
this.ivRadarGhosts.setImageBitmap(null);
this.ivRadarGhosts.setImageDrawable(null);
this.ivRadarGhosts = null;
Bitmap localBitmap3 = localBitmapDrawable3.getBitmap();
if ((localBitmap3 != null) && (!localBitmap3.isRecycled()))
{
localBitmap3.recycle();
}
BitmapDrawable localBitmapDrawable4 = (BitmapDrawable) this.ivSignalButton
.getDrawable();
this.ivSignalButton.setImageBitmap(null);
this.ivSignalButton.setImageDrawable(null);
this.ivSignalButton = null;
Bitmap localBitmap4 = localBitmapDrawable4.getBitmap();
if ((localBitmap4 != null) && (!localBitmap4.isRecycled()))
{
localBitmap4.recycle();
}
this.countdownHideGhost.cancel();
this.countdownHideGhost = null;
this.countdownShowGhost.cancel();
this.countdownShowGhost = null;
this.radarRun = Boolean.valueOf(false);
this.showGhosts = Boolean.valueOf(false);
this.hideGhosts = Boolean.valueOf(false);
}
public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
switch (paramMotionEvent.getAction()) {
default:
if (paramView != this.ivSignalButton) {
break;
}
case 0:
if (this.radarRun.booleanValue()) {
if (this.radarRun.booleanValue()) {
if (this.ivSignalButton == null) {
break;
}
this.ivSignalButton.setImageBitmap(drawButton("stop radar", "#1BA449"));
}
}
case 1:
if (this.ivSignalButton == null) {
break;
}
this.ivSignalButton.setImageBitmap(drawButton("start radar", "#1BA449"));
}
// while (paramView != this.ivSignalButton);
if (this.radarRun.booleanValue()) {
if (this.ivSignalButton != null) {
this.ivSignalButton.setImageBitmap(drawButton("stop radar", "#005F21"));
}
if ((paramMotionEvent.getX() <= 0.0F) || (paramMotionEvent.getX() >= paramView
.getWidth()) ||
(paramMotionEvent.getY() <= 0.0F) || (paramMotionEvent.getY() >= paramView
.getHeight())) {
this.ivSignalButton.setImageBitmap(drawButton("stop radar", "#005F21"));
}
if (this.ivSignalButton != null) {
this.ivSignalButton.setImageBitmap(drawButton("start radar", "#005F21"));
}
RotateAnimation localRotateAnimation = new RotateAnimation(0.0F, 360.0F, 1, 0.5F, 1,
0.5F);
localRotateAnimation.setInterpolator(new LinearInterpolator());
localRotateAnimation.setFillAfter(true);
localRotateAnimation.setRepeatMode(1);
if (!this.radarRun.booleanValue()) {
if (this.ivSignalButton != null) {
this.ivSignalButton.setImageBitmap(drawButton("stop radar", "#005F21"));
}
}
this.radarRun = Boolean.valueOf(true);
this.radarRun = Boolean.valueOf(false);
if (this.ivRadar != null) {
this.ivRadar.setImageBitmap(drawRadar(Boolean.valueOf(false)));
}
localRotateAnimation.setDuration(10L);
localRotateAnimation.setRepeatCount(0);
if (this.ivRadarGhosts != null) {
this.ivRadarGhosts.setImageBitmap(drawRadarGhosts(Boolean.valueOf(false)));
}
if (this.countdownHideGhost != null) {
this.countdownHideGhost.cancel();
}
if (this.countdownHideGhost != null) {
this.countdownShowGhost.cancel();
}
}
if (this.ivSignalButton == null) {
this.ivSignalButton.setImageBitmap(drawButton("start radar", "#005F21"));
}
if (this.ivRadar != null) {
this.ivRadar.setImageBitmap(drawRadar(Boolean.valueOf(true)));
}
localRotateAnimation.setDuration(3000L);
localRotateAnimation.setRepeatCount(-1);
if (this.countdownHideGhost == null) {
this.countdownHideGhost.start();
}
this.ivRadar.startAnimation(localRotateAnimation);
return true;
}
}
You have to problems here:
You defined a filed RotateAnimation localRotateAnimation but never assigned a value to it. That's why you get a NullPointerException.
You are using a local variable with the same name and assign it a value: RotateAnimation localRotateAnimation = new RotateAnimation(0.0F, 360.0F, 1, 0.5F, 1, 0.5F);. Most likly, you wanted to use the filed. So change that to just localRotateAnimation = new RotateAnimation(/*params*/);
I'm not sure if fixing 2. fixes 1. because I did not understand your logic. Maybe 2. gets called every time before you reach the code which throws the NPE now.
Maybe you need to assign a value somewhere else to.
Maybe this code block is what you want:
// moved up to run it even if condition is false
// and use field
localRotateAnimation = new RotateAnimation(0.0F, 360.0F, 1, 0.5F, 1, 0.5F);
if (this.radarRun.booleanValue()) {
if (this.ivSignalButton != null) {
this.ivSignalButton.setImageBitmap(drawButton("stop radar", "#005F21"));
}
if ((paramMotionEvent.getX() <= 0.0F) || (paramMotionEvent.getX() >= paramView
.getWidth()) ||
(paramMotionEvent.getY() <= 0.0F) || (paramMotionEvent.getY() >= paramView
.getHeight())) {
this.ivSignalButton.setImageBitmap(drawButton("stop radar", "#005F21"));
}
if (this.ivSignalButton != null) {
this.ivSignalButton.setImageBitmap(drawButton("start radar", "#005F21"));
}
localRotateAnimation.setInterpolator(new LinearInterpolator());
localRotateAnimation.setFillAfter(true);
localRotateAnimation.setRepeatMode(1);
if (!this.radarRun.booleanValue()) {
if (this.ivSignalButton != null) {
this.ivSignalButton.setImageBitmap(drawButton("stop radar", "#005F21"));
}
}
this.radarRun = Boolean.valueOf(true);
this.radarRun = Boolean.valueOf(false);
if (this.ivRadar != null) {
this.ivRadar.setImageBitmap(drawRadar(Boolean.valueOf(false)));
}
localRotateAnimation.setDuration(10L);
localRotateAnimation.setRepeatCount(0);
if (this.ivRadarGhosts != null) {
this.ivRadarGhosts.setImageBitmap(drawRadarGhosts(Boolean.valueOf(false)));
}
if (this.countdownHideGhost != null) {
this.countdownHideGhost.cancel();
}
if (this.countdownHideGhost != null) {
this.countdownShowGhost.cancel();
}
}
if (this.ivSignalButton == null) {
this.ivSignalButton.setImageBitmap(drawButton("start radar", "#005F21"));
}
if (this.ivRadar != null) {
this.ivRadar.setImageBitmap(drawRadar(Boolean.valueOf(true)));
}
localRotateAnimation.setDuration(3000L);
localRotateAnimation.setRepeatCount(-1);
if (this.countdownHideGhost == null) {
this.countdownHideGhost.start();
}
this.ivRadar.startAnimation(localRotateAnimation);