I have the following code which I want to use to make sure that my edittext wont be empty. So if the first drawn 0 (zero) is removed it must revert to 0 when the focus changes, Here is the app so far:
package your.test.two;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class TesttwoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText edtxt = (EditText)findViewById(R.id.editText1);
// if I don't add the following the app crashes (obviously):
edtxt.setText("0");
edtxt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
update();
}
});
}
public void update() {
EditText edittxt = (EditText)findViewById(R.id.editText1);
Integer i = Integer.parseInt(edittxt.getText().toString());
// If i is an empty value, app crashes so if I erase the zero
//on the phone and change focus, the app crashes
}
}
I have tried the following in the update() method:
String str = edittxt.getText().toString();
if (str == "") {
edittxt.setText("0");
}
But it doesn't work. How can I allow the edittext to never be emty, revert to zero when empty but not when a value exists. I have already made sure that the edittext can only allow numerical values.
if(str.equals("")){
edittxt.setText("0");
}
WarrenFaith is right. Refer to this post to learn more about this issue: Java String.equals versus ==
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With