I am making an application in which i have to fetch item name and price from first activity to another and i am able to do that but in second activity i am allowing user to put quantity in numbers and whenever user will click on button a TextView to show total amount, but not able to calculate total Amount for item.
I know this is very simple task to do but i am getting error while write this line in button onClick():
txtResult=txtCost*txtQty
here i am placing second activity code,
please correct this one:-
public class SecondScreenActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen2);
TextView txtName = (TextView) findViewById(R.id.txtName);
TextView txtCost = (TextView) findViewById(R.id.txtCost);
EditText txtQty=(EditText)findViewById(R.id.txtQty);
Button btnClose = (Button) findViewById(R.id.btnCalculate);
TextView txtResult = (TextView) findViewById(R.id.txtResult);
Intent i = getIntent();
// Receiving the Data
String name = i.getStringExtra("name");
String cost = i.getStringExtra("cost");
// Displaying Received data
txtName.setText(name);
txtCost.setText(cost);
// Binding Click event to Button
btnClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Closing SecondScreen Activity
//finish();
txtResult=txtCost*txtQty;
}
});
}
}
You can do it by
int cost = Integer.parseInt(txtCost.getText().toString());
int qty = Integer.parseInt(txtQty.getText().toString());
int result = cost*qty;
and then set this result into txtResult
txtResult.setText(result+"");
or you can convert int to String and then apply setText
Why are to multiplying value in Textview
btnClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Float f_name = new Float(name);
Float f_cost = new Float(cost);
Float f_result=f_name *f_cost ;
txtResult.setText(f_result);
}
});
}
}
txtResult=txtCost*txtQty;
These are TextView objects. You can't do maths on objects. Get the textview's values into integers and then try to multiply.
Do something like this.. depending on the type of variable you want (integer, float, double).
int a = new Integer(txtCost.getText().toString());
int b = new Integer(txtQty.getText().toString());
int c = a * b;
txtResult.setText(d);
There are 2 changes that needs to be made.
Make both txtCost and txtQty global variables.
both these variables cannot be directly multiplied. Instead do somthing like this.
double cost = Double.parseDouble(txtCost.getText().toString());
double qty = Double.parseDouble(txtQty.getText().toString());
txtResult = cost * qty ;
Related
Learning how to produce random numbers from arrays. The code will pick a random string during the onCreate method, but when the button is clicked there is no change to the string. Am I messing up the scope of my variables somehow? I really do not know what it wrong.
public class MainActivity extends AppCompatActivity {
String[] qArray; //initialize qArray
private static final Random rgen = new Random(); //sets the new Random method to the keyword rgen
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qArray = getResources().getStringArray(R.array.qArray); //grabs string array in the XML file
String q = qArray[rgen.nextInt(qArray.length)];//generates a random index of qArray to set to q
TextView question = (TextView) findViewById(R.id.question); //sets the TextView to "question"
question.setText(q); //sets the text in "question" to q
}
public void onClick(View view){
Button button = (Button) view.findViewById(R.id.button_click);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
/*This should do the same thing as onCreate but each time
the button is pressed. I think the error is here.*/
String q = qArray[rgen.nextInt(qArray.length)];
TextView question = (TextView) findViewById(R.id.question);
question.setText(q);
}
});
}
}
First of all you haven't set click listener on button properly you made onClick method which is never called . Also you are getting the references of view multiple times you should do it like this.
public class MainActivity extends AppCompatActivity {
String[] qArray; //initialize qArray
private static final Random rgen = new Random(); //sets the new Random method to the keyword rgen
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qArray = getResources().getStringArray(R.array.qArray); //grabs string array in the XML file
String q = qArray[rgen.nextInt(qArray.length)];//generates a random index of qArray to set to q
TextView question = (TextView) findViewById(R.id.question); //sets the TextView to "question"
question.setText(q); //sets the text in "question" to q
Button button = (Button) view.findViewById(R.id.button_click);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
/*This should do the same thing as onCreate but each time
the button is pressed. I think the error is here.*/
String q = qArray[rgen.nextInt(qArray.length)];
question.setText(q);
}
});
}
}
You either need to set the onClickListener in xml (in which case you don't need to set the listener in code), or you need to set the listener in onCreate. Right now its being set in a function named onClick, which is never called.
First, you never set the onClickListeren. You have a method which adds one, but you never call it. Move the code in the onClick method to your onCreate method. This will probably fix your problem.
If not, don't make your Random final and add this to your #Override onClick():
rgen = new Random(System.currentTimeMillis());
This will use a different seed every time
What I'm trying to do is:
If the EditText input is equal to the random number generated, then stop the loop otherwise keep on the loop and reset input text.
For some reason, I'm getting an infinite loop. I am new to programming, any help is really appreciated.
Here is the code:
public class Main extends Activity implements OnClickListener{
private TextView tvResult;
private TextView tvRandTest;
private EditText et1;
private String randonNumber;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvResult = (TextView) findViewById(R.id.textView4);
tvRandTest = (TextView) findViewById(R.id.textView3);
et1 = (EditText) findViewById(R.id.editText1);
}//End Main
public void myClickHandler(View view)
{
if(view.getId() == R.id.button1)
{
//Generates 6 one digit Random Numbers
int randonNumber1 = (int) (0 + Math.random() * 9);
//Parse Numbers
String rd1 = Integer.toString(randonNumber1);
randonNumber = rd1;
boolean done = false;
do
{
et1.getText().toString();
if(et1.equals(randonNumber))
{
Toast.makeText(Main.this,"Equal Number", Toast.LENGTH_SHORT).show();
tvResult.setText(randonNumber);
done = true;
}//end if
else
{
Toast.makeText(Main.this,"Not Equal Number", Toast.LENGTH_SHORT).show();
et1.setText("");
}//end else
}//End While
while(!done);
}//End if
if(view.getId() == R.id.button2)
{
tvRandTest.setText(randonNumber);
}
}//End Method
#Override
public void onClick(View arg0) {
// TODO
}
}//End Class
if(et1.equals(randonNumber))
I will change it with
if(et1.equals(String.valueOf(randonNumber)))
you put directly the int value inside the equals method two things will happen:
the autboxing will create an Integer object starting from the int value
the toString() method will be called through this object.
the toString() method of Integer in android, as the doc stands:
Returns a string containing a concise, human-readable description of this object.
So you are compareing the address of the new object with the content of et1 and not with its real value. Here the reference
In this line et1.getText().toString(); you need to assign result to variable, for example String input = et1.getText().toString(); Then in next line you need to compare two strings, if(input.equals(randonNumber)) But your program can hang cause of infinity loop on UI thread. You should use TextWatcher
to handle when text in EditText was changed
Getting Error while calculating amount, three fields name, qty, price in which name and price getting from first activity and qty edittext thru this allowing user to input qty, but getting error :-
the final local variable qty, price, total cannot be assigned since it is defined in an enclosing type android.please see the source code
public class SecondScreenActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen2);
TextView txtName = (TextView) findViewById(R.id.txtName);
final TextView txtCost = (TextView) findViewById(R.id.txtCost);
final EditText txtQty=(EditText)findViewById(R.id.txtQty);
final double price = Double.parseDouble(txtCost.getText().toString());
final double qty = Double.parseDouble(txtQty.getText().toString());
final double total=0;
Button btnClose = (Button) findViewById(R.id.btnCalculate);
final TextView txtResult = (TextView) findViewById(R.id.txtResult);
Intent i = getIntent();
// Receiving the Data
String name = i.getStringExtra("name");
String cost = i.getStringExtra("cost");
// Displaying Received data
txtName.setText(name);
txtCost.setText(cost);
// Binding Click event to Button
btnClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Closing SecondScreen Activity
//finish();
//Getting Error Here
//the final local variable qty price total
//cannot be assigned since it is defined
//in an enclosing type android
qty=Double.parseDouble(txtQty.getText().toString());
price=Double.parseDouble(txtCost.getText().toString());
total=qty*price;
txtResult.setText(Double.toString(total));
}
});
}
}
You don't need to define the variables qty and price in the onCreate(). Only define them in your OnClickListener and all will be well. You can't change final variables after you set them. That's why they are final.
It's hard to explain in the title. Basically as far as I can tell the submit button is taking the name and placing it in the array like I want. What I need now is for the Play(done) Button to transfer the user and the data to the next class (which I believe is coded correctly) and I need it to start a game. The game which you will see in the second class (get the data from the previous) I need it to display the names from the names array 1 at a time and randomly assign them a task to do from the tasks array.
Currently the app is force closing after I click the play button. I'm linking both classes cause I'm pretty sure the problem is in the second class. Thanks for your help ahead of time.
Class1
public class Class1 extends Activity
{
int players=0;
String names[];
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.class1);
final EditText input = (EditText) findViewById(R.id.nameinput);
final ArrayList<String> names = new ArrayList<String>();
Button submitButton = (Button) findViewById(R.id.submit_btn);
submitButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View submit1)
{
players++;
for(int i=0; i < 6; i++)
{
names.add(input.getText().toString());
input.setText("");
}
}
});
Button doneButton = (Button) findViewById(R.id.done_btn);
doneButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View done1)
{
Intent done = new Intent(Class1.this, Game.class);
Bundle bundle = new Bundle();
bundle.putStringArrayList("arrayKey", names);
done.putExtra("players", players);
//done.putExtra("names", names[players]);
startActivity(done);
}
});
}
Game Class
public class Game extends Activity
{
int players, counter=0, score, ptasks,rindex;
String[] names, tasks;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
Bundle bundle = this.getIntent().getExtras();
String[] names = bundle.getStringArray("arrayKey");
Intent game = getIntent();
players = game.getIntExtra("players", 1);
//names = game.getStringArrayExtra("names");
Random generator = new Random();
tasks[0]= "";
tasks[1]= "";
tasks[2]= "";
tasks[3]= "";
tasks[4]= "";
tasks[5]= "";
tasks[6]= "";
tasks[7]= "";
tasks[8]= "";
tasks[9]= "";
while (counter <5)
{
for (int i = 0; i < players; i++)
{
TextView name1 = (TextView) findViewById(R.id.pname);
name1.setText( names[i]+":");
ptasks = 10;
rindex = generator.nextInt(ptasks);
TextView task = (TextView) findViewById(R.id.task);
task.setText( tasks[rindex]);
}
Button failButton = (Button) findViewById(R.id.fail_btn);
failButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View failed)
{
}
});
Button notButton = (Button) findViewById(R.id.notbad_btn);
notButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View notbad)
{
}
});
Button champButton = (Button) findViewById(R.id.champ_btn);
champButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View champp)
{
}
});
counter++;
}
}
Thought I should also mention that these buttons on the 2nd page I would like to assign a score to whichever name array person is up and keep track until the final round where it will display the winner. If anyone has any idea how to make that work.
Have you made sure to include the Game activity as an Application Node in your AndroidManifest?
If not, open your manifest to the application tab, on the bottom hit Add, and add an Activity of the name .Game
Without this, that intent never gets received by the other class.
You've already been told that you use non-initialized arrays here: EditText and using buttons to submit them. But also you're trying to get array extra, however you don't put it inside intent. And you're using uninitialized tasks array in Game class.
I'm a beginner in application development. My problem is, that when I run my app and I click on the Calculate button, the program stops. The code:
public class screen1 extends Activity {
private EditText name;
private CheckBox box1;
private Spinner spinner;
private TextView text1, text2, text3, text4, text5, text6;
private Button calcbutton, closebutton;
String strength;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner hubSpinner = (Spinner) findViewById(R.id.myspinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.military_ranks , android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
hubSpinner.setAdapter(adapter);
name = (EditText)findViewById(R.id.editText1);
strength = name.getText().toString();
box1 = (CheckBox)findViewById(R.id.checkBox1);
text1 = (TextView)findViewById(R.id.textView4);
text2 = (TextView)findViewById(R.id.textView6);
text3 = (TextView)findViewById(R.id.textView8);
text4 = (TextView)findViewById(R.id.textView10);
text5 = (TextView)findViewById(R.id.textView12);
text6 = (TextView)findViewById(R.id.textView14);
final Button calcbutton = (Button) findViewById(R.id.button1);
calcbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int str = Integer.valueOf(strength);
int rank = spinner.getSelectedItemPosition()+1;
double sebzes;
if(box1.isChecked()){
sebzes = (((rank-1)/20+0.3)*((str/10)+40))*1*(1+1/100);
text1.setText(Double.toString(sebzes));
}
else{
sebzes = (((rank-1)/20+0.3)*((str/10)+40))*1;
text1.setText(Double.toString(sebzes));
}
}
});
final Button closebutton = (Button) findViewById(R.id.button2);
closebutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}
In the edittext component you should be able to write numbers only. I don't know why it's not working.
The problem are these two lines:
int str = Integer.valueOf(strength);
int rank = spinner.getSelectedItemPosition()+1;
The first won't fail if you use only numbers in your EditText but it would be better to ensure that or at least catch the exception that is thrown when you try to convert a character to a numberical value. Additionally you could also use Integer.valueOf(strength).intValue(); even so it is normally not really necessary.
The real problem is the second line. You declared the variable spinner but you never instantiate it. That's why you will get a NullPointerException there.
On an unrelated note: You also should start your class name with a capital letter to follow the Java naming conventions.
You're not instantiating spinner anywhere, but you're referencing it in the second line of your button click method. Probably a null reference problem.