Toast Won't show on android application, using android studio - java

Good Morning, I tried getting the toast to show if the number of students is less than 0, or greater than 100. The app seems to work fine, except showing the toast. This assignment is due tomorrow night.
Here is my code:
package co.tekitall.classroommanager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
import static co.tekitall.classroommanager.R.id.NumOfStudents;
public class Classroom extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_classroom);
Button button = (Button) findViewById(R.id.SubmitClassRoomInfoButton);
}
void ClassroomElements() {
//ArrayList
ArrayList<EditText> arrayList = new ArrayList<>();
arrayList.add((EditText) findViewById(R.id.Teacher_Name));
arrayList.add((EditText) findViewById(R.id.Room_Number));
arrayList.add((EditText) findViewById(R.id.ClassroomHelper));
arrayList.add((EditText) findViewById(R.id.NumOfStudents));
}
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
EditText numofstudents = (EditText) findViewById(R.id.NumOfStudents);
String getstucount = numofstudents.getText().toString();
int setstucount = Integer.parseInt(getstucount);
if(setstucount < 0) {
numofstudents.setText("");
Toast toast = Toast.makeText(Classroom.this, "Please try Again! Number must be greater then 0 and less than 100...", Toast.LENGTH_LONG);
toast.show();
}
if(setstucount > 100) {
numofstudents.setText("");
Toast toast = Toast.makeText(Classroom.this, "Please try Again! Number must be greater then 0 and less than 100...", Toast.LENGTH_LONG);
toast.show();
} else
numofstudents.setText("");
Toast toast = Toast.makeText(Classroom.this, "Good Job",
Toast.LENGTH_LONG);
toast.show();
}
};
}

You need to bind button and listener using
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_classroom);
Button button = (Button) findViewById(R.id.SubmitClassRoomInfoButton);
button.setOnClickListener(listener);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
Plus use if and else-if instead of multiple ifs because a number can only be either less than 0 otherwise greater than 100 or between|equals 0 or 100
if(setstucount < 0){//...code}
else if(setstucount > 100){//...code}
else {//...code}

Looks like you have a Button and an OnClickListener but you're never connecting them together. For example:
button.setOnClickListener(listener);

Related

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());
}}

Attempting to create validation for a number, crashes when attempting to test

The Title is the best I could explain it. I am attempting to create a validation for a number box in Java, using android studio. However, the validation, when it should instead display the message "weight must be entered!", the program collapses upon itself. Any idea what could be wrong? Thanks in advance.
package com.example.student.project8a_medicalcalculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DecimalFormat;
import java.util.EmptyStackException;
public class MainActivity extends AppCompatActivity {
double weightEntered;
double convertedWeight;
final double conversionRate = 2.2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
final EditText weight = (EditText) findViewById(R.id.Weight);
final RadioButton lbToKilo = (RadioButton) findViewById(R.id.LbToKilo);
final RadioButton kiloToLB = (RadioButton) findViewById(R.id.KiloToLb);
final TextView result = (TextView) findViewById(R.id.Results);
Button convert = (Button) findViewById(R.id.bnConvert);
convert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String weightV;
weightV = weight.getText().toString();
if (weightV.equals(" "))Toast.makeText(MainActivity.this, "Weight must be entered! ", Toast.LENGTH_LONG).show();
weightEntered = Double.parseDouble(weight.getText().toString());
DecimalFormat tenth = new DecimalFormat("#.#");
if (lbToKilo.isChecked()){
if (weightEntered <= 500){
convertedWeight = weightEntered / conversionRate;
result.setText(tenth.format(convertedWeight) + " kilograms");
} else {
Toast.makeText(MainActivity.this, "Pounds must be less than 500", Toast.LENGTH_LONG).show();
}
}
if (kiloToLB.isChecked()){
if (weightEntered <= 225){
convertedWeight = weightEntered * conversionRate;
result.setText(tenth.format(convertedWeight) + " pounds");}
else {
Toast.makeText(MainActivity.this, "Kilos must be less than 225 ", Toast.LENGTH_LONG).show();
}
}
}
});
}
}
Double.parseDouble() will raise NumberFormatException exception and make app crash when when you try to parse an empty string.
you checked the input string, but run Double.parseDouble() even it equals empty.
You could do as below:
if (!weightV.isEmpty()){
weightEntered = Double.parseDouble(weight.getText().toString());
......
}else{
Toast.makeText(MainActivity.this, "Weight must be entered! ", Toast.LENGTH_LONG).show();
......
}
You say: the validation, when it should instead display the message "weight must be entered!", /the program collapses upon itself
So you put a space " " in the EditText and expect to see the Toast.
You would see the Toast if you change the code:
if (weightV.trim().isEmpty()) {
Toast.makeText(MainActivity.this, "Weight must be entered! ", Toast.LENGTH_LONG).show();
return;
}
But without return the code continues to execute and Double.parseDouble(weight.getText().toString()) throws an exception because an empty EditText's text is not a valid number.

Android - Checkbox/radio button score quiz app

I would like to ask for some help with my android code.
It should add one point with correct radiobutton and checkbox click - which it does - but there is an error, which I can't find out why.:
here is the java code:
package com.example.android.myquizapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import static com.example.android.myquizapp.R.id.Tom;
import static com.example.android.myquizapp.R.id.score;
public class MainActivity extends AppCompatActivity {
Button btnSubmit;
int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSubmit = (Button)findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
int score = 0;
if (((RadioButton)findViewById(R.id.Monica)).isChecked()) {score++;}
if (((RadioButton)findViewById(R.id.h5)).isChecked()) {score++;}
if (((RadioButton)findViewById(R.id.a3)).isChecked()) {score++;}
if (((CheckBox) findViewById(R.id.Tom)).isChecked()){score++;}
if (((CheckBox) findViewById(R.id.Brad)).isChecked()){score++;}
if (((CheckBox) findViewById(R.id.Bruce)).isChecked()){score++;}
{displayResult(score);}}
});}
private void displayResult() {
String message = "You scored " + score;
message += " out of 6";
message += "\nWell done!";
Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0 , 0);
toast.show();
}}
the word "score" is red underlined in Android studio:
{displayResult(score);}}
the app works fine, so not quite understand why.
Can you help me?
Your displayResult() method does not have any arguments. And you are passing an argument to it. That is why your are seeing that red line
And How on the earth is your app working fine. You can't even compile that code with this error.
firstly you have declare int score = 0; globally, So you don't need to declare locally in Onclick method. remove following line from Onclick method.
int score = 0;
then you are passing param score to displayResult() method but you have declared with no params.call
displayResult();
Firstly you are passing the int score to the displayResult() method which is not expecting any arguments and secondly you are wrapping it around extra {} brackets which is wrong.
Also you have initialized Button btnSubmit twice which is also wrong and now since you are passing the score value there is no need to create global score which is redundant and not being used anywhere.
You should modify you code as:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
int score = 0;
if (((RadioButton)findViewById(R.id.Monica)).isChecked()) {score++;}
if (((RadioButton)findViewById(R.id.h5)).isChecked()) {score++;}
if (((RadioButton)findViewById(R.id.a3)).isChecked()) {score++;}
if (((CheckBox) findViewById(R.id.Tom)).isChecked()){score++;}
if (((CheckBox) findViewById(R.id.Brad)).isChecked()){score++;}
if (((CheckBox) findViewById(R.id.Bruce)).isChecked()){score++;}
displayResult(score);
}
});}
private void displayResult(int score) {
String message = "You scored " + score;
message += " out of 6";
message += "\nWell done!";
Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0 , 0);
toast.show();
}
}
Hope this solves your issues

Buttons onClick method restarts if clicked to fast

I have little application where you can tell your fortune (it's actualy just random), there are four edittextfields that you can type in and one button that choose one of the edittextfields, and remove it. Pretty simple. But i have problem, if someone presses the button multiple times too fast then all of the code in the onClick() method doesn't execute (probably because it is called again). Is there some way that I can prevent this from happening (I want all of the code in the onClick() method to execute before it can be called again)?
Here is the code:
package com.foretell.lukas.spamedprick;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
public class MainActivity extends AppCompatActivity {
ArrayList<EditText> tfa = new ArrayList<EditText>();
int x = 0;
boolean tf = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// References to XML widgets
final RelativeLayout rl = (RelativeLayout) findViewById(R.id.background);
final Button daButton = (Button) findViewById(R.id.button);
Button restartButton = (Button) findViewById(R.id.restartButton);
final EditText ruta1 = (EditText) findViewById(R.id.editText);
final EditText ruta2 = (EditText) findViewById(R.id.editText2);
final EditText ruta3 = (EditText) findViewById(R.id.editText3);
final EditText ruta4 = (EditText) findViewById(R.id.editText4);
final TextView outputText = (TextView) findViewById(R.id.outputText);
tfa.add(ruta1);
tfa.add(ruta2);
tfa.add(ruta3);
tfa.add(ruta4);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.spar);
final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.hurra);
daButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
if(tf) {
daButton.setEnabled(false);
mp.start();
try {
tf = false;
Thread.sleep(2000);
} catch (InterruptedException e) {
e.getStackTrace();
outputText.setText("Nått gick åt h***ete!");
}
Collections.shuffle(tfa);
x++;
if (x <= 2) {
outputText.setText("Det är inte " + tfa.get(0).getText() + "...");
tfa.get(0).setText("");
tfa.remove(0);
} else if (x == 3) {
outputText.setText("Det är...");
} else if (x == 4) {
tfa.get(1).setText("");
tfa.remove(1);
outputText.setText("Det är " + tfa.get(0).getText() + "!");
mp2.start();
}
tf = true;
daButton.setEnabled(true);
}else{
System.out.println("YO!");
}
}
}
);
restartButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
tfa.add(ruta1);
tfa.add(ruta2);
tfa.add(ruta3);
tfa.add(ruta4);
ruta1.requestFocus();
outputText.setText("");
x = 0;
ruta1.setText("");
ruta2.setText("");
ruta3.setText("");
ruta4.setText("");
}
}
);
}
}
Thanks.
I dont think that an "onClick" can be started before the last "onClick" is finished.
Here is the qoute from the android documentation:
The system does not create a separate thread for each instance of a component. All components that run in the same process are instantiated in the UI thread, and system calls to each component are dispatched from that thread. Consequently, methods that respond to system callbacks (such as onKeyDown() to report user actions or a lifecycle callback method) always run in the UI thread of the process.
http://developer.android.com/guide/components/processes-and-threads.html
Maybe you do something in the onClick method, that makes trouble, but without the code it is hard to tell:)
You have to do something like this
Button button= (Button) findViewById(R.id.buttonId);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
button.setEnabled(false);
// do your work here
// make it true after your work is done
button.setEnabled(true);
}
});

Finish class and get int from class finished to main class

I have a MainClass which one is the full app, when I click one button I go to another class (PopupValores) which one I make it looks like a popup. In this class I have a EditText where you type a integer and a button to close this class. My question is how to get that int typed in PopupClass and use it in MainClass. Heres the code for the PopupValores.
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class PopupValores extends Activity implements OnClickListener {
TextView texto;
String mensaje;
EditText editable;
Button ok;
public static int cantidad;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popupvalores);
ok = (Button) findViewById (R.id.Bok);
texto = (TextView) findViewById (R.id.textView1);
editable = (EditText) findViewById (R.id.editText1);
mensaje = editable.getText().toString();
ok.setOnClickListener(this);
ok.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View arg0) {
finish();
return true;
}
});
}
public void onClick(View v){
switch(v.getId()){
case R.id.Bok:
String mensaje;
mensaje = editable.getText().toString();
cantidad = Integer.parseInt(mensaje);
texto.setText("New value " + cantidad + ".");
}
}
}
Then in my MainClass I click a button and it shows the int
int id, vaas = PopupValores.cantidad;
public void onClick (View v)
{
posicion = (ImageCell) v;
seleccion = posicion.mCellNumber;
if (seleccion == -1){
....
toast (id + " " + vaas);
....
}
}
But instead of showing the value declared in PopupValores it shows 0. What I'm doing wrong here?
You need to call the popup Activity with Activity.startActivityForResult()
Once finishing the popup Activity, set the requested result via Activity.setResult() (you can save your data in the intent's bundle)
In your main Activity, override onActivityResult and retrieve the data
Its called startActivityforResult
and has been answered soo many times here on stackoverflow Here is one

Categories