6

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.

klefevre
  • 8,595
  • 7
  • 42
  • 71
Stuyvenstein
  • 2,340
  • 1
  • 27
  • 33

2 Answers2

7
if(str.equals("")){
    edittxt.setText("0");
}

WarrenFaith is right. Refer to this post to learn more about this issue: Java String.equals versus ==

Community
  • 1
  • 1
Cristian
  • 198,401
  • 62
  • 356
  • 264
  • If you stumble upon this issue, you should read about the differences between `equals()` and `==`. @Christian: maybe a bit more of an explanation would be nice, as this issue suggest that the basics are unclear for the OP :) – WarrenFaith Dec 27 '11 at 17:40
0

I would recommend surrounding your parseInt call with a try/catch block that catches a NumberFormatException which is probably the error being thrown (since you didn't specify, I can only guess), so it looks like:

public void update() {
    EditText edittxt = (EditText)findViewById(R.id.editText1);
    Integer i;
    try {   
       i = Integer.parseInt(edittxt.getText().toString());
       // do something with i
    } catch (NumberFormatException e) {
       // log and do something else like notify the user or set i to a default value
    }    
}
Pedantic
  • 5,032
  • 2
  • 24
  • 37