当EditText
为空且按下按钮时,android应用程序崩溃
如果一个或多个edittext为空并按下该按钮会导致错误。
这是代码:
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");
}
当edittext为空并按下按钮时,android应用程序崩溃 如果一个或多个edittext为空
你能帮帮我吗答案 0 :(得分:1)
试试这个,你需要首先检查你的Edittext
值是否为空
使用 isEmpty(CharSequence str) 检查您的Edittext
是否为空
如果字符串为null或0-length,则返回true。
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();
}
}
});