Unable to Interact with Android Custom Dialog - java

Ok, bear with me because I haven't worked with custom Dialogs (or Android programming at all really) that much, and I'm sure I've made a stupid beginner mistake.
So I have a simple dice rolling app that I'm trying to incorporate into my existing app, but I want to do it as essentially a popup. The solution I found thus far was to extend a dialog class and use the xml from the app as a custom layout. This actually displays the expected output, but doesn't allow me to interact with it (i.e. it shows dice on screen but I can't roll them!).
The java class I'm calling is this:
import java.io.IOException;
import java.util.Random;
import com.zeldar.scanner.R;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class RollDice extends Activity implements SensorEventListener {
private final int rollAnimations = 50;
private final int delayTime = 15;
private Resources res;
private final int[] diceImages = new int[] { R.drawable.d1, R.drawable.d2, R.drawable.d3, R.drawable.d4, R.drawable.d5, R.drawable.d6 };
private Drawable dice[] = new Drawable[6];
private final Random randomGen = new Random();
#SuppressWarnings("unused")
private int diceSum;
private int roll[] = new int[] { 6, 6 };
private ImageView die1;
private ImageView die2;
private LinearLayout diceContainer;
private SensorManager sensorMgr;
private Handler animationHandler;
private long lastUpdate = -1;
private float x, y, z;
private float last_x, last_y, last_z;
private boolean paused = false;
private static final int UPDATE_DELAY = 50;
private static final int SHAKE_THRESHOLD = 400;
#Override
public void onCreate(Bundle savedInstanceState) {
paused = false;
super.onCreate(savedInstanceState);
setContentView(R.layout.dice);
setTitle(getString(R.string.app_name));
res = getResources();
for (int i = 0; i < 6; i++) {
dice[i] = res.getDrawable(diceImages[i]);
}
diceContainer = (LinearLayout) findViewById(R.id.diceContainer);
diceContainer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
rollDice();
} catch (Exception e) {};
}
});
die1 = (ImageView) findViewById(R.id.die1);
die2 = (ImageView) findViewById(R.id.die2);
animationHandler = new Handler() {
public void handleMessage(Message msg) {
die1.setImageDrawable(dice[roll[0]]);
die2.setImageDrawable(dice[roll[1]]);
}
};
sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
boolean accelSupported = sensorMgr.registerListener(this,
sensorMgr.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
if (!accelSupported) sensorMgr.unregisterListener(this); //no accelerometer on the device
rollDice();
}
private void rollDice() {
if (paused) return;
new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < rollAnimations; i++) {
doRoll();
}
}
}).start();
MediaPlayer mp = MediaPlayer.create(this, R.raw.roll);
try {
mp.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
}
private void doRoll() { // only does a single roll
roll[0] = randomGen.nextInt(6);
roll[1] = randomGen.nextInt(6);
diceSum = roll[0] + roll[1] + 2; // 2 is added because the values of the rolls start with 0 not 1
synchronized (getLayoutInflater()) {
animationHandler.sendEmptyMessage(0);
}
try { // delay to alloy for smooth animation
Thread.sleep(delayTime);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
public void onResume() {
super.onResume();
paused = false;
}
public void onPause() {
super.onPause();
paused = true;
}
#Override
public void onSensorChanged(SensorEvent event) {
Sensor mySensor = event.sensor;
if (mySensor.getType() == SensorManager.SENSOR_ACCELEROMETER) {
long curTime = System.currentTimeMillis();
if ((curTime - lastUpdate) > UPDATE_DELAY) {
long diffTime = (curTime - lastUpdate);
lastUpdate = curTime;
x = event.values[SensorManager.DATA_X];
y = event.values[SensorManager.DATA_Y];
z = event.values[SensorManager.DATA_Z];
float speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;
if (speed > SHAKE_THRESHOLD) { //the screen was shaked
rollDice();
}
last_x = x;
last_y = y;
last_z = z;
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
return; //this method isn't used
}
}
And this is the layout xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/diceContainer"
android:orientation="vertical"
android:gravity="center"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp" >
<ImageView
android:id="#+id/die1"
android:src="#drawable/d6"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginBottom="15dp"
android:contentDescription="#string/content_dice" />
<ImageView
android:id="#+id/die2"
android:src="#drawable/d6"
android:layout_width="150dp"
android:layout_height="150dp"
android:contentDescription="#string/content_dice" />
</LinearLayout>
Finally, the call I'm using to create the dialog:
private Dialog rollDice;
rollDice = new Dialog(ScanActivity.this);
rollDice.setContentView(R.layout.dice);
rollDice.setTitle("Roll Dice");
rollDice.setCancelable(true);
rollDice.show();
To clarify: the most confusing part is that I'm not getting an error, either on compile or run time, it just pops up the window and won't let me do anything with it (except dismiss)!

I would suggest using an activity with a dialog theme if you are wanting something like a dialog. This will allow it to "pop-up" like a dialog but give you more flexibility and easier to manipulate, IMHO. Create a separate activity to open up and add this to your manifest for the activity
<activity android:theme="#android:style/Theme.Dialog">
Themes
There may be a better way to do this but I think this might work well for you.

Related

Android Studio (Log Sensor Data to csv. File)

I have to log my Sensor data from my Android Phone to a csv. file so I can use it further , the problem is I tried something with some code(FileWriter to csv) that I found and put it into my code and it does not work, can maybe someone tell me what I do wrong, where my error is. The idea is to just record different sensor data with different EventHandlers like in the Code Example and then write the sensor data to a csv. file together and that csv. file should be on the phone.
I have maybe to mention that I have never before programed in Java or did Android , so please try to answer me as simple as possible, thank you :)
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.CompoundButton;
import android.widget.ProgressBar;
import android.widget.Switch;
import android.widget.TextView;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
TextView txt_currentAccel, txt_prevAccel, txt_acceleration, txt_temp;
ProgressBar prog_shakeMeter;
Switch switch1;
//define Sensor Variables
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private SensorManager mSensorManagerNew;
private Sensor mTemp;
private double accelerationCurrentValue;
private double accelerationPreviousValue;
private int SwitchFlag = 0;
final String TAG = "SensorLog";
FileWriter writer;
private SensorEventListener sensorEventListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER && SwitchFlag == 1) {
float x = sensorEvent.values[0];
float y = sensorEvent.values[1];
float z = sensorEvent.values[2];
accelerationCurrentValue = Math.sqrt((x * x + y * y + z * z));
double changeInAcceleration = Math.abs(accelerationCurrentValue - accelerationPreviousValue);
accelerationPreviousValue = accelerationCurrentValue;
//update text views
txt_currentAccel.setText("Current =" + accelerationCurrentValue);
txt_prevAccel.setText(("Prev = " + accelerationPreviousValue));
txt_acceleration.setText("Acceleration change =" + changeInAcceleration);
prog_shakeMeter.setProgress((int) changeInAcceleration);
try {
writer.write(String.format("ACC; %f; %f; %f; %f; %f; %f\n", sensorEvent.values[0], sensorEvent.values[1], sensorEvent.values[2], 0.f, 0.f, 0.f));
}catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
};
private SensorEventListener sensorEventListenerNew = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
float temp = sensorEvent.values[0];
txt_temp.setText("Temp = " + temp);
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt_acceleration = findViewById(R.id.txt_accel);
txt_prevAccel = findViewById(R.id.txt_prevAccel);
txt_currentAccel = findViewById(R.id.txt_currentAccel);
txt_temp = findViewById(R.id.txt_temp);
prog_shakeMeter = findViewById(R.id.prog_shakeMeter);
switch1 = findViewById(R.id.switch1);
// Initialize Sensors
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManagerNew = (SensorManager) getSystemService(SENSOR_SERVICE);
mTemp = mSensorManagerNew.getDefaultSensor(Sensor.TYPE_LIGHT);
switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b == true) {
SwitchFlag = 1;
} else {
SwitchFlag = 0;
}
}
});
}
public void flag() {
if (SwitchFlag == 1) {
Log.d(TAG, "Writing to " + getStorageDir());
try {
writer = new FileWriter(new File(getStorageDir(), "sensors_" + System.currentTimeMillis() + ".csv"));
} catch (
IOException e) {
e.printStackTrace();
}
} else {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(sensorEventListenerNew, mTemp, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(sensorEventListener, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(sensorEventListener);
mSensorManager.unregisterListener(sensorEventListenerNew);
}
private String getStorageDir() {
return this.getExternalFilesDir(null).getAbsolutePath();
}
}

Android: Save CSV File to internal Storage

I have put somehow together a code that records my sensor data from the phone and i want to save them as csv file in some directory (maybe DCIM) in the internal Storage on the phone, but i cannot find something similar, i am also new to Android Studio and java.
On the bottom you can see ,i found that code example with
"getExternalFilesDir(null).getAbsolutePath()" , how can i change that , that my file is saved on the phone in internal storage and tell him exactly where so i can find it later and use it further ?
package com.example.shakedemo;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.CompoundButton;
import android.widget.ProgressBar;
import android.widget.Switch;
import android.widget.TextView;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
TextView txt_currentAccel, txt_prevAccel, txt_acceleration, txt_temp;
ProgressBar prog_shakeMeter;
Switch switch1;
//define Sensor Variables
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private SensorManager mSensorManagerNew;
private Sensor mTemp;
private double accelerationCurrentValue;
private double accelerationPreviousValue;
private int SwitchFlag = 0;
final String TAG = "SensorLog";
FileWriter writer;
private SensorEventListener sensorEventListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER && SwitchFlag == 1) {
float x = sensorEvent.values[0];
float y = sensorEvent.values[1];
float z = sensorEvent.values[2];
accelerationCurrentValue = Math.sqrt((x * x + y * y + z * z));
double changeInAcceleration = Math.abs(accelerationCurrentValue - accelerationPreviousValue);
accelerationPreviousValue = accelerationCurrentValue;
//update text views
txt_currentAccel.setText("Current =" + accelerationCurrentValue);
txt_prevAccel.setText(("Prev = " + accelerationPreviousValue));
txt_acceleration.setText("Acceleration change =" + changeInAcceleration);
prog_shakeMeter.setProgress((int) changeInAcceleration);
try {
writer.write(String.format("ACC; %f; %f; %f; %f; %f; %f\n", sensorEvent.values[0], sensorEvent.values[1], sensorEvent.values[2], 0.f, 0.f, 0.f));
}catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
};
private SensorEventListener sensorEventListenerNew = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
float temp = sensorEvent.values[0];
txt_temp.setText("Temp = " + temp);
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt_acceleration = findViewById(R.id.txt_accel);
txt_prevAccel = findViewById(R.id.txt_prevAccel);
txt_currentAccel = findViewById(R.id.txt_currentAccel);
txt_temp = findViewById(R.id.txt_temp);
prog_shakeMeter = findViewById(R.id.prog_shakeMeter);
switch1 = findViewById(R.id.switch1);
// Initialize Sensors
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManagerNew = (SensorManager) getSystemService(SENSOR_SERVICE);
mTemp = mSensorManagerNew.getDefaultSensor(Sensor.TYPE_LIGHT);
switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b == true) {
Log.d(TAG, "Writing to " + getStorageDir());
try {
writer = new FileWriter(new File(getStorageDir(), "sensors_" + System.currentTimeMillis() + ".csv"));
} catch (
IOException e) {
e.printStackTrace();
}
SwitchFlag = 1;
} else {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
SwitchFlag = 0;
}
}
});
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(sensorEventListenerNew, mTemp, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(sensorEventListener, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(sensorEventListener);
mSensorManager.unregisterListener(sensorEventListenerNew);
}
private String getStorageDir() {
return this.getExternalFilesDir(null).getAbsolutePath();
}
}

Trying to add a touch event on my bitmap, but i got wrong values? Android Studio

Im new on Stack Overflow!, I joined here for some problem that I got right now.
Im working with Android Studio where im trying to make a type of game that it requires a grid usage to start it. At this point im trying to implement the touch event on some bitmaps, those bitmaps are the tiles of my game but im kinda of confused, in My view, where I place all of the tiles i can get all of the coordinates (including height and width) of each tile, I check those values but when I apply the touch event (On Action Down) im getting the coords of my last tile of my grid. Thats strange, because when im drawing it in my canvas Im still got the actual values (the real coords) but in touch are different, im trying to figure this but no result at all.
Can someone here tell me where i go wrong?
Sorry for my english.
PS: The grid can be dragged.
MyView.java
package com.example.sammuzero.aplicamesta;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Map;
/**
* Created by lezama on 24-07-2017.
*/
public class MyView extends SurfaceView {
Bitmap piso1;
Bitmap muro;
Bitmap queso;
SurfaceHolder aguanta;
GameLoopThread loopGame;
Terreno pintaTerreno;
Sprite mouse;
boolean scroll;
float destinyX = 0;
float destinyY = 0;
float originX = 0;
float originY = 0;
float transX = 0;
float transY = 0;
float escala = 1;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
aguanta = getHolder();
loopGame = new GameLoopThread(this);
aguanta.addCallback(new SurfaceHolder.Callback(){
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
loopGame.setRunning(true);
loopGame.start();
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
boolean retry = true;
loopGame.setRunning(false);
while (retry) {
try {
loopGame.join();
retry = false;
} catch (InterruptedException e) {}
}
}
});
piso1 = BitmapFactory.decodeResource(getResources(), R.drawable.floor1);
muro = BitmapFactory.decodeResource(getResources(), R.drawable.pared);
queso = BitmapFactory.decodeResource(getResources(), R.drawable.kso);
pintaTerreno = new Terreno(0,0,new MapBit(piso1), new MapBit(muro));
}
public void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
canvas.scale(escala,escala);
canvas.translate((destinyX - originX), (destinyY - originY));
transX = (destinyX - originX);
transY = (destinyY - originY);
for(int i = 0; i < pintaTerreno.getAncho(); i++) {
for (int j = 0; j < pintaTerreno.getAlto(); j ++){
dibujaCasilla(i,j, canvas);
Log.i("Probando X,Y", "X: " + pintaTerreno.getCasilla(i, j).getGrafico().getX()
+ " Y: " + pintaTerreno.getCasilla(i, j).getGrafico().getY());
}
}
canvas.scale(1.0f,1.0f);
//mouse.onDraw(canvas);
}
public void queTerrenoDibujo(Terreno e)
{
pintaTerreno = e;
}
public void setEscala(int escalaATransformar) {
float nuevaEscala;
nuevaEscala = (float) escalaATransformar / 100;
escala = nuevaEscala;
}
private void dibujaCasilla(int i, int j,Canvas canvas) {
// Primero revisa si hay una pared o no alli.
if (pintaTerreno.getCasilla(i,j).getRepresenta() == 'P') {
pintaTerreno.getCasilla(i,j).getGrafico().setX(64 * i);
pintaTerreno.getCasilla(i,j).getGrafico().setY(64 * j);
pintaTerreno.getCasilla(i,j).getGrafico().onDraw(canvas);
}
else {
pintaTerreno.getCasilla(i,j).getGrafico().setX(64 * i);
pintaTerreno.getCasilla(i,j).getGrafico().setY(64 * j);
pintaTerreno.getCasilla(i,j).getGrafico().onDraw(canvas);
if(pintaTerreno.getCasilla(i,j).getRepresenta() == 'Q')
canvas.drawBitmap(queso,(64 * i) + 16, (64 * j) + 16, null);
}
/*
MapBit nuevoBloque = null;
if (pintaTerreno.getCasilla(i,j).getRepresenta() == 'P') {
nuevoBloque = new MapBit((64 * i),(64 * j),muro);
nuevoBloque.onDraw(canvas);
}
else {
nuevoBloque = new MapBit((64 * i),(64 * j),piso1);
nuevoBloque.onDraw(canvas);
if(pintaTerreno.getCasilla(i,j).getRepresenta() == 'Q')
canvas.drawBitmap(queso,(64 * i) + 16, (64 * j) + 16, null);
}
*/
// Luego, asegurate de los elementos que estan en esa casilla.
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
//return super.onTouchEvent(event);
int action = event.getAction();
if (action==MotionEvent.ACTION_MOVE){
destinyX = event.getX();
destinyY = event.getY();
}
else if (action==MotionEvent.ACTION_DOWN) {
Log.i("Probando X,Y en 0,0", "X: " + pintaTerreno.getCasilla(0, 0).getGrafico().getX()
+ " Y: " + pintaTerreno.getCasilla(0, 0).getGrafico().getY());
for (int i = 0; i < pintaTerreno.getAncho(); i++) {
for (int j = 0; j < pintaTerreno.getAlto(); j++) {
Log.i("Probando X,Y", "X: " + pintaTerreno.getCasilla(i, j).getGrafico().getX()
+ " Y: " + pintaTerreno.getCasilla(i, j).getGrafico().getY());
String msg = "X: " + pintaTerreno.getCasilla(i, j).getGrafico().getX() + " Y: " + pintaTerreno.getCasilla(i, j).getGrafico().getY();
if (pintaTerreno.getCasilla(i, j).getGrafico().isCollition(event.getX(), event.getY())) {
Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
}
}
}
originX = event.getX() - transX;
originY = event.getY() - transY;
scroll = true;
}
else if (action==MotionEvent.ACTION_UP){
transX = (destinyX - originX);
transY = (destinyY - originY);
scroll = false;
}
return true;
}
}
Terreno.java (The grid)
package com.example.sammuzero.aplicamesta;
import java.util.ArrayList;
import java.util.Random;
/**
*
* #author estudiante
*/
public class Terreno {
private ArrayList<Object> todo = new ArrayList<>();
private Casilla[][] plataforma;
private int alto;
private int ancho;
public Terreno (int alt, int anch, MapBit nada, MapBit pared)
{
int i;
int j;
this.plataforma = new Casilla[alt][anch];
this.alto = alt;
this.ancho = anch;
for(i = 0; i < this.alto; i++)
for(j = 0; j < this.ancho; j++)
this.plataforma[i][j] = new Casilla(i,j, nada);
this.inicializa(pared);
}
// Getters //
public int getAlto(){return this.alto;}
public int getAncho(){return this.ancho;}
public Casilla getCasilla(int i, int j){return this.plataforma[i][j];}
public ArrayList<Object> getTodo(){return this.todo;}
// Setters //
public void setEnCasilla(int x, int y, Object o, char r){this.plataforma[x][y].setObjeto(o,r);}
// Metodos //
public void inicializa(MapBit pared)
{
int cuantos = ((this.alto*this.ancho) * 10) / 100;
Random rand = new Random();
int llevo = 0;
int sel = 0;
for(int i = 0; i < this.alto ; i++)
for(int j = 0 ; j < this.ancho; j++)
{
sel = 1+rand.nextInt(10);
if(sel == 1 && llevo < cuantos)
{
Pared nueva = new Pared(this.plataforma[i][j]);
this.plataforma[i][j].setGrafico(pared);
todo.add(nueva);
llevo ++;
}
else if (sel == 10) {
Queso nuevo = new Queso(this.plataforma[i][j]);
todo.add(nuevo);
}
}
}
}
Casilla.java (the tile)
package com.example.sammuzero.aplicamesta;
import android.support.design.widget.Snackbar;
/**
* Created by lezama on 28-07-2017.
*/
public class Casilla {
private int posX;
private int posY;
private Object contenido;
private char representa;
private MapBit grafico;
public Casilla(int i, int j, MapBit graf)
{
this.posX = i;
this.posY = j;
this.representa = '0';
contenido = null;
this.grafico = graf;
}
public int getPosX() {return this.posX;}
public int getPosY() {return this.posY;}
public char getRepresenta() {return this.representa;}
public MapBit getGrafico() {return this.grafico;}
public void setObjeto(Object item , char rep)
{
this.contenido = item;
this.representa = rep;
}
public void setGrafico (MapBit grafico1) {this.grafico = grafico1;}
/*
public void onTouch()
{
Toast.makeText(this.getContext(), "X:"+this.posX+" Y:"+this.posY, Toast.LENGTH_SHORT).show();
} */
}
MapBit.java (where it resides my Bitmap)
package com.example.sammuzero.aplicamesta;
import android.graphics.Bitmap;
import android.graphics.Canvas;
/**
* TI, MapBit!
* Created by Samuzero15 on 28-07-2017.
*/
public class MapBit {
private float x;
private float y;
private int height;
private int width;
private Bitmap bmp;
public MapBit(Bitmap pmb)
{
this.bmp = pmb;
this.height = this.bmp.getHeight();
this.width = this.bmp.getWidth();
}
// Getmethis
public float getX(){return this.x;}
public float getY(){return this.y;}
public int getHeight(){return this.height;}
public int getWidth(){return this.width;}
public Bitmap getBitmap(){return this.bmp;}
public void setX(float newX){this.x = newX;}
public void setY(float newY){this.y = newY;}
public void onDraw(Canvas canvas)
{
canvas.drawBitmap(this.bmp,x,y,null);
}
public boolean isCollition(float x2, float y2) {
return x2 > this.x && x2 < this.x + this.width && y2 > this.y && y2 < this.y + this.height;
}
}
activity_main.xml (The main view for landscape)
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
tools:context="com.example.sammuzero.aplicamesta.MainActivity">
<RelativeLayout
android:layout_width="304dp"
android:layout_height="439dp"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:weightSum="1"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp">
<view
android:id="#+id/game"
class="com.example.sammuzero.aplicamesta.MyView"
id="#+id/view4"
layout_width="match_parent"
android:layout_width="match_parent"
android:layout_height="356dp"
android:gravity="center" />
<SeekBar
android:id="#+id/zoom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center"
android:max="150"
android:min="25"
android:progress="100" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp">
<Button
android:id="#+id/exit"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Salir" />
<Button
android:id="#+id/gatos"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Gatos" />
<Button
android:id="#+id/reinicio"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Repetir" />
<ImageButton
android:id="#+id/nextTurn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:srcCompat="#android:drawable/ic_media_play" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
The main activity in java:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
MyView elJuego;
Button salida;
Button reset;
Button nextTurn;
SeekBar escal;
Bitmap piso1;
Bitmap muro;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
salida = (Button) findViewById(R.id.exit);
reset = (Button) findViewById(R.id.reinicio);
elJuego = (MyView) findViewById(R.id.game);
escal = (SeekBar) findViewById(R.id.zoom);
salida.setOnClickListener(this);
reset.setOnClickListener(this);
escal.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
progressChanged = progress;
elJuego.setEscala(progressChanged);
}
public void onStartTrackingTouch(SeekBar seekBar) {}
public void onStopTrackingTouch(SeekBar seekBar) {}
});
piso1 = BitmapFactory.decodeResource(getResources(), R.drawable.floor1);
muro = BitmapFactory.decodeResource(getResources(), R.drawable.pared);
}
#Override
public void onClick(View v)
{
switch(v.getId())
{
case R.id.exit:
finish();
System.exit(0);
break;
case R.id.reinicio:
elJuego.invalidate();
Terreno nuevo = new Terreno(2,2,new MapBit(piso1) , new MapBit(muro));
elJuego.queTerrenoDibujo(nuevo);
default: break;
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
}

How to add a value to a textView on android

I'm working on an android app where I need to display my phone's accelerometer values (X, Y,Z) into textviews. I tried to display it on toast and it worked but couldn't do it for textviews.
here's my code:
/// This for my main page:
package com.sourcey.materiallogindemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainAccelerometer extends Activity implements AccelerometerListener{
private TextView mTxtViewX;
private TextView mTxtViewY;
private TextView mTxtViewZ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_accelerometer);
mTxtViewX = (TextView) findViewById(R.id.textX);
mTxtViewY = (TextView) findViewById(R.id.textY);
mTxtViewZ = (TextView) findViewById(R.id.textZ);
Intent intent = getIntent();
// Check onResume Method to start accelerometer listener
}
public void onAccelerationChanged(float x, float y, float z) {
// TODO Auto-generated method stub
}
public void onShake(float force) {
// Called when Motion Detected
Toast.makeText(getBaseContext(), "Motion detected",
Toast.LENGTH_LONG).show();
}
#Override
public void onResume() {
super.onResume();
Toast.makeText(getBaseContext(), "onResume Accelerometer Started",
Toast.LENGTH_LONG).show();
//Check device supported Accelerometer senssor or not
if (AccelerometerManager.isSupported(this)) {
//Start Accelerometer Listening
AccelerometerManager.startListening(this);
}
}
#Override
public void onStop() {
super.onStop();
//Check device supported Accelerometer senssor or not
if (AccelerometerManager.isListening()) {
//Start Accelerometer Listening
AccelerometerManager.stopListening();
Toast.makeText(getBaseContext(), "onStop Accelerometer Stoped",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i("Sensor", "Service distroy");
//Check device supported Accelerometer senssor or not
if (AccelerometerManager.isListening()) {
//Start Accelerometer Listening
AccelerometerManager.stopListening();
Toast.makeText(getBaseContext(), "onDestroy Accelerometer Stoped",
Toast.LENGTH_LONG).show();
}
}
}
and this is my AccelerometerManager Activity where I want to do the display
import android.content.Context;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class AccelerometerManager {
static Context aContext=null;
/** Accuracy configuration */
private static float threshold = 15.0f;
private static int interval = 200;
private static Sensor sensor;
private static SensorManager sensorManager;
// you could use an OrientationListener array instead
// if you plans to use more than one listener
private static AccelerometerListener listener;
/** indicates whether or not Accelerometer Sensor is supported */
private static Boolean supported;
/** indicates whether or not Accelerometer Sensor is running */
private static boolean running = false;
/**
* Returns true if the manager is listening to orientation changes
*/
public static boolean isListening() {
return running;
}
/**
* Unregisters listeners
*/
public static void stopListening() {
running = false;
try {
if (sensorManager != null && sensorEventListener != null) {
sensorManager.unregisterListener(sensorEventListener);
}
} catch (Exception e) {}
}
/**
* Returns true if at least one Accelerometer sensor is available
*/
public static boolean isSupported(Context context) {
aContext = context;
if (supported == null) {
if (aContext != null) {
sensorManager = (SensorManager) aContext.
getSystemService(Context.SENSOR_SERVICE);
// Get all sensors in device
List<Sensor> sensors = sensorManager.getSensorList(
Sensor.TYPE_ACCELEROMETER);
supported = new Boolean(sensors.size() > 0);
} else {
supported = Boolean.FALSE;
}
}
return supported;
}
/**
* Configure the listener for shaking
* #param threshold
* minimum acceleration variation for considering shaking
* #param interval
* minimum interval between to shake events
*/
public static void configure(int threshold, int interval) {
AccelerometerManager.threshold = threshold;
AccelerometerManager.interval = interval;
}
/**
* Registers a listener and start listening
* #param accelerometerListener
* callback for accelerometer events
*/
public static void startListening( AccelerometerListener accelerometerListener )
{
sensorManager = (SensorManager) aContext.
getSystemService(Context.SENSOR_SERVICE);
// Take all sensors in device
List<Sensor> sensors = sensorManager.getSensorList(
Sensor.TYPE_ACCELEROMETER);
if (sensors.size() > 0) {
sensor = sensors.get(0);
// Register Accelerometer Listener
running = sensorManager.registerListener(
sensorEventListener, sensor,
SensorManager.SENSOR_DELAY_GAME);
listener = accelerometerListener;
}
}
/**
* Configures threshold and interval
* And registers a listener and start listening
* #param accelerometerListener
* callback for accelerometer events
* #param threshold
* minimum acceleration variation for considering shaking
* #param interval
* minimum interval between to shake events
*/
public static void startListening(
AccelerometerListener accelerometerListener,
int threshold, int interval) {
configure(threshold, interval);
startListening(accelerometerListener);
}
/**
* The listener that listen to events from the accelerometer listener
*/
private static SensorEventListener sensorEventListener =
new SensorEventListener() {
private long now = 0;
private long timeDiff = 0;
private long lastUpdate = 0;
private long lastShake = 0;
private float x = 0;
private float y = 0;
private float z = 0;
private float lastX = 0;
private float lastY = 0;
private float lastZ = 0;
private float force = 0;
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
public void onSensorChanged(SensorEvent event) {
// use the event timestamp as reference
// so the manager precision won't depends
// on the AccelerometerListener implementation
// processing time
now = event.timestamp;
x = event.values[0];
y = event.values[1];
z = event.values[2];
// if not interesting in shake events
// just remove the whole if then else block
if (lastUpdate == 0) {
lastUpdate = now;
lastShake = now;
lastX = x;
lastY = y;
lastZ = z;
Toast.makeText(aContext, "No Motion detected", Toast.LENGTH_SHORT).show();
} else {
timeDiff = now - lastUpdate;
if (timeDiff > 0) {
/*force = Math.abs(x + y + z - lastX - lastY - lastZ)
/ timeDiff;*/
force = Math.abs(x + y + z - lastX - lastY - lastZ);
if (Float.compare(force, threshold) >0 ) {
//Toast.makeText(Accelerometer.getContext(), (now-lastShake)+" >= "+interval, 1000).show();
if (now - lastShake >= interval) {
// trigger shake event
listener.onShake(force);
// AXE X
String sx= String.valueOf(x);
Toast toast1=Toast.makeText(aContext,"X="+sx, Toast.LENGTH_SHORT);
TextView mTxtViewX = (TextView) toast1.getView().findViewById(android.R.id.message);
mTxtViewX.setTextColor(Color.GREEN);
//toast1.show();
mTxtViewX.setText(sx);
// AXE Y
String sy= String.valueOf(y);
Toast toast2= Toast.makeText(aContext,"Y="+ sy, Toast.LENGTH_SHORT);
TextView mTxtViewY = (TextView) toast2.getView().findViewById(android.R.id.message);
mTxtViewY.setTextColor(Color.RED);
//toast2.show();
mTxtViewY.setText(sy);
// AXE Z
String sz= String.valueOf(z);
Toast toast3= Toast.makeText(aContext, "Z=" + sz, Toast.LENGTH_SHORT);
TextView mTxtViewZ = (TextView) toast3.getView().findViewById(android.R.id.message);
mTxtViewZ.setTextColor(Color.BLACK);
//toast3.show();
mTxtViewZ.setText(sz);
}
else
{
Toast.makeText(aContext,"No Motion detected", Toast.LENGTH_SHORT).show();
}
lastShake = now;
}
lastX = x;
lastY = y;
lastZ = z;
lastUpdate = now;
}
else
{
Toast.makeText(aContext,"No Motion detected", Toast.LENGTH_SHORT).show();
}
}
// trigger change event
listener.onAccelerationChanged(x, y, z);
}
};
}
and this is my xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainAccelerometer" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/primary_dark"
android:text="Shake/Tilt Your Phone To Get Accelerometer Motion Alerts"
android:id="#+id/textView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true" />
<TextView android:id="#+id/textX"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="12dp"
android:background="#color/base"
android:gravity="center"
android:textSize="16dip"
android:layout_above="#+id/textY"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView android:id="#+id/textY"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="12dp"
android:background="#color/abc_search_url_text_normal"
android:gravity="center"
android:textSize="16dip"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="166dp" />
<TextView android:id="#+id/textZ"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="12dp"
android:background="#color/accent_material_dark"
android:gravity="center"
android:textSize="16dip"
android:layout_above="#+id/textX"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
You could try to update the TextViews in
public void onAccelerationChanged(float x, float y, float z) {
// TODO Auto-generated method stub
}
You are using the wrong Ids in when finding your view
android.R.id.message
Use the Id you set on your xml.
textX
textY
textZ
use this to display String in TextView
mTxtViewX.setText("text to be displayed");
mTxtViewY.setText("text to be displayed");
mTxtViewZ.setText("text to be displayed");
Warning check that all TextView has correct reference attached to them in findViewById
You have to find the correct textview like this:
TextView mTxtViewX = (TextView) ((MainActivity)aContext).findViewById(R.id.textX);

Game score in Android (java)

So I'm doing an Android game for an assignment resit. This is not my first app but it is my first game. I've never been that much of an expert and quite frankly this is hard for me. I hope someone here can help.
I actually have two problems to add a score (I sincerely hope it's not too much). The thing is, I want to display it in a TextView. When the Sprite "bad" is hit, I want the score to increase by 1.
My first problem is that said TextView doesn't appear on my activity even when I'm not putting anything else than text in it. I tried to put it in LinearLayout, or change some parameters for its position, but I didn't find any other helpful thing on internet.
My second problem is for the score, which even if I can't see it, probably doesn't work. I found some helps saying to put a JPanel or JLabel but I don't think this is what I need. I tried a simple thing where I just made it an int that increases in the isHit and then displays it on the page. But it doesn't display anything, and the program took the bad habit of crashing before I can't even do anything when I have these written in the code.
I don't actually know which other page would be useful, so here is my GameView.java, if any other might be needed, please tell me.
package com.example.proprietaire.assignmentna2;
import com.example.proprietaire.assignmentna2.R;
import com.example.proprietaire.assignmentna2.Sprite;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class GameView extends SurfaceView implements Runnable {
private SurfaceHolder holder;
private int x = 0, xSpeed = 1;
private Bitmap bmp;
Thread thread = null;
volatile boolean running = false;
static final long FPS = 10;
private long lastClick;
private List<Sprite> sprites = new ArrayList<Sprite>();
private List<Sprite> sprites2 = new ArrayList<Sprite>();
private List<TempSprite> temps = new ArrayList<TempSprite>();
private Bitmap bmpSmoke;
int score = 0;
public GameView(Context context) {
super(context);
thread = new Thread(this);
holder = getHolder();
holder.addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
running = false;
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
createSprites();
running = true;
thread.start();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
bmpSmoke = BitmapFactory.decodeResource(getResources(), R.drawable.smoke);
}
private void createSprites() {
sprites.add(createSprite(R.drawable.bad));
sprites2.add(createSprite(R.drawable.good));
}
private Sprite createSprite(int resource) {
bmp = BitmapFactory.decodeResource(getResources(), resource);
return new Sprite(this, bmp);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
for (int i = temps.size() - 1; i>= 0; i--) {
temps.get(i).onDraw(canvas);
}
for (Sprite sprite : sprites) {
sprite.onDraw(canvas);
}
for (Sprite sprite : sprites2) {
sprite.onDraw(canvas);
}
}
#Override
public void run() {
long ticksPS = 1000 / FPS;
long startTime;
long sleepTime;
while (running) {
Canvas c = null;
startTime = System.currentTimeMillis();
try {
c = getHolder().lockCanvas();
synchronized (getHolder()) {
onDraw(c);
}
} finally {
if (c != null) {
getHolder().unlockCanvasAndPost(c);
}
}
sleepTime = ticksPS - (System.currentTimeMillis() - startTime);
try {
if (sleepTime > 0)
thread.sleep(sleepTime);
else
thread.sleep(10);
} catch (Exception e) {
}
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (System.currentTimeMillis() - lastClick> 300) {
lastClick = System.currentTimeMillis();
float x = event.getX();
float y = event.getY();
synchronized (getHolder()) {
for (int i = sprites.size() - 1; i >= 0; i--) {
Sprite sprite = sprites.get(i);
if (sprite.isHit(event.getX(), event.getY())) {
sprites.remove(sprite);
temps.add(new TempSprite(temps, this, x, y, bmpSmoke));
sprites.add(createSprite(R.drawable.bad));
sprites.add(createSprite(R.drawable.bad));
sprites2.add(createSprite(R.drawable.good));
score++;
break;
}
//TextView textView = (TextView)findViewById(R.id.textView);
//String s = "" + score;
//textView.setText((new Integer(score)).toString(Integer.parseInt(s)));
}
}
}
return true;
}
}
Here is GameActivity.java
package com.example.proprietaire.assignmentna2;
import android.app.Activity;
import android.os.Bundle;
public class GameActivity extends Activity {
GameView GV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GV = new GameView(this);
setContentView(GV);
}
}
The xml for the game is a simple TextView without any special thing added.
Thank you in advance.
I just checked some of my old code when I was making my own game, I made a dummy .xml file with nothing but a RelativeLayout in it. So your `GameActivity would look something like this:
private TextView tv;
private GameView gv;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dummyXml);
initializeGameView();
}
From this point on, you can play around with your GameView and your TextView. I will give an example of the start:
private void initializeGameView(){
RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl_dummy_xml);
LinearLayout ll = new LinearLayout(this);
//Layout stuff
ll.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
ll.setOrientation(LinearLayout.VERTICAL);
ll.setGravity(Gravity.CENTER_HORIZONTAL);
//add more stuff, play around with whatever you want to do here
gv = new GameView();
ll.addView(gv);
tv = new TextView(this);
tv.setText(gv.getScore());
ll.addView(tv);
//Finally, don't forget to add the linear layout to the relative layout
rl.addView(ll);
}
Add a getScore() method to your GameView class or alternatively in a more elegant location :P
If you still have questions (after you've tried and tried and tried), feel free to ask ahead! =)
EDIT:
Updated code example with init of the TextView tv. If you want to update the textview you added at any point, add a method toughly similar to this one:
public void updateTextViewScore(){
tv.setText(gv.getScore());
}
I made the GameView and TextView variables global, therefore you can access them in any method you wish.
You probably want to call this method (thus update the textview) inside the game loop e.g. whenever the score changes.
Good luck! Hope this clears it up a bit.

Categories