So this is the code i got so far:
Button calculate = (Button)findViewById(R.id.calculate);
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText sun = (EditText)findViewById(R.id.sun1);
EditText mon = (EditText)findViewById(R.id.mon1);
EditText tue = (EditText)findViewById(R.id.tue1);
EditText wed = (EditText)findViewById(R.id.wed1);
EditText thu = (EditText)findViewById(R.id.thu1);
EditText fri = (EditText)findViewById(R.id.fri1);
EditText sat = (EditText)findViewById(R.id.sat1);
EditText wage = (EditText)findViewById(R.id.wage);
double sun1 = Double.parseDouble(sun.getText().toString());
double mon1 = Double.parseDouble(mon.getText().toString());
double tue1 = Double.parseDouble(tue.getText().toString());
double wed1 = Double.parseDouble(wed.getText().toString());
double thu1 = Double.parseDouble(thu.getText().toString());
double fri1 = Double.parseDouble(fri.getText().toString());
double sat1 = Double.parseDouble(sat.getText().toString());
double wage1 = Double.parseDouble(wage.getText().toString());
TextView hours = (TextView)findViewById(R.id.hours);
TextView income = (TextView)findViewById(R.id.Income);
if(wage.getText().length()==0){
Toast.makeText(getContext(), "Enter the wage", Toast.LENGTH_SHORT).show();
}
else{
Calculator calc = new Calculator(sun1,mon1,tue1,wed1,thu1,fri1,sat1,wage1);
hours.setText(calc.hours()+"");
income.setText(calc.calc()+"");
}
As you can see, I want to display a toast whenever the user leaves any field empty. In this case, I have used only wage object to show where I am failing. I have also tried wage.getText().toString().equals("") and still my app crashes. Maybe it is the toast class that i am getting wrong. Using (this) instead of getContext() in the maketoast doesn't help either. Any suggestions?
You are getting an error, because your findViewById(...) isn't bound to the correct this. It should be outside of the onClick listener.
Typically, I would do something like the following:
public class MainActivity extends Activity {
private EditText sun;
private EditText mon;
private EditText tue;
private EditText wed;
private EditText thu;
private EditText fri;
private EditText sat;
private EditText wage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
instantiateViews();
}
private void instantiateViews() {
sun = (EditText) findViewById(R.id.sun1);
mon = (EditText) findViewById(R.id.mon1);
tue = (EditText) findViewById(R.id.tue1);
wed = (EditText) findViewById(R.id.wed1);
thu = (EditText) findViewById(R.id.thu1);
fri = (EditText) findViewById(R.id.fri1);
sat = (EditText) findViewById(R.id.sat1);
wage = (EditText) findViewById(R.id.wage);
}
//Write whatever other code you would here
}
Also, I recommend you use TextUtils.isEmpty over your current method to check that wage is empty.
Related
This question already has answers here:
OnClickListener in Android Studio
(5 answers)
Closed 6 years ago.
I am new to android studio and tried a tutorial where the presenter demonstrated his program but when I type out the code I am persistently getting an error like Cannot resolve Symbol setOnClickListener where the setOnClickListener is highlighted in red.
TextView Resultant = (TextView) findViewById(R.id.Resultant);
EditText Percentage_Input = (EditText) findViewById(R.id.Percentage_Input);
EditText Number_Input = (EditText) findViewById(R.id.Percentage_Input);
#Override
public View findViewById(#IdRes int id) {
return super.findViewById(R.id.Percentage_Input);
}
Button calc_btn = (Button) findViewById(R.id.calc_btn);
calc_btn.setOnClickListener(new View.OnClickListener(){
public void onClick((View) view); {
float percent = Float.parseFloat(Percentage_Input.getText().toString());
float dec = percent/100;
float Qty = Float.parseFloat(Number_Input.getText().toString());
float total = dec*Qty;
Resultant.setText(Float.toString(total));
}
})
I think your code is not in the right place. I see you are overriding findViewById (I wonder why) and rest of your code is also at the same level. You need to put all this code within a lifecycle method.
Maybe in onCreate()
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView Resultant = (TextView) findViewById(R.id.Resultant);
EditText Percentage_Input = (EditText) findViewById(R.id.Percentage_Input);
EditText Number_Input = (EditText) findViewById(R.id.Percentage_Input);
Button calc_btn = (Button) findViewById(R.id.calc_btn);
calc_btn.setOnClickListener(new View.OnClickListener() {
public void onClick((View) view); {
float percent = Float.parseFloat(Percentage_Input.getText().toString());
float dec = percent / 100;
float Qty = Float.parseFloat(Number_Input.getText().toString());
float total = dec * Qty;
Resultant.setText(Float.toString(total));
}
});
}
Also you are missing a semicolon ; at the end of setting OnClickListener.
Move ; and put at the end, this:
TextView Resultant = (TextView) findViewById(R.id.Resultant);
EditText Percentage_Input = (EditText) findViewById(R.id.Percentage_Input);
EditText Number_Input = (EditText) findViewById(R.id.Percentage_Input);
#Override
public View findViewById(#IdRes int id) {
return super.findViewById(R.id.Percentage_Input);
}
Button calc_btn = (Button) findViewById(R.id.calc_btn);
calc_btn.setOnClickListener(new View.OnClickListener(){
public void onClick((View) view) {
float percent = Float.parseFloat(Percentage_Input.getText().toString());
float dec = percent/100;
float Qty = Float.parseFloat(Number_Input.getText().toString());
float total = dec*Qty;
Resultant.setText(Float.toString(total));
}
});
Remove you method findViewById, this is some weird stuff, returning always the same view.
Put the rest of your code inside onCreate and add the missing ; at the end.
I want the fields entered by the user to be displayed as a list view of the studentnoText and courseField in a new activity..
public class Student extends Activity {
private String totalStudents [];
private EditText studentnoText;
private EditText studentnameText;
private EditText courseField;
private Spinner departmentSpinner;
private EditText dobField;
private Button registerButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student);
studentnoText = (EditText) findViewById(R.id.studentnoText);
studentnameText = (EditText) findViewById(R.id.studentnameText);
dobField = (EditText) findViewById(R.id.dobField);
courseField = (EditText) findViewById(R.id.courseField);
departmentSpinner = (Spinner) findViewById(R.id.departmentSpinner);
registerButton = (Button) findViewById(R.id.registerButton);
}
public void registerButtonPressed (View view){
Log.v("Register","Register Pressed!");
}
}
USE PUT EXTRA TO SEND DATA
mIntent.putExtra("TEXT", studentnoText.gettext().toString());
mIntent.putExtra("TEXT_1", studentName.gettext().toString());
USE GET EXTRA TO GET DATA
String strNO,strName;
strNO= extras.getString("TEXT");
strName = extras.getString("TEXT_1");
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.
I am unsure as to how to approach this.
I have taken some guidelines given by another person on here and have now gotten to the point of it crashing when I push the button (the monitor)
http://i.stack.imgur.com/C8WgN.png
I want to be able to post a toast notification when the button is pushed, and then have it go away after a few seconds
Also, is there a way to do it to where it will still create a toast notification although some of the info (like line2) is empty?
basic.java:
public class Basic extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic);
Spinner spinner = (Spinner) findViewById(R.id.Spinner01);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.state_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final Button display = (Button) findViewById(R.id.Button01);
display.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText firstField = (EditText) findViewById(R.id.First);
EditText lastField = (EditText) findViewById(R.id.Last);
EditText line1Field = (EditText) findViewById(R.id.Line1);
EditText line2Field = (EditText) findViewById(R.id.Line2);
EditText cityField = (EditText) findViewById(R.id.City);
EditText stateField = (EditText) findViewById(R.id.Spinner01);
EditText zipField = (EditText) findViewById(R.id.Zip);
//EditText phoneField = (EditText) findViewById(R.id.Telephone);
final Editable firstName = firstField.getText();
final Editable lastName = lastField.getText();
final Editable lineOne = line1Field.getText();
final Editable lineTwo = line2Field.getText();
final Editable city = cityField.getText();
final Editable state = stateField.getText();
final Editable zip = zipField.getText();
//final Editable phoneNumber = phoneField.getText();
Toast toDisplay = Toast.makeText(null, firstName, 10);
toDisplay.show();
}
});
}
}
I would like the layout of the toast to be multi-lined, and looking like a postal address
First Last
Street Line 1
Line 2
City, State Zip
Toast.makeText(Change.this, "First Last \n Street Line 1 \n Line 2 \n City, State Zip", Toast.LENGTH_SHORT).show();
By using above toast we can display the output in multilines.In above statement i am using static text in that place u put required fieds like
Toast.makeText(Change.this, firstField.getText().toString()+"\n"+ lastField.getText().toString()+"\n"+ City.getText().toString(), Toast.LENGTH_SHORT).show();
I am learning how to create UI elements. I have created a few EditText input fields. On the click of a Button I want to capture the content typed into that input field.
<EditText android:id="#+id/name" android:width="220px" />
That's my field. How can I get the content?
By using getText():
Button mButton;
EditText mEdit;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mButton = (Button)findViewById(R.id.button);
mEdit = (EditText)findViewById(R.id.edittext);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Log.v("EditText", mEdit.getText().toString());
}
});
}
Get value from an EditText control in android. EditText getText property use to get value an EditText:
EditText txtname = findViewById(R.id.name);
String name = txtname.getText().toString();
I guess you will have to use this code when calling the "mEdit" your EditText object :
myActivity.this.mEdit.getText().toString()
Just make sure that the compiler know which EditText to call and use.
I hope this one should work:
Integer.valueOf(mEdit.getText().toString());
I tried Integer.getInteger() method instead of valueOf() - it didn't work.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button rtn = (Button)findViewById(R.id.button);
EditText edit_text = (EditText)findViewById(R.id.edittext1);
rtn .setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Log.v("EditText value=", edit_text.getText().toString());
}
});
}
You might also want to take a look at Butter Knife. It aims at reducing the amount of boilerplate code by using annotation. Here is a simple example:
public class ExampleActivity extends ActionBarActivity {
#InjectView(R.id.name)
EditText nameEditText;
#InjectView(R.id.email)
EditText emailEditText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example);
Butterknife.inject(this);
}
#OnClick(R.id.submit)
public void onSubmit() {
Editable name = nameEditText.getText();
Editable email = emailEditText.getText();
}
}
Just add the following dependency to your build.gradle:
compile 'com.jakewharton:butterknife:x.y.z'
As an alternative there is also AndroidAnnotations.
Shortest & Simplest
getText(editText);
getText(button);
getText(textView);
Little Workaround
Just make method in your BaseActivity / create BaseActivity if you don't have.
public class BaseActivity extends AppCompatActivity{
public String getText(TextView tv) {
return tv.getText().toString().trim();
}
}
And extend your all activities by this BaseActivity.
public class YourActivity extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState){
getText(editText);
getText(button);
getText(textView);
}
}
Note that EditText, Button extends TextView, so I created only getText(TextView tv).
String value = YourEditText.getText().toString;
A more advanced way would be to use butterknife bindview. This eliminates redundant code.
In your gradle under dependencies; add this 2 lines.
compile('com.jakewharton:butterknife:8.5.1') {
exclude module: 'support-compat'
}
apt 'com.jakewharton:butterknife-compiler:8.5.1'
Then sync up.
Example binding edittext in MainActivity
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity {
#BindView(R.id.name) EditTextView mName;
...
public void onCreate(Bundle savedInstanceState){
ButterKnife.bind(this);
...
}
}
But this is an alternative once you feel more comfortable or starting to work with lots of data.
step 1 : create layout with name activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context=".MainActivity"
android:background="#c6cabd"
>
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17dp"
android:textColor="#ff0e13"
/>
<EditText
android:id="#+id/et"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tv"
android:hint="Input your country"
/>
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get EditText Text"
android:layout_below="#id/et"
/>
</RelativeLayout>
Step 2 : Create class Main.class
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
final TextView tv = (TextView) findViewById(R.id.tv);
final EditText et = (EditText) findViewById(R.id.et);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String country = et.getText().toString();
tv.setText("Your inputted country is : " + country);
}
});
}
}
If you are using Kotlin and wants to make it generic you can use the Extension function
Extension function:
fun EditText.getTextString(): String {
this.text.toString()
}
and call this method directly from your EditText
yourEditText.getTextString()
Try this code
final EditText editText = findViewById(R.id.name); // your edittext id in xml
Button submit = findViewById(R.id.submit_button); // your button id in xml
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
String string = editText.getText().toString();
Toast.makeText(MainActivity.this, string, Toast.LENGTH_SHORT).show();
}
});
Button kapatButon = (Button) findViewById(R.id.islemButonKapat);
Button hesaplaButon = (Button) findViewById(R.id.islemButonHesapla);
Button ayarlarButon = (Button) findViewById(R.id.islemButonAyarlar);
final EditText ders1Vize = (EditText) findViewById(R.id.ders1Vize);
final EditText ders1Final = (EditText) findViewById(R.id.ders1Final);
final EditText ders1Ortalama = (EditText) findViewById(R.id.ders1Ortalama);
//
final EditText ders2Vize = (EditText) findViewById(R.id.ders2Vize);
final EditText ders2Final = (EditText) findViewById(R.id.ders2Final);
final EditText ders2Ortalama = (EditText) findViewById(R.id.ders2Ortalama);
//
final EditText ders3Vize = (EditText) findViewById(R.id.ders3Vize);
final EditText ders3Final = (EditText) findViewById(R.id.ders3Final);
final EditText ders3Ortalama = (EditText) findViewById(R.id.ders3Ortalama);
//
final EditText ders4Vize = (EditText) findViewById(R.id.ders4Vize);
final EditText ders4Final = (EditText) findViewById(R.id.ders4Final);
final EditText ders4Ortalama = (EditText) findViewById(R.id.ders4Ortalama);
//
final EditText ders5Vize = (EditText) findViewById(R.id.ders5Vize);
final EditText ders5Final = (EditText) findViewById(R.id.ders5Final);
final EditText ders5Ortalama = (EditText) findViewById(R.id.ders5Ortalama);
//
final EditText ders6Vize = (EditText) findViewById(R.id.ders6Vize);
final EditText ders6Final = (EditText) findViewById(R.id.ders6Final);
final EditText ders6Ortalama = (EditText) findViewById(R.id.ders6Ortalama);
//
final EditText ders7Vize = (EditText) findViewById(R.id.ders7Vize);
final EditText ders7Final = (EditText) findViewById(R.id.ders7Final);
final EditText ders7Ortalama = (EditText) findViewById(R.id.ders7Ortalama);
//
/*
*
*
* */
kapatButon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// kapatma islemi
Toast.makeText(getApplicationContext(), "kapat",
Toast.LENGTH_LONG).show();
}
});
/*
*
*
* */
hesaplaButon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// hesap islemi
int d1v = Integer.parseInt(ders1Vize.getText().toString());
int d1f = Integer.parseInt(ders1Final.getText().toString());
int ort1 = (int) (d1v * 0.4 + d1f * 0.6);
ders1Ortalama.setText("" + ort1);
//
int d2v = Integer.parseInt(ders2Vize.getText().toString());
int d2f = Integer.parseInt(ders2Final.getText().toString());
int ort2 = (int) (d2v * 0.4 + d2f * 0.6);
ders2Ortalama.setText("" + ort2);
//
int d3v = Integer.parseInt(ders3Vize.getText().toString());
int d3f = Integer.parseInt(ders3Final.getText().toString());
int ort3 = (int) (d3v * 0.4 + d3f * 0.6);
ders3Ortalama.setText("" + ort3);
//
int d4v = Integer.parseInt(ders4Vize.getText().toString());
int d4f = Integer.parseInt(ders4Final.getText().toString());
int ort4 = (int) (d4v * 0.4 + d4f * 0.6);
ders4Ortalama.setText("" + ort4);
//
int d5v = Integer.parseInt(ders5Vize.getText().toString());
int d5f = Integer.parseInt(ders5Final.getText().toString());
int ort5 = (int) (d5v * 0.4 + d5f * 0.6);
ders5Ortalama.setText("" + ort5);
//
int d6v = Integer.parseInt(ders6Vize.getText().toString());
int d6f = Integer.parseInt(ders6Final.getText().toString());
int ort6 = (int) (d6v * 0.4 + d6f * 0.6);
ders6Ortalama.setText("" + ort6);
//
int d7v = Integer.parseInt(ders7Vize.getText().toString());
int d7f = Integer.parseInt(ders7Final.getText().toString());
int ort7 = (int) (d7v * 0.4 + d7f * 0.6);
ders7Ortalama.setText("" + ort7);
//
Toast.makeText(getApplicationContext(), "hesapla",
Toast.LENGTH_LONG).show();
}
});