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
}
Related
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());
}}
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.
I am trying to make a basic conversion tool that i will expand on later. But when i take the information from the EditText and covert it to Integer then try to multiply it, my application crashes on the button click.
My Java code is as follows, New member to this site, but have been using it for help for weeks now, So thanks you have all helped out so much already
package com.example.mayconverter;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Feetyards extends Activity{
EditText feet;
Button convertFeet;
int formula;
TextView displayText;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.feet_yards);
displayText =(TextView) findViewById(R.id.displayText);
formula = 3;
convertFeet = (Button) findViewById(R.id.buttonFeet);
final EditText feet = (EditText) findViewById(R.id.editTextFeet);
convertFeet.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String data = feet.getText().toString();
final int dataint = Integer.parseInt(data);
displayText.setText(dataint + formula);
}
});
}
}
It always helps to post your LogCat errors, but it looks like you have two problems:
You are accidentally creating two variables with the same name feet:
This creates a local feet variable (not what you want)
final EditText feet = (EditText) findViewById(R.id.editTextFeet);
Use this instead to initialize your class variable feet:
feet = (EditText) findViewById(R.id.editTextFeet);
You need to convert your "formula" back into a String:
displayText.setText((dataint + formula) + "");
When you use setText(Int), this tried to load a String value stored in your resources, while setText(String) displays the String passed to the function.
replace this line
displayText.setText(dataint + formula);
with
displayText.setText((dataint + formula)+"");
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().
I'm trying to create an android program. The program works like this, a user enters the number of dice he wants to throw and the program does it. My curly brace are all over the place and I don't were to add or remove them. My while statement I use to control input verification, does not work.
Can you help fight my curly braces and fix my while statement.
Here how my program looks like
http://img232.imageshack.us/i/alphascreen.png/
package com.warhammerdicerrolleralpha;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class myMain extends Activity
{
EditText enternumberofdice;
ImageView i = new ImageView(this);
{
i.setAdjustViewBounds(true);
}
private int myFaceValue;
/**
* Called when the activity is first created.
*
* #return
*/
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public int roll()
{
int val = (int) (6 * Math.random() + 1); // Range 1-6
setValue(val);
return val;
}
int myNum = 0;
{
try
{
myNum = Integer.parseInt(enternumberofdice.getText().toString());
}
catch(NumberFormatException nfe)
{
enternumberofdice.setText("Does not work");
}
}
public int getValue()
{
return myFaceValue;
}
public void setValue(int myFaceValue)
{
this.myFaceValue = myFaceValue;
}
{
switch (myFaceValue)
{
case 5:
i.setImageResource(R.drawable.dicefive);
break;
case 1:
i.setImageResource(R.drawable.diceone);
break;
case 3:
i.setImageResource(R.drawable.dicethree);
break;
case 2:
i.setImageResource(R.drawable.dicetwo);
break;
case 4:
i.setImageResource(R.drawable.dicefour);
break;
case 6:
i.setImageResource(R.drawable.dicesix);
break;
}
Button buttonGenerate = (Button)findViewById(R.id.button1);
final TextView textGenerateNumber = (TextView)findViewById(R.id.text4);
enternumberofdice = (EditText) findViewById(R.id.enternumberofdice);
buttonGenerate.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
while (myNum > 0 )
{
// TODO Auto-generated method stub
textGenerateNumber.setText(String.valueOf(enternumberofdice));
roll();
myNum --;
}
}
});
}
}
A simple "trick" for figuring out where the missing braces ought to go is to use Eclipse's "correct indentation" function. The indentation will give you clues as to where you need to insert or remove braces.
The problem with the '>' operator is that enternumberofdice is not a primitive number type. It is of type EditText; i.e. a text entry widget.
Hint: you have to extract the "value" from the widget as text (i.e. a String), then convert the text to a primitive number.
Some problems I notice:
1) It looks to me like your OnCreate() method doesn't have closing brackets.
2) Remove the } right after this line: this.myFaceValue = myFaceValue; and add a } in place of the // NOT WORKING line.