im having a trouble while i call acce variable of this class
public class Slider extends AppCompatActivity {
...
public double[] acce={3.00,2.00,1.00};
public double[] gyro={3.00,2.00,1.00};
#Override
protected void onCreate(Bundle savedInstanceState) {
...
accelerometer = new Accelerometer(this);
gyroscope = new Gyroscope(this);
accelerometer.setListner(new Accelerometer.Listner() {
#Override
public double[] onTranslation(float ax, float ay, float az) {
acce = setAccValue(ax,ay,az);
return acce;
}
...
}
from this class
public void AntremanSayfasi(Context context){
...
Slider slider = new Slider();
AntremanaBasla.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aa = (float) slider.acce[0];
bb = (float) slider.acce[1];
cc = (float) slider.acce[2];
accx.setText(String.valueOf(aa));
accy.setText(String.valueOf(bb));
accz.setText(String.valueOf(cc));
}
});
}
the problem is... i can get the determined values but cannot get the updated values of sensor change ?
sorry for rooky question, any help will be appritiated
UPDATE
this is the main Class
public class Slider extends AppCompatActivity {
private ViewPager AktifHareket;
private LinearLayout mDotLayout;
private String asd;
private int asdf;
private Antreman antreman;
TextView DenemeSayiCek;
int position;
View view;
int count;
View viewFix;
Context context;
//Sensors-------------------------------------------------------------------------------------------
private Accelerometer accelerometer;
private Gyroscope gyroscope;
public double[] acc={3.00,2.00,1.00};
public double[] gyr={3.00,2.00,1.00};
public double[] acce={5.00,5.00,5.00};
public double[] gyro={3.00,2.00,1.00};
//Sensors---------------------------------------------------------------------------------------
//Main------------------------------------------------------------------------------------------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Antreman antreman = new Antreman();
context = this;
setContentView(R.layout.activity_slider);
Login login = new Login();
AktifHareket = (ViewPager) findViewById(R.id.slideViewPager);
mDotLayout = (LinearLayout) findViewById(R.id.dotsLayout);
SliderAdapter sliderAdapter = new SliderAdapter(this);
AktifHareket.setAdapter((sliderAdapter));
addDotsIndicator();
//Saydir Buton------------------------------------------------------------------------------
TextView Deneme = (TextView) findViewById(R.id.deneme);
TextView Deneme4 = (TextView) findViewById(R.id.deneme4);
TextView Deneme3 = (TextView) findViewById(R.id.deneme3);
TextView Deneme2 = (TextView) findViewById(R.id.deneme2);
Button Saydir = (Button) findViewById(R.id.SaydirSlide);
Button Saydir2 = (Button) findViewById(R.id.Saydir2Slide);
Saydir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
position = AktifHareket.getCurrentItem();
view = AktifHareket.getChildAt(position);
count = Integer.valueOf(AktifHareket.indexOfChild(view));
viewFix = AktifHareket.getChildAt(count);
DenemeSayiCek = (TextView) viewFix.findViewById(R.id.TekrarSayisiSlide);
asd = (String) DenemeSayiCek.getText().toString();
asdf = Integer.valueOf(asd);
asdf++;
DenemeSayiCek.setText(String.valueOf(asdf));
Deneme.setText(Arrays.toString(acce));
Deneme2.setText(String.valueOf(position));
Deneme3.setText(Arrays.toString(acce));
Deneme4.setText(String.valueOf(SliderAdapter.POSITION_NONE));
}
});
//Saydir Buton------------------------------------------------------------------------------
//ImageButton-------------------------------------------------------------------------------
ImageView logoImage = (ImageView) findViewById(R.id.logo);
logoImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
antreman.AntremanSayfasi(context);
}
});
antreman.AntremanSayfasi(context);//Açılışta Sayfayı açsın diye
//ImageButton-------------------------------------------------------------------------------
//Sensors-----------------------------------------------------------------------------------
accelerometer = new Accelerometer(this);
gyroscope = new Gyroscope(this);
accelerometer.setListner(new Accelerometer.Listner() {
#Override
public double[] onTranslation(float ax, float ay, float az) {
acce = setAccValue(ax,ay,az);
Antreman.SensorValues.accValues=acce;
return acce;
}
});
gyroscope.setListner(new Gyroscope.Listner() {
#Override
public void onRotation(float gx, float gy, float gz) {
setGyroValue(gx,gy,gz);
}
});
//Sensors-----------------------------------------------------------------------------------
}
//Sensors---------------------------------------------------------------------------------------
protected void onResume(){
super.onResume();
accelerometer.register();
gyroscope.register();
}
protected void onPouse(){
super.onPause();
accelerometer.unregister();
gyroscope.unregister();
}
public double[] setAccValue(double ac, double bc, double cc){
this.acc[0] = ac;
this.acc[1] = bc;
this.acc[2] = cc;
return acc;
}
public double[] setGyroValue(float qq, float wq, float eq){
this.gyr[0] = qq;
this.gyr[1] = wq;
this.gyr[2] = eq;
return gyr;
}
public void getAccValue(double ac, double bc, double cc){
ac = (float) acce[0];
bc = (float) acce[1];
cc = (float) acce[2];
}
public void getGyroValue(float qq, float wq, float eq){
qq = (float) gyro[0];
wq = (float) gyro[1];
eq = (float) gyro[2];
}
//Sensors---------------------------------------------------------------------------------------
public void addDotsIndicator(){
TextView[] mDots = new TextView[3];
for(int i = 0; i < mDots.length; i++){
mDots[i] = new TextView(this);
mDots[i].setText(Html.fromHtml("•"));
mDots[i].setTextSize(35);
mDots[i].setTextColor(getResources().getColor(R.color.colorPrimaryDark));
mDotLayout.addView(mDots[i]);
}
}
//----------------------------------------------------------------------------------------------
}
ant this is the class i need to initialize those values from the main class
public class Antreman {
private Accelerometer accelerometer;
private Gyroscope gyroscope;
public double aa;
public float bb;
public float cc;
public float qq;
public float ww;
public float ee;
//Pop up----------------------------------------------------------------------------------------
public void AntremanSayfasi(Context context){
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
final View popup_durum = li.inflate(R.layout.popup_durum,null);
Button AntremanaBasla = popup_durum.findViewById(R.id.basla);
Button Cikis = popup_durum.findViewById(R.id.cikis);
dialogBuilder.setView(popup_durum);
AlertDialog dialog = dialogBuilder.create();
dialog.show();
TextView gyrox = (TextView) popup_durum.findViewById(R.id.gyrox);
AntremanaBasla.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aa = SensorValues.accValues[0];
gyrox.setText(String.valueOf(aa));
}
});
Cikis.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
static class SensorValues{
public static double[] accValues = {1.00};
}
}
you can use the concept of common class in this case and I believe it will solve your problem quite easily. Follow to steps below.
Make a public class and declare an array of double inside it which you need to access in another class
Public class Common{
public static List<double> acce;
}
and in your activity where the sensors give updated value use a temp list
and assign it to Common.acce;
Common.acce = tempList;
Now, when you need to access acce just use Common.acce, and the reference of tempList is in the Common.acce and when the data in tempList will be updated by your sensor the list in common will be also updated, so ultimately you will get the updated value.
Feel free to ask if something is unclear. And Kindly mark it as the correct answer if it helps you so that in future this answer can help other needy. Happy Coding 😀.
Related
I am facing issue while subtracting my product, I am using three buttons to get the value of the selected one and then multiply these value for add more product or subtract . But when i click on subtract button it will minus the whole amount. So please help me in this. Below mention is my code. If you want some more info then please ask me.
public class ShowDetailActivity extends AppCompatActivity {
private TextView addToCardBtn;
private TextView titleTxt, feeTxt, descriptionTxt, numberOrderTxt;
private ImageView plusBtn, minusBtn, picFood, priceBtn, mediumPriceBtn, largePriceBtn;
private ProductsDomain object;
private int numberOrder = 1;
private ManagementCart managementCart;
private LinearLayout cheese_ll;
private LinearLayout scale_ll;
private int itemPrice;
private CheckBox cheeseBoxyes;
private int price;
private int checkvalue;
private int uncheckValue;
private boolean cheeseBoolean = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_detail);
managementCart = new ManagementCart(this);
initView();
getBundle();
//Button Code
price=object.getPrice();
priceBtn.setOnClickListener(this::onClick);
mediumPriceBtn.setOnClickListener(this::onClick);
largePriceBtn.setOnClickListener(this::onClick);
//check box code for extra cheese
}
private void onClick(View view) {
int id=view.getId();
switch (id){
case R.id.smallPriceBtn:
price=object.getPrice();
itemPrice=object.getPrice();
feeTxt.setText(Integer.toString(price*numberOrder));
break;
case R.id.mediumPriceBtn:
price = object.getMediumPrice();
feeTxt.setText(Integer.toString(price*numberOrder));
itemPrice=object.getMediumPrice();
break;
case R.id.largePriceBtn:
price = object.getLargePrice();
feeTxt.setText(Integer.toString(price*numberOrder));
itemPrice=object.getLargePrice();
break;
}
}
private void getBundle() {
object = (ProductsDomain) getIntent().getSerializableExtra("object");
if (object.getWithCheese() == 1)//get cheese
{
cheese_ll.setVisibility(View.VISIBLE);
scale_ll.setVisibility(View.GONE);
} else {
cheese_ll.setVisibility(View.GONE);
scale_ll.setVisibility(View.VISIBLE);
}
Glide.with(this).load("http://192.168.100.215/pizzaVill/Images/" + object.getImage()).into(picFood);
titleTxt.setText(object.getName());
descriptionTxt.setText(object.getDescription());
numberOrderTxt.setText(Integer.toString(numberOrder));
feeTxt.setText(Integer.toString(object.getPrice()));
plusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
numberOrder = numberOrder + 1;
numberOrderTxt.setText(Integer.toString(numberOrder));
feeTxt.setText(Integer.toString(numberOrder * price));
//Code if there is no size required
}
});
minusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (numberOrder > 1) {
numberOrder = numberOrder - 1;
}
numberOrderTxt.setText(Integer.toString(numberOrder));
feeTxt.setText(Integer.toString(price - itemPrice));
}
});
addToCardBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
object.setNumberInCard(numberOrder);
object.setFinalPrice(price);
managementCart.insertFood(object);
}
});
}
private void initView() {
addToCardBtn = findViewById(R.id.addToCardBtn);
titleTxt = findViewById(R.id.titleTxt);
feeTxt = findViewById(R.id.priceTxt);
descriptionTxt = findViewById(R.id.descriptionTxt);
numberOrderTxt = findViewById(R.id.numberOrderTxt);
plusBtn = findViewById(R.id.plusBtn);
minusBtn = findViewById(R.id.minusBtn);
picFood = findViewById(R.id.foodPic);
priceBtn = findViewById(R.id.smallPriceBtn);
mediumPriceBtn = findViewById(R.id.mediumPriceBtn);
largePriceBtn = findViewById(R.id.largePriceBtn);
cheese_ll = findViewById(R.id.cheese_ll);
scale_ll = findViewById(R.id.scale_ll);
cheeseBoxyes = findViewById(R.id.cheeseBoxyes);
}
I want that after click to TextView show animation after that (after animation) show some modal window. How I may do this? P.s. My animation contained in XML file in <animation-list>
public class ExerciseWithExplain1 extends AppCompatActivity {
private Button solution;
private TextView txtVWRed, explainForTable, solExplain, nextScreen, falseRow53, falseRow54, falseRow55, falseRow56, falseRow46, trueRow45, trueRow44, falseRow43, trueRow36, trueRow35, falseRow34, trueRow33, trueRow23, falseRow23, trueRow25, trueRow24, falseRow24, falseRow25, falseRow26, falseRow33, trueRow34, falseRow35, falseRow36, trueRow43, falseRow44, falseRow45, trueRow46, trueRow53, trueRow54, trueRow55, trueRow56, trueRow26;
LinearLayout layForTable;
AlertDialog.Builder ad;
Context context;
AnimationDrawable animationDrawable;
ImageView animImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exercise_with_explain1);
trueRow23 = findViewById(R.id.trueRow23);
falseRow23 = findViewById(R.id.falseRow23);
falseRow24 = findViewById(R.id.falseRow24);
trueRow24 = findViewById(R.id.trueRow24);
trueRow25 = findViewById(R.id.trueRow25);
falseRow25 = findViewById(R.id.falseRow25);
trueRow26 = findViewById(R.id.trueRow26);
falseRow26 = findViewById(R.id.falseRow26);
falseRow33 = findViewById(R.id.falseRow33);
trueRow33 = findViewById(R.id.trueRow33);
trueRow34 = findViewById(R.id.trueRow34);
falseRow34 = findViewById(R.id.falseRow34);
falseRow35 = findViewById(R.id.falseRow35);
trueRow35 = findViewById(R.id.trueRow35);
falseRow36 = findViewById(R.id.falseRow36);
trueRow36 = findViewById(R.id.trueRow36);
trueRow43 = findViewById(R.id.trueRow43);
falseRow44 = findViewById(R.id.falseRow44);
falseRow45 = findViewById(R.id.falseRow45);
falseRow43 = findViewById(R.id.falseRow43);
trueRow44 = findViewById(R.id.trueRow44);
trueRow45 = findViewById(R.id.trueRow45);
trueRow46 = findViewById(R.id.trueRow46);
falseRow46 = findViewById(R.id.falseRow46);
trueRow53 = findViewById(R.id.trueRow53);
trueRow54 = findViewById(R.id.trueRow54);
trueRow55 = findViewById(R.id.trueRow55);
trueRow56 =findViewById(R.id.trueRow56);
falseRow53 = findViewById(R.id.falseRow53);
falseRow54 = findViewById(R.id.falseRow54);
falseRow55 = findViewById(R.id.falseRow55);
falseRow56 =findViewById(R.id.falseRow56);
animImage = findViewById(R.id.animImage);
animImage.setBackgroundResource(R.drawable.question_mark);
animationDrawable = (AnimationDrawable) animImage.getBackground();
context = ExerciseWithExplain1.this;
ad = new AlertDialog.Builder(context);
ad.setTitle(R.string.explainLogic);
ad.setMessage(R.string.logicForAnd);
final int ir = 0;
falseRow56.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
animImage.setVisibility(View.VISIBLE);
animationDrawable.start();
ad.show();
}
});
trueRow56.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
animImage.setVisibility(View.VISIBLE);
animationDrawable.start();
}
});
falseRow55.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
animImage.setVisibility(View.VISIBLE);
animationDrawable.start();
}
});
You can Try it by using Custom AnimationDrwable
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
public abstract class CustomAnimationDrawableNew extends AnimationDrawable {
/** Handles the animation callback. */
Handler mAnimationHandler;
public CustomAnimationDrawableNew(AnimationDrawable aniDrawable) {
/* Add each frame to our animation drawable */
for (int i = 0; i < aniDrawable.getNumberOfFrames(); i++) {
this.addFrame(aniDrawable.getFrame(i), aniDrawable.getDuration(i));
}
}
#Override
public void start() {
super.start();
/*
* Call super.start() to call the base class start animation method.
* Then add a handler to call onAnimationFinish() when the total
* duration for the animation has passed
*/
mAnimationHandler = new Handler();
mAnimationHandler.post(new Runnable() {
#Override
public void run() {
onAnimationStart();
}
});
mAnimationHandler.postDelayed(new Runnable() {
#Override
public void run() {
onAnimationFinish();
}
}, getTotalDuration());
}
/**
* Gets the total duration of all frames.
*
* #return The total duration.
*/
public int getTotalDuration() {
int iDuration = 0;
for (int i = 0; i < this.getNumberOfFrames(); i++) {
iDuration += this.getDuration(i);
}
return iDuration;
}
/**
* Called when the animation finishes.
*/
public abstract void onAnimationFinish();
/**
* Called when the animation starts.
*/
public abstract void onAnimationStart();
}
Now Use it like this code.
TextView tv = (TextView) findViewById(R.id.iv_testing_testani);
tv.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
// Pass our animation drawable to our custom drawable class
CustomAnimationDrawableNew cad = new CustomAnimationDrawableNew(
(AnimationDrawable) getResources().getDrawable(
R.drawable.anim_test)) {
#Override
void onAnimationStart() {
// Animation has started...
}
#Override
void onAnimationFinish() {
// Animation has finished...
}
};
// Set the views drawable to our custom drawable
v.setBackgroundDrawable(cad);
// Start the animation
cad.start();
}
});
I want make a Dice game, i have use a github project (https://github.com/dylanmtaylor/Simple-Dice).
The MainActivity is available here : https://github.com/dylanmtaylor/Simple-Dice/blob/master/src/com/dylantaylor/simpledice/RollDice.java
I want to get the value of the dice
Exemple :
If the first dice is 1 and the second is 6 we have a total of 7 i want make an action.
I have make a button who change a textview, this button try to get the number of the dices.
TextView hwTextView = (TextView)findViewById(R.id.textView8);
hwTextView.setText(String.valueOf(diceSum));
I have try to get the value "diceSum", "diceImages", "dice", "dice[roll[0]", "dice[roll[1]" but that didn't show a number.
How can i do try to get the value of the dice ?
My MainActivity
public class dices extends AppCompatActivity {
Button button;
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 = 800;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
paused = false;
setContentView(R.layout.activity_dixit);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.setStatusBarColor(Color.parseColor("#2c3e50"));
}
View view = this.getWindow().getDecorView();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
button=(Button)findViewById(R.id.button_roll);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rollDice();
TextView hwTextView = (TextView)findViewById(R.id.textView8);
hwTextView.setText(String.valueOf(diceSum));
}
});
res = getResources();
for (int i = 0; i < 6; i++) {
dice[i] = res.getDrawable(diceImages[i]);
}
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]]);
}
};
}
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;
}
}
I didn't understand why your code didn't work. I myself making a very small games based on "Scarne's dice game(pig)" and myself facing the challenge of retrieving the value of dice rolled. Mind, I am just using one die. This is what I did:
int userScore;
private int[] diceArray = {R.drawable.d1, R.drawable.d2, R.drawable.d3,
R.drawable.d4,R.drawable.d5,R.drawable.d6};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onRollBtnClicked() {
ImageView diceFace = (ImageView) findViewById(R.id.diceFaceImageView);
userScore = randomIntegerGenerator(1,6); // this is what you need
diceFace.setImageResource(diceArray[userScore]);
}
// function to return random integer from min to max
public int randomIntegerGenerator(int min, int max) {
return random.nextInt((max - min) + 1) + min;
}
I am storing my rolled die value in userScore. You can use the similar approach.
Problem: My Calculations are off when I compared the results on my app to the bmi website. THank you so much in advance, also my math is really bad so I apologize in advance.
Here are the results that my app is giving me:
http://www.tiikoni.com/tis/view/?id=8bd04d4
Here are the results based of the BMI Website NIH
http://www.tiikoni.com/tis/view/?id=86d4458
BMIFRAG.java
public class BmiFrag extends Fragment implements View.OnClickListener
{
Button BmiButton;
public static EditText heightFT;
public static EditText heightIn;
public static EditText weightIn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_bmi, container,
false);
BmiButton = (Button) myView.findViewById(R.id.CalculateBmi);
BmiButton.setOnClickListener(this);
return myView;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.CalculateBmi:
weightIn = (EditText)
getActivity().findViewById(R.id.ETtweight);
heightIn = (EditText)
getActivity().findViewById(R.id.ETHeightIn);
heightFT = (EditText)
getActivity().findViewById(R.id.ETHeightFT);
final TextView tv4 = (TextView)
getActivity().findViewById(R.id.TFDisplayBmi);
String getWeightIN = weightIn.getText().toString();
String getHeightIN = heightIn.getText().toString();
String getHeightFT = heightFT.getText().toString();
if (TextUtils.isEmpty(getWeightIN)) {
weightIn.setError("Please enter your weight");
weightIn.requestFocus();
return;
}
else if (TextUtils.isEmpty(getHeightIN)) {
heightIn.setError("Please enter your height in Inches");
heightIn.requestFocus();
return;
}
else if (TextUtils.isEmpty(getHeightFT)) {
heightFT.setError("Please enter your height in Feet");
heightFT.requestFocus();
return;
}
else {
float weight = Float.parseFloat(getWeightIN );
float heightIN = Float.parseFloat(getHeightIN) ;
float heightFT = Float.parseFloat(getHeightFT) ;
float bmiValue = calculateBMI(weight,heightIN,heightFT);
String bmiInterpretation = interpretBMI(bmiValue);
tv4.setText(String.valueOf(bmiValue + "-" +
bmiInterpretation));
}
break;
}
}
private float calculateBMI(float weight, float heightIN, float v) {
float bmi= (float) (weight/ (heightIN*v)*4.88);
float total= Math.round(bmi);
return total;
}
private String interpretBMI(float bmiValue) {
if (bmiValue < 16) {
return "Severely underweight";
} else if (bmiValue < 18.5) {
return "Underweight";
} else if (bmiValue < 25) {
return "Normal";
} else if (bmiValue < 30) {
return "Overweight";
} else {
return "Obese";
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
You don't use the same formula. Try this:
float bmi = weight * 703f / (float)Math.pow(heightIN+12f*v,2);
The formula above can be found here.
I hope it helps.
I have this animation activity for falling images. It works perfectly. What I would like to is change this, so I can call something like, startImageFallAnimation(), in another activity, and have it show over the current activity. I'd hate to have to add all this code to every activity I want to use it in. I experimented for a few hours, with no luck.
How can I accomplish this?
import com.tmp.animation.R;
public class FallAnimationActivity extends Activity {
// 100 = lots falling / 1000 = less falling
public int imageInterval = 100;
private int[] LEAVES = {
R.drawable.coin,
R.drawable.starsm,
//R.drawable.leaf_yellow,
//R.drawable.leaf_other,
};
private Rect mDisplaySize = new Rect();
private RelativeLayout mRootLayout;
private ArrayList<View> mAllImageViews = new ArrayList<View>();
private float mScale;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Display display = getWindowManager().getDefaultDisplay();
display.getRectSize(mDisplaySize);
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
mScale = metrics.density;
mRootLayout = (RelativeLayout) findViewById(R.id.main_layout);
new Timer().schedule(new ExeTimerTask(), 0, imageInterval);
}
public void create() {
setContentView(R.layout.main);
Display display = getWindowManager().getDefaultDisplay();
display.getRectSize(mDisplaySize);
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
mScale = metrics.density;
mRootLayout = (RelativeLayout) findViewById(R.id.main_layout);
new Timer().schedule(new ExeTimerTask(), 0, imageInterval);
}
public void startAnimation(final ImageView aniView) {
aniView.setPivotX(aniView.getWidth()/2);
aniView.setPivotY(aniView.getHeight()/2);
long delay = new Random().nextInt(Constants.MAX_DELAY);
final ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
animator.setDuration(Constants.ANIM_DURATION);
animator.setInterpolator(new AccelerateInterpolator());
animator.setStartDelay(delay);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
int angle = 50 + (int)(Math.random() * 101);
int movex = new Random().nextInt(mDisplaySize.right);
#Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = ((Float) (animation.getAnimatedValue())).floatValue();
aniView.setRotation(angle*value);
aniView.setTranslationX((movex-40)*value);
aniView.setTranslationY((mDisplaySize.bottom + (150*mScale))*value);
}
});
animator.start();
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int viewId = new Random().nextInt(LEAVES.length);
Drawable d = getResources().getDrawable(LEAVES[viewId]);
LayoutInflater inflate = LayoutInflater.from(FallAnimationActivity.this);
ImageView imageView = (ImageView) inflate.inflate(R.layout.ani_image_view, null);
imageView.setImageDrawable(d);
mRootLayout.addView(imageView);
mAllImageViews.add(imageView);
LayoutParams animationLayout = (LayoutParams) imageView.getLayoutParams();
animationLayout.setMargins(0, (int)(-150*mScale), 0, 0);
animationLayout.width = (int) (60*mScale);
animationLayout.height = (int) (60*mScale);
startAnimation(imageView);
}
};
private class ExeTimerTask extends TimerTask {
#Override
public void run() {
// we don't really use the message 'what' but we have to specify something.
mHandler.sendEmptyMessage(Constants.EMPTY_MESSAGE_WHAT);
}
}
}
EDIT- After lots of work, this is the best I've got, but I cant solve passing context into the handler, or passing the layout into the first method.
import com.tmp.animation.R;
public class FallPop {
private static final String TAG = FallPop.class.toString();
private static final FallPop INSTANCE = new FallPop();
private int[] LEAVES = {
R.drawable.leaf_green,
R.drawable.leaf_red,
R.drawable.leaf_yellow,
R.drawable.leaf_other,
};
private Rect mDisplaySize = new Rect();
private RelativeLayout mRootLayout;
private ArrayList<View> mAllImageViews = new ArrayList<View>();
private float mScale;
private FallPop(){
}
public static FallPop getInstance() {
return INSTANCE;
}
public Context context;
public Context context2;
int count = 0;
public void doAnim(Context context){
WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
display.getRectSize(mDisplaySize);
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
mScale = metrics.density;
// FIX!!!
// mRootLayout = (RelativeLayout) findViewById(R.id.main_layout);
new Timer().schedule(new ExeTimerTask(), 0, 200);
}
public void startAnimation(final ImageView aniView) {
aniView.setPivotX(aniView.getWidth()/2);
aniView.setPivotY(aniView.getHeight()/2);
long delay = new Random().nextInt(Constants.MAX_DELAY);
final ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
animator.setDuration(Constants.ANIM_DURATION);
animator.setInterpolator(new AccelerateInterpolator());
animator.setStartDelay(delay);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
int angle = 50 + (int)(Math.random() * 101);
int movex = new Random().nextInt(mDisplaySize.right);
#Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = ((Float) (animation.getAnimatedValue())).floatValue();
aniView.setRotation(angle*value);
aniView.setTranslationX((movex-40)*value);
aniView.setTranslationY((mDisplaySize.bottom + (150*mScale))*value);
}
});
animator.start();
}
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int viewId = new Random().nextInt(LEAVES.length);
// Need some context here \/
Drawable d = ContextCompat.getDrawable(context, LEAVES[viewId]);
// Original line, also didnt work \/
//Drawable d = getResources().getDrawable(LEAVES[viewId]);
LayoutInflater inflate = LayoutInflater.from(context);
ImageView imageView = (ImageView) inflate.inflate(R.layout.ani_image_view, null);
imageView.setImageDrawable(d);
mRootLayout.addView(imageView);
mAllImageViews.add(imageView);
RelativeLayout.LayoutParams animationLayout = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
animationLayout.setMargins(0, (int) (-150 * mScale), 0, 0);
animationLayout.width = (int) (60 * mScale);
animationLayout.height = (int) (60 * mScale);
startAnimation(imageView);
}
};
class ExeTimerTask extends TimerTask {
#Override
public void run() {
// we don't really use the message 'what' but we have to specify something.
mHandler.sendEmptyMessage(Constants.EMPTY_MESSAGE_WHAT);
}
}
}
Create a Java class with static method startImageFallAnimation(),where you will write all your animation code and just call the method wherever it is required
The quickest solution I can think of would be to make the target Activities extend this class and change the access level of the member variables in FallAnimationActivity to 'protected'. Depending on whether you need this in all/most Activities, I'd put the logic in a base class.
have context as a parameter in your util class
example:
public animation(Imageview imageview, Context mContext)
{
Animation slideLeft = AnimationUtils.loadAnimation(mContext, R.anim.slide_out_left);
imageview.startAnimation(slideLeft);
}
then in the activity you want to call it in do
// for activity
Utils.animation(Your image view, this)
//for fragment
Utils.animation(Your image view, getContext)
my utility class is called Utils, so you type whatever you named the class and call the method accordingly