Flappy Bird Game I am getting error while adding pipe - java

I have a problem. I'm working for a flappy bird game.
I added the bird, tested it and there is no problem.
but when I test when adding pipes, I encounter such an error.
It gives an error on line 76. I could not solve this error.
Since my Java coding is not very good, I searched a lot for the error but couldn't find it. That's why I felt the need to open a topic here. I would be very happy if those who have knowledge can review and give information about the problem.
GameView.java
package com.woxiapps.hopbird;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.logging.LogRecord;
public class GameView extends View {
private Bird bird;
private android.os.Handler handler;
private Runnable r;
private ArrayList<Pipe> arrPipes;
private int sumpipe, distance;
public GameView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
initBird();
initPipe();
handler = new Handler();
r = new Runnable() {
#Override
public void run() {
invalidate();
}
};
}
private void initPipe() {
sumpipe = 6;
distance = 300*Constants.SCREEN_HEIGHT/1920;
arrPipes = new ArrayList<>();
for (int i = 0; i < sumpipe/2; i++){
if (i < sumpipe/2) {
this.arrPipes.add(new Pipe(Constants.SCREEN_WIDTH+i*((Constants.SCREEN_WIDTH+200*Constants.SCREEN_WIDTH/1080)/(sumpipe/2)),
0,200*Constants.SCREEN_WIDTH/1080, Constants.SCREEN_WIDTH/2));
this.arrPipes.get(this.arrPipes.size()-1).setBm(BitmapFactory.decodeResource(this.getResources(),R.drawable.pipe2));
this.arrPipes.get(this.arrPipes.size()-1).randomY();
}else {
this.arrPipes.add(new Pipe(this.arrPipes.get(i-sumpipe/2).getX(),this.arrPipes.get(i-sumpipe/2).getY()
+this.arrPipes.get(i-sumpipe/2).getHeight() + this.distance, 200*Constants.SCREEN_WIDTH/1080, Constants.SCREEN_HEIGHT/2));
this.arrPipes.get(this.arrPipes.size()-1).setBm(BitmapFactory.decodeResource(this.getResources(), R.drawable.pipe1));
}
}
}
private void initBird() {
bird = new Bird();
bird.setWidth(100*Constants.SCREEN_WIDTH/1080);
bird.setHeight(100*Constants.SCREEN_HEIGHT/1920);
bird.setX(100*Constants.SCREEN_WIDTH/1080);
bird.setY(Constants.SCREEN_HEIGHT/2-bird.getHeight()/2);
ArrayList<Bitmap> ArrBms = new ArrayList<>();
ArrBms.add(BitmapFactory.decodeResource(this.getResources(),R.drawable.bird1));
ArrBms.add(BitmapFactory.decodeResource(this.getResources(),R.drawable.bird2));
bird.setArrBms(ArrBms);
}
public void draw(Canvas canvas){
super.draw(canvas);
bird.draw(canvas);
for (int i = 0; i < sumpipe; i++) {
if (this.arrPipes.get(i).getX() < -arrPipes.get(i).getWidth()){
this.arrPipes.get(i).setX(Constants.SCREEN_WIDTH);
if(i < sumpipe/2){
arrPipes.get(i).randomY();
}else {
arrPipes.get(i).setY(this.arrPipes.get(i-sumpipe/2).getY()
+this.arrPipes.get(i-sumpipe/2).getHeight() + this.distance);
}
}
this.arrPipes.get(i).draw(canvas);
}
handler.postDelayed(r, 10);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
bird.setDrop(-15);
}
return true;
}
}
enter image description here

Related

Java Android Studio game randomly ends when conditions are not met

I am trying to create a game in Android Studio that is similar to flappy bird. I'm following a YouTube tutorial as I am new to java and i believe I've followed it very closely.
My problem is that sometimes the game will terminate early, despite the gameOver conditions not being met. I have a function "updateAndDrawTubes" that draws the pipes to the canvas and also checks whether the player is touching the pipes. When the player does touch the pipe, the game finishes and goes to the gameOver screen, displaying the score. However, I am finding that even if there is no collision, sometimes the game will finish and go to the gameOver screen early.
My code is a mess, so apologies for that but any help would really be appreciated as I've exhausted all other options.
GameEngine.java
package com.example.mymainuniproj;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import java.util.ArrayList;
import java.util.Random;
public class GameEngine {
BackgroundImage backgroundImage;
Player player;
static int gameState;
ArrayList<Tube> tubes;
Random random;
int score;
int scoringTube;
Paint scorePaint;
public GameEngine() {
backgroundImage = new BackgroundImage();
player = new Player();
//0-not started, 1-playing, 2-gameover
gameState = 0;
tubes = new ArrayList<>();
random = new Random();
for (int i = 0; i < AppConstants.numberOfTubes; i++) {
int tubeX = AppConstants.SCREEN_WIDTH + i * AppConstants.distanceBetweenTubes;
int topTubeOffsetY = AppConstants.minTubeOffsetY + random.nextInt(AppConstants.maxTubeOffsetY - AppConstants.minTubeOffsetY + 1);
Tube tube = new Tube(tubeX, topTubeOffsetY);
tubes.add(tube);
}
score = 0;
scoringTube = 0;
scorePaint = new Paint();
scorePaint.setColor(Color.RED);
scorePaint.setTextSize(100);
scorePaint.setTextAlign(Paint.Align.LEFT);
}
// this function is responsible for telling coins and enemies where to spawn
public void updateAndDrawTubes(Canvas canvas) {
if (gameState == 1) {
if ((tubes.get(scoringTube).getTubeX() < player.getPlayerX() + AppConstants.getBitmapBank().getPlayerWidth())
//if current tubes X value is < player X value
&& (tubes.get(scoringTube).getTopTubeOffsetY() > player.getPlayerY())
|| (tubes.get(scoringTube).getBottomTubeY() < (player.getPlayerY() + AppConstants.getBitmapBank().getPlayerHeight()))) {
//game over
gameState = 2;
Context context = AppConstants.gameActivityContext;
Intent intent = new Intent(context, GameOver.class);
intent.putExtra("score",score);
context.startActivity(intent);
((Activity)context).finish();
} else if (tubes.get(scoringTube).getTubeX() < player.getPlayerX() - AppConstants.getBitmapBank().getTubeWidth()) {
score++;
scoringTube++;
if (scoringTube > AppConstants.numberOfTubes - 1) {
scoringTube = 0;
}
}
// repeats twice, once for the enemy, once for the coin at each X coord
for (int i = 0; i < AppConstants.numberOfTubes; i++) {
//if tube(x) in the array's X value is less than tube width (which is 90px)
if (tubes.get(i).getTubeX() < -AppConstants.getBitmapBank().getTubeWidth()) {
tubes.get(i).setTubeX(tubes.get(i).getTubeX() + AppConstants.numberOfTubes * AppConstants.distanceBetweenTubes);
int topTubeOffsetY = AppConstants.minTubeOffsetY + random.nextInt(AppConstants.maxTubeOffsetY - AppConstants.minTubeOffsetY + 1);
tubes.get(i).setTopTubeOffsetY(topTubeOffsetY);
}
tubes.get(i).setTubeX(tubes.get(i).getTubeX() - AppConstants.tubeVelocity);
canvas.drawBitmap(AppConstants.getBitmapBank().getTubeTop(), tubes.get(i).getTubeX(), tubes.get(i).getTopTubeY(), null);
canvas.drawBitmap(AppConstants.getBitmapBank().getTubeBottom(), tubes.get(i).getTubeX(), tubes.get(i).getBottomTubeY(), null);
}
canvas.drawText("Score: " + score, 0, 110, scorePaint);
}
}
public void updateAndDrawBackgroundImage(Canvas canvas) {
backgroundImage.setX(backgroundImage.getX() - backgroundImage.getVelocity());
if (backgroundImage.getX() < -AppConstants.getBitmapBank().getBackgroundWidth()) {
backgroundImage.setX(0);
}
canvas.drawBitmap(AppConstants.getBitmapBank().getBackground(), backgroundImage.getX(), backgroundImage.getY(), null);
if (backgroundImage.getX() < -(AppConstants.getBitmapBank().getBackgroundWidth() - AppConstants.SCREEN_WIDTH)) {
canvas.drawBitmap(AppConstants.getBitmapBank().getBackground(), backgroundImage.getX() + AppConstants.getBitmapBank().getBackgroundWidth(), backgroundImage.getY(), null);
}
}
public void updateAndDrawPlayer(Canvas canvas) {
if (gameState == 1) {
if (player.getPlayerY() < (AppConstants.SCREEN_HEIGHT - AppConstants.getBitmapBank().getPlayerHeight()) || player.getVelocity() < 0) {
player.setVelocity(player.getVelocity() + AppConstants.gravity);
player.setPlayerY(player.getPlayerY() + player.getVelocity());
}
}
int currentFrame = player.getCurrentFrame();
canvas.drawBitmap(AppConstants.getBitmapBank().getPlayer(currentFrame), player.getPlayerX(), player.getPlayerY(), null);
currentFrame++;
if (currentFrame > player.maxFrame) {
currentFrame = 0;
}
player.setCurrentFrame(currentFrame);
}
}
GameOver.java
package com.example.mymainuniproj;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class GameOver extends AppCompatActivity {
TextView tvScore, tvPersonalBest;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_over);
int score = getIntent().getExtras().getInt("score");
SharedPreferences pref = getSharedPreferences("MyPref",0);
int scoreSP = pref.getInt("scoreSP",0);
SharedPreferences.Editor editor = pref.edit();
//update high score
if(score > scoreSP){
scoreSP = score;
editor.putInt("scoreSP",scoreSP);
editor.commit();
}
tvScore = findViewById(R.id.tvScore);
//tvPersonalBest = findViewById(R.id.tvPersonalScore);
tvScore.setText(""+score);
//tvPersonalBest.setText(""+scoreSP);*/
}
public void showToastOnClick(View view){
String text = "";
switch (view.getId()){
case R.id.buttonRestart: restart(); break;
}
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
public void restart(){
Intent intent = new Intent(GameOver.this , GameActivity.class);
startActivity(intent);
finish();
}
public void exit(View view){
finish();
}
}
AppConstants.java
package com.example.mymainuniproj;
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;
public class AppConstants {
static BitmapBank bitmapBank; //bitmap object ref
static GameEngine gameEngine; //game engine object ref
static int SCREEN_WIDTH, SCREEN_HEIGHT;
static int gravity;
static int VELOCITY_WHEN_JUMPED;
static int gapBetweenTopAndBottomTubes;
static int numberOfTubes;
static int tubeVelocity;
static int minTubeOffsetY;
static int maxTubeOffsetY;
static int distanceBetweenTubes;
static Context gameActivityContext;
public static void initialization(Context context){
setScreenSize(context);
bitmapBank = new BitmapBank(context.getResources() );
setGameConstants();
gameEngine = new GameEngine();
}
public static void setGameConstants(){
AppConstants.gravity = 3;
AppConstants.VELOCITY_WHEN_JUMPED = -40;
gapBetweenTopAndBottomTubes = 800;
AppConstants.numberOfTubes = 2;
AppConstants.tubeVelocity = 12;
AppConstants.minTubeOffsetY = (int)(AppConstants.gapBetweenTopAndBottomTubes / 2.0);
AppConstants.maxTubeOffsetY = AppConstants.SCREEN_HEIGHT - AppConstants.minTubeOffsetY - AppConstants.gapBetweenTopAndBottomTubes;
AppConstants.distanceBetweenTubes = AppConstants.SCREEN_WIDTH * 3 / 4;
}
//return bitmapBank instance
public static BitmapBank getBitmapBank(){
return bitmapBank;
}
//return gameEngine instance
public static GameEngine getGameEngine(){
return gameEngine;
}
// get screen height and widtch
private static void setScreenSize(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
int width = metrics.widthPixels;
int height = metrics.heightPixels;
AppConstants.SCREEN_WIDTH = width;
AppConstants.SCREEN_HEIGHT = height;
}
}
This is my first time posting anywhere like this so please go easy on me if the format is bad or if I'm missing anything important!
If there is any other parts of the code that would help please just let me know and I'll try to be quick!
Thank you!

how can i fix my progress and seek slider to work for all media?

so im making a media player in javafx (eclipse) and i used to slider as a progress bar and scrubber but for some reason the sider only shows the progress for the first media , as soon as i press next the progress doesnt show anymore.
i can still seek to the position i was to but progress wont show
Here is the code for the main class
i have a class play List item which holds the names for all the files in a given directory
package application;
import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.util.Duration;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.input.MouseEvent;
import javafx.scene.media.Media;
import javafx.event.EventHandler;
public class MainController implements Initializable {
#FXML
private MediaView mv;
private MediaPlayer mp;
private Media me;
#FXML
private Label title;
#FXML
Slider volslider;
int pointer = 0;
#FXML
Slider progBar;
#Override
public void initialize(URL location, ResourceBundle resources) {
String path = new File("src/media/" + application.Playlist.playnext(pointer)).getAbsolutePath();
me = new Media(new File(path).toURI().toString());
mp = new MediaPlayer(me);
mv.setMediaPlayer(mp);
// mp.setAutoPlay(true);
DoubleProperty width = mv.fitWidthProperty();
DoubleProperty height = mv.fitHeightProperty();
width.bind(Bindings.selectDouble(mv.sceneProperty(), "width"));
height.bind(Bindings.selectDouble(mv.sceneProperty(), "height"));
mp.setOnReady(new Runnable() {
#Override
public void run() {
volslider.setValue(mp.getVolume() * 100);
volslider.valueProperty().addListener(new InvalidationListener() {
#Override
public void invalidated(Observable observable) {
mp.setVolume(volslider.getValue() / 100);
}
});
mp.currentTimeProperty().addListener(new ChangeListener<Duration>() {
#Override
public void changed(ObservableValue<? extends Duration> observable, Duration oldValue,
Duration newValue) {
progBar.setValue((newValue.toSeconds() / mp.getTotalDuration().toSeconds()) * 100);
}
});
progBar.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
mp.seek(Duration.seconds((progBar.getValue() / 100) * mp.getTotalDuration().toSeconds()));
}
});
}
});
}
public void play(ActionEvent event) {
mp.play();
}
public void pause(ActionEvent event) {
mp.pause();
}
public void speedup(ActionEvent event) {
mp.setRate(2);
}
public void normalspeed(ActionEvent event) {
mp.setRate(1);
}
public void slowmo(ActionEvent event) {
mp.setRate(0.5);
}
public void reload(ActionEvent event) {
progBar.setValue(0);
mp.seek(mp.getStartTime());
mp.stop();
}
public void end(ActionEvent event) {
progBar.setValue(100);
mp.seek(mp.getTotalDuration());
mp.stop();
}
public void next(ActionEvent event) {
progBar.setValue(0);
mp.seek(mp.getTotalDuration());
mp.stop();
pointer++;
pointer = application.Playlist.checkrange(pointer);
String path = new File("src/media/" + application.Playlist.playnext(pointer)).getAbsolutePath();
me = new Media(new File(path).toURI().toString());
mp = new MediaPlayer(me);
mv.setMediaPlayer(mp);
mp.play();
}
public void previous(ActionEvent event) {
// progBar.setValue(0);
mp.seek(mp.getTotalDuration());
mp.stop();
pointer--;
pointer = application.Playlist.checkrange(pointer);
String path = new File("src/media/" + application.Playlist.playnext(pointer)).getAbsolutePath();
me = new Media(new File(path).toURI().toString());
mp = new MediaPlayer(me);
mv.setMediaPlayer(mp);
mp.play();
}
}
In your next() method you create a new MediaPlayer but you don't update the reference to your currentTime property which has been bound in the initialize function. If you want to change that, unbind the old MediaPlayer's currentTime property and then bind it to your new MediaPlayer instance in next().

Show The Desired/Specific Frequency

I've made an android apps about visualize spectrum frequency from recording sound. I'm using package from www.netlib.org/fftpack/jfftpack.tgz to perform FFT. We know that Each line of spectrum handle frequency from this formula : "((frequency_sample/2)/samples)". Its easy to see the first, second, and third spectrum that occurs. But, above fifth spectrum its hard to determine which spectrum it is.
I want to know the specific frequency (for example freq 200Hz) is occur or not and show it as toast or something like that. Is there any good source library I could refer to do this?
Thanks :)
package com.example.agita.stethoscopeandroid;
/**
* Created by Agita on 5/21/2015.
*/
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import ca.uol.aig.fftpack.RealDoubleFFT;
public class RekamActivity extends Activity implements OnClickListener {
Button startRecordingButton, stopRecordingButton;
TextView statusText;
File recordingFile;
boolean isRecording = false;
int frequency = 8000;
int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
private RealDoubleFFT transformer;
int blockSize = 256;
RecordAudio recordTask;
ImageView imageView;
Bitmap bitmap;
Canvas canvas;
Paint paint;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rekam);
statusText = (TextView) this.findViewById(R.id.StatusTextView);
startRecordingButton = (Button) this .findViewById(R.id.StartRecordingButton);
stopRecordingButton = (Button) this .findViewById(R.id.StopRecordingButton);
startRecordingButton.setOnClickListener(this);
stopRecordingButton.setOnClickListener(this);
stopRecordingButton.setEnabled(false);
transformer = new RealDoubleFFT(blockSize);
imageView = (ImageView) this.findViewById(R.id.ImageView01);
bitmap = Bitmap.createBitmap(256, 100, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
paint = new Paint();
paint.setColor(Color.GREEN);
imageView.setImageBitmap(bitmap);
String recordedAudioFile = getRecoredAudioFile();
File path = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Datarekaman/");
path.mkdirs();
try {
recordingFile = File.createTempFile("recording"+recordedAudioFile, ".wav", path);
} catch (IOException e) {
throw new RuntimeException("Couldn't create file on SD card", e);
}
}
private String getRecoredAudioFile() {
String returnAudio;
java.util.Date date= new java.util.Date();
returnAudio = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date.getTime());
return returnAudio;
}
public void onClick(View v) {
if (v == startRecordingButton) {
record();
} else if (v == stopRecordingButton) {
stopRecording();
}
}
public void record() {
startRecordingButton.setEnabled(false);
stopRecordingButton.setEnabled(true);
recordTask = new RecordAudio();
recordTask.execute();
}
public void stopRecording() {
isRecording = false;
}
private class RecordAudio extends AsyncTask<Void, double[], Void> {
#Override
protected Void doInBackground(Void... params) {
isRecording = true;
try {
DataOutputStream dos = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream(
recordingFile)));
int bufferSize = AudioRecord.getMinBufferSize(frequency,
channelConfiguration, audioEncoding);
AudioRecord audioRecord = new AudioRecord(
MediaRecorder.AudioSource.MIC, frequency,
channelConfiguration, audioEncoding, bufferSize);
short[] buffer = new short[blockSize];
double[] toTransform = new double[blockSize];
audioRecord.startRecording();
while (isRecording) {
int bufferReadResult = audioRecord.read(buffer, 0,
blockSize);
for (int i = 0; i < blockSize && i < bufferReadResult; i++) {
dos.writeShort(buffer[i]);
toTransform[i] = (double) buffer[i]/32768.0;
}
transformer.ft(toTransform);
publishProgress(toTransform);
}
audioRecord.stop();
dos.close();
} catch (Throwable t) {
Log.e("AudioRecord", "Recording Failed");
}
return null;
}
/*protected void onProgressUpdate(Integer... progress) {
statusText.setText(progress[0].toString());
}*/
protected void onProgressUpdate (double[]... toTransform) {
canvas.drawColor(Color.BLACK);
for (int i = 0; i < toTransform[0].length; i++) {
int x;
x = i;
int downy = (int) (100 - (toTransform[0][i] * 10));
int upy = 100;
//canvas.drawRect(x * 3, downy, x * 3 + 4, upy, paint);
canvas.drawLine(x, downy, x, upy, paint);
imageView.invalidate();
}
}
protected void onPostExecute(Void result) {
startRecordingButton.setEnabled(true);
stopRecordingButton.setEnabled(false);
}
}
}

How I can get array which values were get in method of another class

In mainActivity I made timer,which you click in button each 3 seconds show value of available memory and write in array.And after writting finished, the second button "see chart" stay clickable,we click and transwer to the next activity(second class).
In second class creates canvas with lines, and must be create chart which can show available memory in time. But I can't carry array in first class to second class.
I need carry array "Masiv " at method run() to my second class.
First class
package foxstrot.p3;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.Intent;
import android.graphics.Canvas;
import android.os.Build;
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 java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
public class MainActivity extends ActionBarActivity {
private Timer timer;
private MyTimerTask myTimerTask;
private Intent i;
long[] Masiv = new long[50];
int k;
private long freeMemory;
private Canvas canvas;
private G.DrawView d;
private int t = 0;
private long j;
private TextView tv;
private long r;
private Button b2;
MyTimerTask myTimerTask1 = new MyTimerTask();
int ii = 0;
ArrayList <Integer> AL = new ArrayList<Integer>() ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView);
b2 = (Button)findViewById(R.id.b2);
b2.setClickable(false);
//myTimerTask1.getMas();
//actManager.getMemoryInfo(memInfo);
//freeMemory = memInfo.availMem;
//tv.setText("freeMemory: " + freeMemory);
//Canvas canvas = new Canvas();
/*G g = new G();
G.DrawView d = g.new DrawView(this);*/
}
public void start(View v) {
timer = new Timer();
myTimerTask = new MyTimerTask();
timer.schedule(myTimerTask, 3000, 3000);
}
public void chart(View v){
i = new Intent(this,G.class);
startActivity(i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class MyTimerTask extends TimerTask {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
long getFreeMemory(){
ActivityManager actManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
actManager.getMemoryInfo(memInfo);
freeMemory = memInfo.availMem;
return freeMemory;
}
runOnUiThread(new Runnable() {
#Override
public void run() {
r = getFreeMemory();
k = (int)r/100000;
//setMas(k)
AL.add(k);
tv.setText("Free memory : " + k);
t++;
if(t == 5){
cancel();
b2.setClickable(true);
}
}
});
}
public void setMas(long p){
//if(ii==5){}
//Log.d("LOG_TAG", "SetMy_Array[0]: " + k + "SetMy_Array[1]: " + k);
ii++;
}
/*public long getMas(){
Log.d("LOG_TAG", "GetMy_Array[0]: " + k + "GetMy_Array[1]: " + k);
return k;
}*/
}
}
Second class
package foxstrot.p3;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
/**
* Created by Admin on 14.04.2015.
*/
public class G extends Activity {
int ii;
private long[] My_Array ;
private MainActivity mainActivity = new MainActivity();
//private MainActivity.MyTimerTask myTimerTask = mainActivity.new MyTimerTask();
//private long[] G_mas = myTimerTask.getMas();
ArrayList<Integer> AL = new ArrayList<Integer>() ;
Intent intent;
private boolean drawGraph = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new DrawView(this));
intent = getIntent();
//AL = intent.getIntegerArrayListExtra("Joker");
//Log.d("LOG_TAG","Al: " + AL.get(0) + "AL: " + AL.get(0));
//My_Array = myTimerTask.getMas();
//Log.d("LOG_TAG","My_Array[0]: " + myTimerTask.getMas() + "My_Array[1]: " + myTimerTask.getMas());
/*for(int i=0;i<G_mas.length;i++){
max = Math.max(max,G_mas[i]);
min = G_mas[i];
min = Math.min(min, G_mas[i]);
}*/
}
public class DrawView extends View{
Paint p;
Rect rect;
int uN = 0;
int uT = 0;
int y1 = 0;
int x1 = 0;
int n = 2000;
int t = 0;
public DrawView(Context context){
super(context);
p = new Paint();
rect = new Rect();
}
#Override
public void onDraw(Canvas canvas) {
final int cHeight = canvas.getHeight();
final int cWidth = canvas.getWidth();
Paint paint = new Paint();
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
paint.setColor(Color.BLACK);
paint.setTextSize(30);
canvas.drawLine(80,0,80,cHeight-60,paint);
canvas.drawLine(80,cHeight-60,cWidth,cHeight-60,paint);
for(int i=0;i<50;i++){
canvas.drawText(uT + "" , 10 , 25 + y1, paint);
uT = uT + 3;
y1 = y1 + (cHeight/50);
}
for(int i=0;i<9;i++){
canvas.drawText("|"+ uN, 75 + x1, cHeight - 25 , paint);
uN = uN + 1000;
x1 = x1 + (cWidth/9)-25;
/*int joker = 10;
canvas.drawPoint(20+ joker,20,paint);
joker = joker + 40;*/
}
paint.setStrokeWidth(10);
/*for(int i=0;i<My_Array.length;i++){
long xc = (My_Array[i] * (cWidth-80)) / 8000 ;
int yc = (t * (cHeight-60))/147;
t = t + 3;
canvas.drawPoint(xc, yc, paint);
Log.d("LOG_TAG","xc: " + xc + "yc: " + yc);
}*/
/*Paint paint2 = new Paint();
paint2.setColor(Color.RED);
canvas.drawPoint(cWidth, cHeight, paint2);*/
}
}
}
Just use putExtra() and getLongArrayExtra().
Documentation: putExtra(String name, long[] value) and getLongArrayExtra(String name)
In MainActivity.java:
public void chart(View v){
i = new Intent(this,G.class);
i.putExtra("foxstrot.p3.masiv", Masiv);
startActivity(i);
}
In G.java:
private boolean drawGraph = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new DrawView(this));
intent = getIntent();
My_Array = intent.getLongArrayExtra("foxstrot.p3.masiv");
//...................

Ondraw method is not being called

I have my main class like so:
package projects.game.spinners;
import java.util.ArrayList;
import java.util.Collections;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.view.Menu;
public class MainActivity extends Activity
{
public Set set;
public Deal deal= new Deal();
public Player Name = new Player();
public computer comp1= new computer();
public computer comp2= new computer();
public computer comp3= new computer();
private Table table;
public Canvas canvas;
//public ArrayList<Domino> deck = set.getSet();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
set = new Set(this);
table = new Table(this);
ArrayList<Domino> deck = set.getSet();
canvas = new Canvas();
Collections.shuffle(deck);
//deal.deal(Name, comp1, comp2, comp3, deck);
//deck = deal.getDeck();
table.playDomino(deck.get(0), 0, 0);
table.invalidate();
//table.onDraw(this);
//Bitmap dsd = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
}
#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;
}
}
my ondraw method is inside table and it looks like this:
package projects.game.spinners;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.view.View;
import android.widget.Toast;
public class Table extends View
{
ArrayList<Position> table;
Context ctx;
Bitmap draw;
public Table(Context context)
{
super(context);
ctx=context;
table=new ArrayList<Position>();
draw = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
this.setWillNotDraw(false);
}
public int getPossiblePlays()
{
return 0;
}
public void playDomino(Domino domino, int x , int y)
{
table.add(new Position(domino,x,y));
}
#Override
public void onDraw(Canvas canvas)
{
super.onDraw(canvas);
Toast.makeText(ctx,"Tag Already Done", Toast.LENGTH_LONG).show();
canvas.drawBitmap(draw, 0,0, null);
canvas.drawBitmap(table.get(0).getDomino().getImage(), 0,0, null);
}
}
When this is run nothing is being Draw. I want to be able to draw this over and over as i change what should be drawn if there is any other way to do this that does not use a none callable class.
Seems like the table View hasn't been added to anything that's being drawn. Try something like this in your main activity's onCreate:
table = new Table(this);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.IdOfYourMainLayoutFromYourManifest);
layout.addView(table);

Categories