Declare multiple variables in one class in Android Studio - java

I have an assignment to build a simple multi-widget application in Android Studio and I am trying to figure out how to declare multiple variables inside one class for a multi-page photo rating app. I have 4 pages, and 4 photos with a RatingBar underneath each of them. I would like to have the average of all the ratings displayed on the top of the page. For simplicity I have it being cast to the page title using SetTitle
How can I write this java in such a way that I can access all 4 of my ratings and apply the basic math to them? This is technically beyond what we have been taught so far in this class.
package ca.bcit.comp2052.a00587366.multiplewidgetsapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Start of rating bar
RatingBar ratingBar1 = (RatingBar) findViewById(R.id.ratingBar1);
ratingBar1.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar1, float rating, boolean fromUser) {
// Implement your logic here
float total = 0;
total += ratingBar1.getRating();
// total += ratingBar2.getRating();
// total += ratingBar3.getRating();
// total += ratingBar4.getRating();
float average = total / 4;
setTitle("Average: " + average);
}
});
// end of rating bar
Button buttonNext = (Button) findViewById(R.id.nextButton);
buttonNext.setOnClickListener(new
android.view.View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,
Main2Activity.class));
}
});
}
}

You should probably have them as R.id.ratingBars[0] and so forth, but since you don't, assuming it's R.id.ratingBar1 through R.id.ratingBar4, you can do something like this:
final RatingBar[] ratingBars = {
(RatingBar) findViewById(R.id.ratingBar1),
(RatingBar) findViewById(R.id.ratingBar2),
(RatingBar) findViewById(R.id.ratingBar3),
(RatingBar) findViewById(R.id.ratingBar4)
};
for (final RatingBar ratingBar : ratingBars) {
ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar bar, float rating, boolean fromUser) {
// Implement your logic here
float total = 0.0f;
for (final RatingBar ratingBar : ratingBars) {
total += ratingBar.getRating();
}
float average = total / 4.0f;
setTitle("Average: " + average);
}
});
}
This also makes it easier to add new RatingBars if necessary. You just add them to the original array initialization list at the top and everything is taken care of.

You could try calling them by
Main2Activity.ratingBar2.getRating()
But they should be public, which is not too good.
Elsewhere you can declare them private and the create public getter methods to retrieve them from external classes.

Related

Android studio: How do I show an updating variable at all times using a Textview?

The android studio code works as intended. However, points are made in the background since it's an idle game. An on click method only shows the points that were made as of the last click. I need the points to be shown at all times.
I have been testing this new added bit of code but the points are not updating when the button is clicked. Example in photo. Evolution Points = 0; The on click method is updating but there are also points made in the background that need to be shown without a button click. Any suggestions?
visibletotals.setText("Evolutions Points: " + clicks);
full code for reference
package com.example.idleclicker;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
TextView points;
TextView visibletotals;
Button click;
Button upgradebtn;
TextView Leveltext;
int clicks = 0;
int clickcost = 10;
int upgradelevel = 1;
Timer myTimer = new Timer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click = (Button) findViewById(R.id.click);
points = (TextView) findViewById(R.id.points);
upgradebtn = (Button) findViewById(R.id.upgradebtn);
Leveltext = (TextView) findViewById(R.id.leveltext);
visibletotals = (TextView) findViewById(R.id.visibletotals);
visibletotals.setText("Evolutions Points: " + clicks);
click.setEnabled(true);
upgradebtn.setEnabled(true);
myTimer.schedule(new TimerTask() {
#Override
public void run() {
clicks+= upgradelevel;
}
}, 0, 1000);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clicks++;
points.setText(getResources().getString(R.string.evol) + clicks);
}
});
upgradebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicks >= clickcost) {
clicks -= clickcost;
upgradelevel += 1;
clickcost *= 2;
upgradebtn.setText(getResources().getString(R.string.Upgrade) +
clickcost +
getString(R.string.LevelText)
+ upgradelevel);
};
}
});
}}
I can see that your clicks is changing(dynamic) while your set text is static that means it is only replying at the start and it is not triggered from the next time you do it. one way to tackle this is put the settext value in the trigger block(i.e onclicklistener) and make it set the fresh text as per triggered.

How to make TextView print the value from EditText?

I want the EditText element print the value I have entered in the UserInputs Array. I have tried Log.v and doInBackground,but that doesn't work.
I would be happy if you can explain how do I print the needed value in the EditText in the future, because I'm new in the Adnroid development.
I can send .xml file if needed.
Also, don't mind comments inside the code...
This is the code:
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;
import java.util.*;
public class MainActivity extends AppCompatActivity {
private EditText user_input;
private EditText user_input1;
private Button Button;
private TextView result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user_input = findViewById(R.id.user_input);
Button = findViewById(R.id.Button);
result = findViewById(R.id.result);
user_input1 = findViewById(R.id.user_input1);
Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(user_input.getText().toString().trim().equals("")&&user_input1.getText().toString().trim().equals(""))
Toast.makeText(MainActivity.this, "Введите хотя бы 2 варианта", Toast.LENGTH_LONG).show();
else{
//creating method for randomly choosing one of the user inputs
Random rand = new Random();
EditText[] userInputs = {user_input, user_input1};
int randomAnswer = rand.nextInt(userInputs.length);
result = userInputs[randomAnswer];
Log.v("EditText", result.getText().toString());
}}
});
}
private class getResult extends AsyncTask<String, String, TextView> {
#Override
protected TextView doInBackground(String... strings) {
return result;
}
}
}
Actually, I want to print the value in ResuRrect how to do that?
can you please explain me where exactly you want to print values??
So that I can help you.
If you want to print whatever inserted by user you can use textview to display it.
for that just add two textview in xml find it by id in java and on button click perform set text on it.
for example you have two textview
TextView tv1 = findViewById(R.id.tv1);
TextView tv2 = findViewById(R.id.tv2);
and button click will be as follows
Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(user_input.getText().toString().trim()) &&
TextUtils.isEmpty(user_input1.getText().toString().trim())) {
Toast.makeText(MainActivity.this, "Введите хотя бы 2 варианта", Toast.LENGTH_LONG).show();
} else {
//creating method for randomly choosing one of the user inputs
tv1.setText(user_input.getText().toString().trim());
tv2.setText(user_input1.getText().toString().trim());
Log.e("EditText1", user_input.getText().toString().trim());
Log.e("EditText2", user_input2.getText().toString().trim());
}
}
});
Your question isn't clear but if you want to display text to the user, it is better to use TextView.
for the set text of EditText or TextView, you should use setText method.
user_input.setText("hello")
So anyway I made it work. Now when user enters two values in EditText, program will randomly choose on of the inputs and print it in the TextView.
Here is the code:
public void onClick(View v) {
if(user_input.getText().toString().trim().equals("")&&user_input1.getText().toString().trim().equals(""))
Toast.makeText(MainActivity.this, "Введите хотя бы 2 варианта", Toast.LENGTH_LONG).show();
else{
//creating method for randomly choosing one of the user inputs
Random rand = new Random();
String[] key = {user_input1.getText().toString().trim(), user_input.getText().toString().trim()};
int randomAnswer = rand.nextInt(key.length);
result.setText(key[randomAnswer].toString().trim());
}}

Java- hot to have just 1 button to toggle back and forth instead of two buttons?

I have 1 button for changing an image and a text.
I wanted to make that same button so that if I click AGAIN, it would change back to the original image and the text. However, 'TextView' and 'ImageView' in Java code would tell me, I have already defined. Therefore, I guess I can't re-define them within 1 button.
I ended up creating 2 buttons: 1 to change and 2nd one to return back. How can I just have one button to change and return images and text? HELP!
package com.example.android.cookies;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* Called when the cookie should be eaten.
*/
public void eatCookie(View view) {
// TODO: Find a reference to the ImageView in the layout. Change the image.
ImageView imageView = (ImageView)
findViewById(R.id.android_cookie_image_view);
imageView.setImageResource(R.drawable.after_cookie);
// TODO: Find a reference to the TextView in the layout. Change the text.
TextView textView = (TextView) findViewById(R.id.status_text_view);
textView.setText("Im so full");
}
public void returnCookie(View view) {
ImageView imageView = (ImageView)
findViewById(R.id.android_cookie_image_view);
imageView.setImageResource(R.drawable.before_cookie);
TextView textView = (TextView) findViewById(R.id.status_text_view);
textView.setText("I'm so hungry");
}
}
]2
I have written a well maintained code for you. You can save current state.
I don't recommend boolean. Because if you take int you can save more states in future, whereas in boolean you can save only two states- true or false.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
ImageView imageView;
TextView textView;
Button button;
final int STATE_HUNGRY = 1;
final int STATE_FULL = 2;
int currentState = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.android_cookie_image_view);
textView = (TextView) findViewById(R.id.status_text_view);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (currentState) {
case STATE_FULL:
returnCookie();
break;
case STATE_HUNGRY:
eatCookie();
break;
default: // used when there is no state available
eatCookie();
}
}
});
}
public void eatCookie() {
currentState = STATE_FULL;
imageView.setImageResource(R.drawable.after_cookie);
textView.setText("Im so full");
}
public void returnCookie() {
currentState = STATE_HUNGRY;
imageView.setImageResource(R.drawable.before_cookie);
textView.setText("I'm so hungry");
}
}
Have you tried using a static variable to keep track of the currently displayed image? Static means it will maintain its state between function calls. Then toggle it each time the function is called. The initial declaration will only be called once.
static Boolean eaten = false;

Button and calculating in eclipse

now this is my problem.
I have 2 views which on both you will calculate something.
I use the same code on both views (but with the small changes so they do not calculate the same thing)
But the problem is, the button on page 2 do NOT calculate anything.
Here is the code for the java file view #2:
package tk.iWeld.iweld;
import android.os.Bundle; import android.app.Activity;
import android.support.v4.view.ViewPager; import android.view.View;
import android.widget.EditText; import android.widget.TextView;
public class TestLay extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testlayout);
}
public void StartClickListener(View view) {
}
public void calculateClickListener(View view) {
// make sure we handle the click of the calculator button
if (view.getId() == R.id.button) {
// get the references to the widgets
EditText text1Text = (EditText)findViewById(R.id.editText1);
EditText text2Text = (EditText)findViewById(R.id.editText2);
TextView resultText = (TextView)findViewById(R.id.resultat);
float text1 = Float.parseFloat(text1Text.getText().toString());
float text2 = Float.parseFloat(text2Text.getText().toString());
// calculate the result value
float totalresult = calculateRESULT(text1, text2);
// now set the value in the result text
resultText.setText("Debug=ok" + (totalresult));
}
}
// the formula to calculate the result index
private float calculateRESULT (float text1, float text2) {
return (float) (3.14 * (text1 * text1) * text2 / 4 / 1000000);
} }
The best way to diagnose a problem like this is to break it down.
1) Check that you're getting inside your click listener:
if (view.getId() == R.id.button) {
//make sure you get here
}
2) If you're getting inside the click listener OK, simplify your calculateRESULT() function and return a simple result:
private float calculateRESULT (float text1, float text2) {
return 3.14;
}
This will help you find where the problem is.
P.S.: I would also suggest you do validation around your inputs:
float text1 = 0;
float text2 = 0;
try {
text1 = Float.parseFloat(text1Text.getText().toString());
text2 = Float.parseFloat(text2Text.getText().toString());
}
catch(Exception e) {
// handle if user inputs non-number
}

main method not being called in Android Activity

So i have this code which solves the quadratic equation in java (android development) and it isnt doing anything!!!! The button when i press it does not give the answer at all... i cant even check if it is doing it correctly.
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class QuadraticEquationSolver extends Activity {
public void main(String[] args){
Button calc = (Button) findViewById(R.id.Calculate);
calc.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
EditText X2 = (EditText)findViewById(R.id.X2);
EditText X = (EditText)findViewById(R.id.X);
EditText Num = (EditText)findViewById(R.id.Num);
TextView ans= (TextView) findViewById(R.id.finalans);
double x2 = Integer.parseInt(X2.getText().toString());
double x = Integer.parseInt(X.getText().toString());
double num = Integer.parseInt(Num.getText().toString());
double finalNum = ((x*-1) + (Math.sqrt((x*x)-(4*x*num))))/(2*x2);
ans.setText("answer: " + finalNum);
}
});
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quadratic_equation_solver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_quadratic_equation_solver, menu);
return true;
}
First of all, welcome to Android development. I would highly recommend as a starting point you read the App Fundamentals and related guides on the SDK documentation site, as they will help you greatly in your new endeavour.
Android does not use a single entry point (i.e. main method) so your code will not be called. You will want to move all that code into onCreate().
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quadratic_equation_solver);
Button calc = (Button) findViewById(R.id.Calculate);
calc.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
EditText X2 = (EditText)findViewById(R.id.X2);
EditText X = (EditText)findViewById(R.id.X);
EditText Num = (EditText)findViewById(R.id.Num);
TextView ans= (TextView) findViewById(R.id.finalans);
double x2 = Integer.parseInt(X2.getText().toString());
double x = Integer.parseInt(X.getText().toString());
double num = Integer.parseInt(Num.getText().toString());
double finalNum = ((x*-1) + (Math.sqrt((x*x)-(4*x*num))))/(2*x2);
ans.setText("answer: " + finalNum);
}
});
}
I don't do any android programming, but I doubt Android will ever call your main method. The content of this main method must probably be in the onCreate method.
onCreate() is your main() equivalent in Android. Your main() function will never be called. The contents of main() should go in onCreate().

Categories