Spinner's getSelectedItemPosition() method returns unexpected results - android

My app has a spinner with four entries in it. I need to be able to retrieve which of these labels is selected, not the actual labels themselves. Below is my partial code for doing this:
// Set up the activity's Spinner
spinnerAdapter = ArrayAdapter.createFromResource(this, R.array.pay_periods, android.R.layout.simple_spinner_item);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner s = (Spinner) findViewById(R.id.main_spinner_payperiod);
s.setAdapter(spinnerAdapter);
In a later method:
switch(payPeriod.getSelectedItemPosition()){
case(0): // Daily
dailyAllowance = Float.parseFloat(payment.getText().toString());
case(1): // Weekly
dailyAllowance = (Float.parseFloat(payment.getText().toString())) / 7;
case(2): // Bi-weekly
dailyAllowance = (Float.parseFloat(payment.getText().toString())) / 14;
case(3): // 30 days
dailyAllowance = (Float.parseFloat(payment.getText().toString())) / 30;
case(Spinner.INVALID_POSITION):
dailyAllowance = 0;
default:
dailyAllowance = 42; // Junk value, for debugging purposes
}
This method always seems to return 42, no matter which of the Spinner's items I have selected. Can anyone help me figure out why? Thank you!

Put a break in your switch-case condition
switch(payPeriod.getSelectedItemPosition()) {
case(0): // Daily
dailyAllowance = Float.parseFloat(payment.getText().toString());
break;
case(1): // Weekly
dailyAllowance = (Float.parseFloat(payment.getText().toString())) / 7;
break;
case(2): // Bi-weekly
dailyAllowance = (Float.parseFloat(payment.getText().toString())) / 14;
break;
case(3): // 30 days
dailyAllowance = (Float.parseFloat(payment.getText().toString())) / 30;
break;
case(Spinner.INVALID_POSITION):
dailyAllowance = 0;
break;
default:
dailyAllowance = 42; // Junk value, for debugging purposes
break;
}
Omitting break in switch-case condition might give a wrong behavior. If a case (without break) was chosen the flow still continues and the default condition is always executed.

Related

Change Images or Bitmap when ever touched on screen

I want to change the bitmap that contains an image whenever user tap on the screen. i.e. the default image is shadow1, now what i want is that when user touched on screen then this image changed to shadow2, then again if user touched then shadow3, then on next touch the image again comes as shadow1 and it goes on and on and on. so basically there are three images and i want that when ever user touched on screen then image changes with each tap.
Following is the code that i tried but it is still not working as expected i.e. the image changes from shadow1 to shadow2 but then not changes to shadow3 or shadow1 even if i touched many times.
public void Touched(float x, float y)
{
boom = false;
try{
switch (bird.GetState()) {
case 0:
distance = 0;
bird.SetState(1);
flapped = true;
Bitmap workingBitmap = BitmapFactory.decodeResource(gameLogic.Resources(), R.drawable.shadow1);
bitmapBird = workingBitmap.copy(Bitmap.Config.ARGB_8888, false);
if (bitmapBird==workingBitmap)
{
}
riseCounter = 0;
pipeValues.clear();
//SoundManager.playSound(2, 1);
break;
case 1:
{
riseCounter = 0;
flapped = true;
t = 3;
Bitmap workingBitmappp = BitmapFactory.decodeResource(gameLogic.Resources(), R.drawable.shadow2);
bitmapBird = workingBitmappp.copy(Bitmap.Config.ARGB_8888, false);
//SoundManager.playSound(2, 1);
}
break;
case 2:
{
riseCounter = 0;
flapped = true;
t = 0;
}
break;
default:
Bitmap workingBitma = BitmapFactory.decodeResource(gameLogic.Resources(), R.drawable.shadow3);
bitmapBird = workingBitma.copy(Bitmap.Config.ARGB_8888, false);
break;
}
} catch(Exception e){}
}
I think there should be a for loop or while loop in 'case 1' and whenever user tap then image changes. Please help me with this.
You can simply use an int value to keep track of the image displayed as;
First Initialize a int at class level;
int num = 0;
then you can use it as;
if(num == 0){
loadFirstImage();
num++;
}
else if(num == 1)
{
loadSecondImage();
num++;
}
else if(num == 2){
loadThirdImage();
num = 0 ;
}
I think that you need to change the state of the bird in your second case statement.
First iteration will set the state to 1, from there, the only case statement you can hit is case 1: because you never change it.
So you need something like
case 1:
bird.SetState(2);
//....
Hope that helps

For loop not acting as expected

Good night.
I have a for loop to calculate some values along the week, during some weeks. My code compare day of the week with the quantity of days that have passed.
The for only works fine on monday when workday is the same than totdays. The rest of days totact is 0 and the fianl equation become NaN.
int totdias = PrefProteos.getInt("dia",0);
int totact = 0;
float califtot = 0;
int stateday = 0;
float promdias;
float promcalif;
int workdays;
Date day = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("EE", Locale.US);
String dayweek = formatter.format(day);
if (dayweek.equals("Mon")) {
stateday = 1;
}
else if (dayweek.equals("Tue")) {
stateday = 2;
}
else if (dayweek.equals("Wed")) {
stateday = 3;
}
else if (dayweek.equals("Thu")) {
stateday = 4;
}
else if (dayweek.equals("Fri")) {
stateday = 5;
}
else if (dayweek.equals("Sat")) {
stateday = 6;
}
else if (dayweek.equals("Sun")) {
stateday = 7;
}
if (stateday >= totdias) {
workdays = 1;
promdias = totdias;
} else {
workdays = (totdias - (stateday - 1));
promdias = stateday;
}
for (int y = workdays; y == totdias;y++) {
for (int x = 1; x <= 12; x++) {
String activ=PrefProteos.getString("act" + x + "-habit", "");
if (!activ.equals("")) {
float notactiv = PrefProteos.getFloat("act" + x + "-puntdia"+y, 0);
califtot = califtot+notactiv;
totact = totact+1;
}
}
}
promcalif = califtot / (totact * promdias);
You have write your first loop condition wrong, you ask only for to run only if workdays = totdias. I guess you want to loop for each days from workdays to totdias
So correct this block :
for (int y = workdays; y == totdias;y++) {
Into
for (int y = workdays; y <= totdias;y++) {
PS :
Your current loop is like writing
if(workdays == totdias) {
You should provide some more code because we can't understand your PrefProteos class and probably the error is in there.
You should also add the full logcat
And you should tell us which line throws the error.
Anyway there are some errors:
Here
for (int y = workdays;y==totdias;y++){
There is no sense of using an equals condition in a for loop exit condition if both equals condition and looping variable are the same, because it will result in an if loop. This is because the for will work only if workdays == totdias since the beginning, elseway it will not work.
For conditions are:
for(counter = defaultvalue; condition that if true, makes the loop goes on; what to do each loop end)
This means that your code will do:
is y(workdays) == totdias?
if yes, do the loop
add one to y(workdays)
exit because the condition is no more true
if not, don't run the loop
So you simply have to call:
if(y == totdias){
//do code
y++;
}
But probably this is an error, because except for monday, this code will never run! so in others days promdias is not istantiated
In the loop
for (int x = 1; x<=12; x++){
String activ=PrefProteos.getString("act" + x + "-habit", "");
if (!activ.equals("")){
//there must be an error here somewhere
float notactiv=PrefProteos.getFloat("act" + x + "-puntdia"+y, 0);
califtot=califtot+notactiv;
totact=totact+1;
}
}
And this must be throwing an error.
promcalif = califtot/(totact*promdias);
Two options:
promidias or totact are 0. you can't do number/0
As said above, promdias might not be istantiated in other days of the week, because the for loop never run
Btw, float name = 0; is not perfect, change them to float name = 0f;

Randomly Switch Case

Hello friends I have 2 situation but I want to do it randomly. When user click button then there is 2 situation case0 or case1 randomly changes. So text's are randomly changes too...
*lastImageName and lastImageName2 are variable strings...
Random rand = new Random();
int newrand = rand.nextInt(1) + 1;
switch(newrand) {
case 0:
text1.setText(lastImageName);
text2.setText(lastImageName2);
break;
case 1:
text1.setText(lastImageName2);
text2.setText(lastImageName);
break;
}
But that's not working sometimes.. What's the rand. problem?
Random rand = new Random();
int a = 0;
int b = 1;
int c = random.nextBoolean() ? a : b;
Remove the +1. Just do that: int newrand = rand.nextInt(2);
Random#nextInt(int) generates a random number between 0 inclusive and the upper bound exclusive. I.e., nextInt(1) will always return 0. Instead, you should just use:
int newrand = rand.nextInt(2);
If you only have two cases then use
boolean state = rand.nextBoolean();
text1.setText(state?lastImageName:lastImageName2);
text2.setText(state?lastImageName2:lastImageName);
For multiple you can also use
Random rand = new Random();
int newrand = rand.nextInt() % count;//count = 2 for your case
switch(newrand) {
case 0:
text1.setText(lastImageName);
text2.setText(lastImageName2);
break;
case 1:
text1.setText(lastImageName2);
text2.setText(lastImageName);
break;
}

Random number generator with no duplicate

I am having a hard time trying to ensure no duplicates numbers appear in the following code below. I tried to create an ArrayList to add all the possible index of the array and then gradually remove the values of the array from the List as more elements are generated by the number generator. This; however, didnt work as I expected. I've been trying to think about it but Haven't been able to come up with a viable solution.
Random randGen = new Random();
public boolean onTouchEvent(MotionEvent touchevent) {
switch (touchevent.getAction()) {
case MotionEvent.ACTION_DOWN: {
x1 = touchevent.getX();
y1 = touchevent.getY();
break;
}
case MotionEvent.ACTION_UP: {
x2 = touchevent.getX();
y2 = touchevent.getY();
int maxLength=exampleArray.length;
List<Integer>indices=new ArrayList<Integer>(maxLength);
for(int i=0;i<maxLength;i++){
indices.add(i);
}
int randomApple = randGen.nextInt(exampleArray.length);
int randomNum=indices.get(randomApple) ;
indices.remove(randomApple);
textView.setText(exampleArray[randomNum]);
if (x1 < x2) {
}
if (x1 > x2) {
//textView.setText(exampleArray[randomNum]);
}
}
}
return false;
}
I think you are missing some steps and adding extraneous ones....
One simple way (if you don't care whether the numbers keep going up) is to keep adding a random positive value to a counter. That way the new counter will always be different.
If you do:
Another way to do this is to creating a list of numbers beforehand (either sequentially [1, 2, 3...] or you randomly add some amount to each new index [rnd1, rnd1 + rnd2, rnd1 + rnd2 + rnd3...]), randomizing the ordering by shuffling the numbers (click this!), and then simply iterating through the created array.

updating Textview based on sensordata

I'm trying to update a textview based on sensorinput - more precise pitch. I have no problem getting the sensor data, converting it to degrees and displaying it in a textview.
The problem is, that I wan't different numbers displayed, based on the pitch in degrees. I have written a if-else if statement and placed it in the onsensorchanged, but apart from the initial number it does not update.
#Override
public void onSensorChanged(SensorEvent event) {
switch(event.sensor.getType()){
case Sensor.TYPE_ACCELEROMETER:
for(int i =0; i < 3; i++){
valuesAccelerometer[i] = event.values[i];
}
break;
case Sensor.TYPE_MAGNETIC_FIELD:
for(int i =0; i < 3; i++){
valuesMagneticField[i] = event.values[i];
}
break;
}
boolean success = SensorManager.getRotationMatrix(
matrixR,
matrixI,
valuesAccelerometer,
valuesMagneticField);
if(success){
SensorManager.getOrientation(matrixR, matrixValues);
// Float to double
double pitch = Math.toDegrees(matrixValues[1]);
// 1 decimal
pitch = Math.abs(round(pitch, 0));
//set textview vinkel to degrees
vinkel.setText(String.valueOf(pitch));
// find tubesize from edittext
String tubesizestring = tubesize.getText().toString();
if(tubesizestring=="1000"){
if(pitch>=0.6){
kwh.setText("2,69");
}else if(pitch>=1.0){
kwh.setText("3,47");
}else if(pitch>=2.0){
kwh.setText("4,90");
}else if(pitch>=5.0){
kwh.setText("7,75");
}else if(pitch>=10.0){
kwh.setText("10,96");
}else if(pitch>=20.0){
kwh.setText("15,50");
}else if(pitch>=30.0){
kwh.setText("18,99");
}else{
kwh.setText("more than 30 degrees");
}
}
}
I hope it is clear what I'm trying to do. Othervise please ask
Hope somebody can point me in the right direction
It doesn't work because your logic is fundamentally flawed. Let's assume the pitch is around 25. It's greater than 0.6 and 1.0 and so on. So obviously only the first if statement will be seen, since the others are else if statements. To get it to work, change the order of the statements.
if(pitch>=30.0){
kwh.setText("18,99");
}else if(pitch>=20.0){
kwh.setText("15,50");
}else if(pitch>=10.0){
kwh.setText("10,96");
}else if(pitch>=5.0){
kwh.setText("7,75");
}else if(pitch>=2.0){
kwh.setText("4,90");
}
else if(pitch>=1.0){
kwh.setText("3,47");
}
else if(pitch>=0.6){
kwh.setText("2,69");
}eelse{
kwh.setText("more than 30 degrees");

Categories

Resources