任何人都知道如果在EditText没有值的情况下防止Android应用程序崩溃吗?
编辑:对不起,我用手机发了这个帖子。你走了:import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class RandomButtonActivity extends Activity implements SensorEventListener
{
public float x = 0, y = 0, z = 0;
public float a = 10, b = 10, c = 10;
public float k = 4;
public int j = 0, i = 0;
public int rand = 0;
public String j1;
public String i1;
TextView testo;
TextView ultimo;
EditText limiteMin;
EditText limiteMax;
Random generator = new Random();
SensorManager sm;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
testo = (TextView) findViewById(R.id.textView1);
ultimo = (TextView) findViewById(R.id.textView4);
limiteMin = (EditText) findViewById(R.id.editText2);
limiteMax = (EditText) findViewById(R.id.EditText01);
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
random();
}
public void onSensorChanged(SensorEvent event)
{
x = event.values[0];
y = event.values[1];
z = event.values[2];
if(x>a+k || x<a-k || y>b+k || y<b-k || z>c+k || z<c-k)
{
rand = random();
}
a = x;
b = y;
c = z;
}
public int random()
{
j = Integer.parseInt(limiteMin.getText().toString());
i = Integer.parseInt(limiteMax.getText().toString());
int v = 0;
if(i==0 && j==0)
{
v = generator.nextInt();
}
else if(j>=i && j!=0)
{
v = 0;
}
else
{
i = i+1;
do
{
v = generator.nextInt(i);
testo.setText("Random: "+v);
}
while(v<j);
}
testo.setText("Random: "+v);
ultimo.setText("Random precedente: "+rand);
return v;
}
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
}
只有当2个EditTexts中的1个为空且调用方法random()时,程序才会崩溃。
答案 0 :(得分:2)
应用以下代码
EditText et= (EditText)findViewById(R.id.editText);
if(et.getText.toString.equals(null) || et.getText.toString.equals(""))
{
Toast.makeText(this,"please enter something in text box",Toast.LENGTH_LONG).show();
}
答案 1 :(得分:0)
您应该使用==运算符检查空值。
et.getText() == null
对空值调用toString()会抛出空指针。这是你崩溃的原因吗?