i have 2 edit Text in my application, 1 button to add the input numbers in the edit Text and 1 text view to display the result. I would like to put a toast message if my edit text tab is empty or null when i click the button. I have searched and tried all the solutions..and nothing seems to work. help please!!
here is my code for adding the two numbers.
MainActivity.java
package com.example.mycalc;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText1 = (EditText)findViewById(R.id.editText1);
final EditText editText2 = (EditText)findViewById(R.id.editText2);
Button button1 = (Button)findViewById(R.id.button1);
final TextView textView1 = (TextView)findViewById(R.id.textView1);
textView1.setText(" ");
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
double edit1 = Double.valueOf(editText1.getText().toString());
double edit2 = Double.valueOf(editText2.getText().toString());
double text = edit1 + edit2;
textView1.setText(String.valueOf(text));
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Your code will be:
To create and show a Toast use this code:
In order to work properly, you should replace this code:
with this:
You can try this two function for string empty, not empty or null. It is simple return true or false. It is very use for all projects.
when user clicks button check:
trim it to avoid blank spaces.
Add to your click listener check