Reputation:
When EditText
is empty and button is pressed android application crashes
if 1 or more edittext is empty and pushing the button causes error.
this is the code:
public class Tab4Weight extends Fragment {
EditText firstNumber;
EditText secondNumber;
TextView addResult;
Button btnAdd;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab4weight, container, false);
firstNumber = (EditText)view.findViewById(R.id.txtNumber1);
secondNumber = (EditText)view.findViewById(R.id.txtNumber2);
addResult = (TextView)view.findViewById(R.id.txtResult);
btnAdd = (Button)view.findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String value1= firstNumber.getText().toString();
String value2= secondNumber.getText().toString();
int a=Integer.parseInt((value1));
int b=Integer.parseInt((value2));
int sum= getCoordinates(a,b);
Toast.makeText(getActivity(),"Weight in Kg: " +
String.valueOf(sum),Toast.LENGTH_LONG).show();
}
private int getCoordinates (int coordA, int coordB){
int results = 0;
if (coordA < 7000 && coordB < 30 && coordB > -45)
{
results = 7400;
}
else{
if (coordA==8000 && coordB ==30)
{
results = 7100;
}
firstNumber.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {int jumlah = Integer.parseInt(firstNumber.getText().toString());
if( firstNumber.getText().toString().equals("")||jumlah > 10001
&& jumlah < 10999) {
firstNumber.setText("11000");
return;
}
else {
if (firstNumber.getText().toString().equals("") || jumlah >
11001 && jumlah < 11999) {
firstNumber.setText("12000");
}
else {
if (firstNumber.getText().toString().equals("") ||
jumlah > 12001 && jumlah < 12999) {
firstNumber.setText("13000");
}
when edittext is empty and button is pressed android application crashes if 1 or more edittext is empty
can you help me
Upvotes: 0
Views: 106
Reputation: 69754
try this you need to check first that your Edittext
value is empty or not
use isEmpty(CharSequence str) to check whether your Edittext
is empty or not
Returns true if the string is null or 0-length.
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!TextUtils.isEmpty(firstNumber.getText().toString())&&!TextUtils.isEmpty(secondNumber.getText().toString())){
String value1= firstNumber.getText().toString();
String value2= secondNumber.getText().toString();
int a=Integer.parseInt((value1));
int b=Integer.parseInt((value2));
int sum= getCoordinates(a,b);
Toast.makeText(getActivity(),"Weight in Kg: " +
String.valueOf(sum),Toast.LENGTH_LONG).show();
}else {
Toast.makeText(getActivity(), "value is empty", Toast.LENGTH_SHORT).show();
}
}
});
Upvotes: 1