I want to program a function that the toast exist when there is nothing
in the "edittext" box (id / password), but it dosen't work.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
import android.widget.EditText;
import android.widget.Toast;
import android.view.View.OnClickListener;
import android.text.Editable;
public class Test extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.button1);
EditText id = (EditText) findViewById(R.id.id);
EditText pwd = (EditText) findViewById(R.id.pwd);
Editable Str_id;
Editable Str_pwd;
Str_id = id.getText();
Str_pwd = pwd.getText();
button1.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v){
if(Str_id==null || Str_pwd == null){
Toast.makeText(Test.this, "Please Enter User ID / Password", Toast.LENGTH_LONG).show();
}
});
}
}
move the following lines inside onClick and try:
Str_id = id.getText();
Str_pwd = pwd.getText();
EDIT: Move
Editable Str_id;
Editable Str_pwd;
Str_id = id.getText();
Str_pwd = pwd.getText();
inside onClick().
I do not recommend toasting a message that a field is required. You're better off just giving the EditText focus, this focus tells the user that this field is required. Its less information on the screen and its subtle, which is important. You don't want to disturb the user too much.
The idea is...
When the submit button is clicked, check the EditTexts if any of them are empty, notify the user through requesting focus, also make sure your UI tells them before hand that the fields required. The hint of the EditText works well for this.
Related
I am new to Android programming and tried to create a small App. I have a MainClass with one EditText and one TextField. EditText is for users to type in a number and the TextField shows the value of the input when clicking on the first button. The second button is for switching to the other class (MainClass2). Now i want to show the input number from EditText (that I defined as "number") in the next class MainClass2 in an empty TextField. I implemented an OnClickListener for the two different buttons mentioned in the MainClass (first screen). Since I only defined the input variable "number" when clicking the first button (cause "number" is then shown in the TextField as mentioned because it is only created via EditText when clicking the first button), "number" is not defined in the code of clicking the second button. Therefore I cant hand it over to the MainClass2 via Intent. Do you have any solutions for this? Thank you in advance. These are the codes for my Classes:
package com.example.teilnehmeranzahl;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
Button button2 = findViewById(R.id.button2);
Button one = (Button) findViewById(R.id.button);
one.setOnClickListener(this); // calling onClick() method
Button two = (Button) findViewById(R.id.button2);
two.setOnClickListener(this);
}
public void onClick(View v) {
// default method for handling onClick Events..
switch (v.getId()) {
case R.id.button:
EditText editText2 = findViewById(R.id.editText2);
String name2=editText2.getText().toString();
int number=Integer.parseInt(name2);
TextView textView = findViewById(R.id.textView);
textView.setText(String.valueOf(number));
Random randomizer = new Random();
int name = randomizer.nextInt(number+1);
TextView textView2 = findViewById(R.id.textView2);
if (name == 1 ) {
textView2.setText("Player 1");
}
if (name == 2 ) {
textView2.setText("Player 2");
}
break;
case R.id.button2:
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("number",number); //here is the error cause number is not
defined, although it is..
startActivity(intent);
break;
default:
break;
}
}
}
And this is the code for MainClass2:
package com.example.teilnehmeranzahl;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
TextView textView3 = findViewById(R.id.textView3);
Intent intent = getIntent();
String number = intent.getStringExtra("number");
textView3.setText(number);
}
}
In case R.id.button2: you have not set the value of number. So it will give number undefined error. To solve this issue either you have to initialize number globally or get the value of number in case R.id.button2: also. Like
case R.id.button2:
EditText editText2 = findViewById(R.id.editText2);
String name2=editText2.getText().toString();
int number=Integer.parseInt(name2);
Intent intent =
new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("number",number);
startActivity(intent);
break;
Well... here's a problem it looks like I'm not the first to experience looking through other questions, however I can't find one that's Android-specific (others are C++ or straight java with different scenarios).
I have a calculator that determines your fuel mileage needs with given user inputs. The thing I'm adding now is a "burnoff" aspect where you can calculate the weight lost over the course of the race. Before adding the weight/burnoff element, everything worked fine.
Now, everything calculates normally except the weight on the first click.
On the second click (and subsequent clicks) it calculates properly. I suspect it has something to do with the switch statement and its location, but I could be wrong.... and even if I'm not, I'm not sure how to change it.
Looking for help on getting it all functioning properly on the first click. Thanks!
EDIT: The non-exception Toast text I put in as a debugger to determine if it was a math issue or what in the code. It pops up with "0.0" on the first click, then either "6.2" or "6.6" on subsequent clicks.
package com.tomcat.performance;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class Fuelsimple extends Activity implements OnCheckedChangeListener{
double fuelweight;
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch (checkedId){
case R.id.rbMethanol:
fuelweight = 6.6;
break;
case R.id.rbGasoline:
fuelweight = 6.2;
break;}
}
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.fuelsimple);
RadioGroup rgFuelType = ((RadioGroup) findViewById (R.id.rgFuelType));
rgFuelType.setOnCheckedChangeListener(this);
RadioButton rbMethanol = ((RadioButton) findViewById(R.id.rbMethanol));
RadioButton rbGasoline = ((RadioButton) findViewById(R.id.rbGasoline));
Button gen = ((Button) findViewById(R.id.submit));
gen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
EditText fuelUsed, pracLaps, featureLaps;
pracLaps = ((EditText) findViewById(R.id.pracLaps));
fuelUsed = ((EditText) findViewById(R.id.fuelUsed));
featureLaps = ((EditText) findViewById(R.id.featureLaps));
TextView textLPGValue, textFuelNeededValue, textBurnoffValue;
try{
double pracLapsVar = Double.parseDouble(pracLaps.getText().toString());
double fuelUsedVar = Double.parseDouble(fuelUsed.getText().toString());
double featureLapsVar = Double.parseDouble(featureLaps.getText().toString());
double efficiency = (pracLapsVar / fuelUsedVar);
double fuelNeeded = (featureLapsVar / efficiency);
double burnoff = (1.05 * (fuelNeeded * fuelweight));
Toast andJelly = Toast.makeText(Fuelsimple.this, String.valueOf(fuelweight), Toast.LENGTH_LONG);
andJelly.show();
textLPGValue = ((TextView) findViewById(R.id.textLPGValue));
textFuelNeededValue = ((TextView) findViewById(R.id.textFuelNeededValue));
textBurnoffValue = ((TextView) findViewById(R.id.textBurnoffValue));
textLPGValue.setText(String.valueOf(String.format("%.3f", efficiency)) + " laps per gallon");
textFuelNeededValue.setText(String.valueOf(String.format("%.3f", fuelNeeded)) + " gallons");
textBurnoffValue.setText(String.valueOf(String.format("%.2f", burnoff)) + " pounds");
} catch (NumberFormatException e) {Toast andEggs = Toast.makeText(Fuelsimple.this, "Please complete all fields and enter your fuel & lap info in decimals or whole numbers.", Toast.LENGTH_LONG); andEggs.show();}
catch (NullPointerException n) {Toast andEggs = Toast.makeText(Fuelsimple.this, "Please enter ALL lap and fuel data.", Toast.LENGTH_LONG);
andEggs.show();}
}}
);
}
public void onClick(View v) {
}
}
As far as I can tell, your variable fuelWeight is never initialized until a radio button is pressed. The simplest way to fix this would be to call setChecked(true) on either rbmethanol or rbGasoline after setting the listener, maybe right below where you initialize those variables. Doing it after setting the listener is important, because you want the switch statement to be resolved. Right now, before you press a radio button, fuelWeight, as with all numeric primitive data types, will be initialized to 0. This is probably the reason your first calculations are wrong.
You can also have a look at CheckChangeListener.It is called whenever the check state changes.
cbSave.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int visibility = isChecked ? View.VISIBLE : View.GONE;
findViewById(R.id.nameInstructions).setVisibility(visibility);
findViewById(R.id.name).setVisibility(visibility);
}
Below is my main activity file. I am stuck with the bottom area (commented out). I want to make it so that when I hit button b1, the text changes from what it is for default. So say it says "hello" by default, I want to switch the text to something like "how are you" when you press button b1. I have tried many things, but I always get errors. Can someone help me?
package com.wdmc85.donottouch;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class DoNotTouchActivity extends Activity
implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b1 = (Button) this.findViewById(R.id.b1);
b1.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
switch(v.getId())
{
case R.id.b1:
//WHAT DO I PUT IN HERE?? I WANT IT SO WHEN YOU HIT BUTTON B1, THE
//TEXT CHANGES FROM WHAT IT IS FOR DEFAULT. SO SAY IT SAYS "HELLO"
//AS DEFAULT, HOW DO I MAKE IT SO WHEN YOU PRESS BUTTON B1 THE TEXT
//CHANGES FROM "HELLO" TO "HOW ARE YOU?" I HAVE TRIED ALL SORTS OF
//THINGS BUT NOTHING HAS WORKED
break;
}
}
}
if want to change text of the button itself
switch(v.getId())
{
case R.id.b1:
Button b1 = (Button) v;
b1.setText("HOW ARE YOU?");
break;
}
if want to change text of the any other Textview
switch(v.getId())
{
case R.id.b1:
TextView tv = (TextView ) this.findViewById(R.id.<tvid>);
tv .setText("HOW ARE YOU?");
break;
}
You should use below method to change text of text view.
textView.setText("your text");
reference link is >> textview>>setText()
can use same for button and other views.
hey I'm creating an app with two switches on it that change the background of the xml.
however, if the user touches button 1 then 2 I want it to change the background from pic1 to pic2(on first button hit) then pic4(on second button hit)
but if the user touches button 2 then 1 I want it to change the background from pic1 to pic3(on first button hit) then pic4(on second button hit)
at the moment this is my script;
package com.jamie.game;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class level2 extends Activity implements OnClickListener{
Button button1;
View targetView;
Button button2;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.level2);
targetView = (View)findViewById(R.id.level2);
button1 = (Button) findViewById(R.id.button1);
button1.setVisibility(View.VISIBLE);
button1.setBackgroundColor(Color.TRANSPARENT);
button1.setOnClickListener((android.view.View.OnClickListener)this);
button2 = (Button) findViewById(R.id.button2);
button2.setVisibility(View.VISIBLE);
button2.setBackgroundColor(Color.TRANSPARENT);
button2.setOnClickListener((android.view.View.OnClickListener)this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==(R.id.button1)){
targetView.setBackgroundResource(R.drawable.pic2);
if(v.getId()==(R.id.button2)){
targetView.setBackgroundResource(R.drawable.pic4);
}else
if(v.getId()==(R.id.button2)){
targetView.setBackgroundResource(R.drawable.pic3);
if(v.getId()==(R.id.button2)){
targetView.setBackgroundResource(R.drawable.pic4);
}
}
}
but all this does is alternate between pic2 and pic3 on button clicks
Probably you need to create a variable to store the ID of the button that was just clicked. Then, when you receive the next click, you can just check this variable to know if the sequence matches your condition. For example, if you click the first button - store its ID in an int lastChecked variable, then when you click the second button - you should whether lastChecked equals to the first button ID. If it is - then you can run your View changing code. Hope this helps.
Describing the functionality of my application: I have put in a Relative Layout a TextView, an EditText and a button. All I am trying to do is: when the user writes something in the EditText and push the button, then the content of the EditText is appeared in the TextView(just like a chat-virtual chat). Everything works perfectly, but when the EditText is empty,and the button get pushed, an empty line is appeared in the TextView(and i don't want to..). Although I've tried to solve it using an if the empty line is still appearing in the TextView. I would be really greatfull, if you could help!!! Than you in advance!
Here is my code:
package teiath.android.appliacation;
import android.app.Activity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class M_chat extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/**Code for the scroll bars in the TextView. */
final TextView tv = (TextView)findViewById(R.id.TEXT_VIEW);
tv.setMovementMethod(new ScrollingMovementMethod());//for the scroll bars
/** Code for the scroll bars in the EditText. */
final EditText wr = (EditText)findViewById(R.id.EDIT_TEXT);
wr.setMovementMethod(new ScrollingMovementMethod());//for the scroll bars
final Button button = (Button) findViewById(R.id.btn1);//find the button by id in main.xml
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
String wrcontent = wr.getText().toString();//gets the text of the EditText and put it in "tvcontent" variable.
String tvcontent = tv.getText().toString();//gets the text of the textView and put it in "tvcontent" variable.
if (wrcontent!="")//if the EditText is not empty
{
//check if the TextView is empty or not
if (tvcontent!="")//If it is not empty...
{
tv.setText(tvcontent + "\n" + wrcontent);//add its current(TextView's text) text, new line and the text of the EditText as the new text of TextView.
//tv.setVisibility(0);//makes visible the textView with the cloud1.png background
wr.setText("");//set the text of the Edit Text as empty
//wrcontent = "";
}
else//if the TextView is empty...
{
tv.setText(wrcontent);//add the text of the editText as the new text of the TextView
wr.setText("");
}
}
/**if (wrcontent=="")
{
}*/
//finish();
}
});
}
}
Don't use !="" for String comparison. To check for empty text, use something like
if ( wrcontent != null && wrcontent.trim().length() == 0 ) {
Better yet, include Guava libraries in your code.