Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent edittext from being empty

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.

like image 588
Stuyvenstein Avatar asked Dec 27 '11 16:12

Stuyvenstein


1 Answers

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

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

like image 53
Cristian Avatar answered Nov 02 '22 00:11

Cristian