Ondraw method is not being called - java

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);

Related

Flappy Bird Game I am getting error while adding pipe

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

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().

How to Display Images on an ArrayList of JButtons?

I am attempting to make a pseudo candy crush style game. I am currently attempting to add images contained in an ArrayList to JButtons that are in an ArrayList as well. I am unsure how to go about this and what I currently have, clearly, doesn't work, as it does not display the images within the JButtons. Here is my UI code:
package code.ui;
import java.awt.GridLayout;
import java.awt.Image;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import code.model.Model;
public class gameUI implements Runnable {
private JFrame _frame;
private Model _model;
private ArrayList<JButton> _buttons;
private JButton _spin;
#Override public void run() {
_frame = new JFrame("Switcher");
_frame.getContentPane().setLayout(new GridLayout(5,5));
_model = new Model(); // create the model for this UI
_model.addObserver(this);
_buttons = new ArrayList<JButton>();
for (int i=0; i<25; i++) {
JButton button = new JButton();
_buttons.add(button);
_frame.getContentPane().add(button);
_buttons.get(i).setIcon(new ImageIcon("Images/"+_model.getImageFileName(i)));
Collections.shuffle(_buttons);
}
_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
_frame.pack();
_frame.setVisible(true);
}
}
This is my code for the model:
package code.model;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.ImageIcon;
public class Model {
private Random _rand;
private ArrayList<String> _imageFileNames;
private ArrayList<String> _imageCurrentValues;
public Model() {
_rand = new Random();
_imageFileNames = new ArrayList<String>();
_imageFileNames.add("Red.png");
_imageFileNames.add("Green.png");
_imageFileNames.add("Purple.png");
_imageFileNames.add("Tile-0.png");
_imageFileNames.add("Tile-1.png");
_imageFileNames.add("Tile-2.png");
_imageFileNames.add("Tile-3.png");
_imageFileNames.add("Tile-4.png");
_imageFileNames.add("Tile-5.png");
_imageCurrentValues = new ArrayList<String>();
for(int i=0; i<25; i=i+1) {
_imageCurrentValues.add(i,null);
}
}
public String getImageFileName(int i) {
return _imageCurrentValues.get(i);
}
}

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");
//...................

MVC with several identical views

for the purpose of my application i need to create several identical views that should behave and response to the same events. Should i instanciate each identical views that i need and hold this list of views in my controller, or there are better ways of handling this ? Thanks.
From what I understand... You should follow your thinking.
Have a list of views that you install to a controller. And if the event occurs go through the list of views and update all of them.
EDIT1: Here is a very simple example showing how it might be done.
import java.awt.Color;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ManyViewsTest
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
View v1 = new View();
View v2 = new View();
View v3 = new View();
View v4 = new View();
View v5 = new View();
JPanel contentPane = new JPanel();
contentPane.add(v1);
contentPane.add(v2);
contentPane.add(v3);
contentPane.add(v4);
contentPane.add(v5);
JFrame f = new JFrame();
f.setContentPane(contentPane);
f.setSize(800, 600);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Controller c = new Controller(f);
f.setVisible(true);
}
});
}
}
class Controller
{
private List<View> views;
public Controller(JFrame f)
{
this.views = new ArrayList<View>();
f.addMouseListener(mL);
for(Component c: f.getContentPane().getComponents())
{
if(c instanceof View)
views.add((View)c);
}
}
public void updateView(String text)
{
for(View v: views)
v.setLabelText(text);
}
private MouseListener mL = new MouseAdapter()
{
int pressCounter = 0;
#Override
public void mousePressed(MouseEvent e)
{
super.mousePressed(e);
updateView("mousePressed, pressCounter="+(++pressCounter));
}
};
}
class View extends JPanel
{
private static final long serialVersionUID = 1L;
private JLabel label;
public View()
{
this.label = new JLabel("Initialized");
label.setBorder(BorderFactory.createLineBorder(Color.GREEN));
add(label);
}
public void setLabelText(String text)
{
label.setText(text);
}
}

Categories