Значения EditText не попадают в раздел кликов - PullRequest
0 голосов
/ 21 августа 2011

Я все еще очень плохо знаком с Android.Я много занимался программированием на html, php, Visual Basic и некоторых языках C, но Java / Android все еще для меня.

Когда я запускаю приведенный ниже код и пытаюсь проверить синтаксис поля EditText box_email, я получаю нулевое значение, и он выходит из строя эмулятора.Если я передаю ей строку по умолчанию, такую ​​как lll@aol.com, она работает, а также работает, если я передаю ее lll @ blah.Он правильно идентифицирует действительный и недействительный синтаксис, но не может видеть никаких данных, передаваемых из формы.

    package test.com;

    import java.util.regex.Pattern;

    import android.app.Activity;
    import android.graphics.drawable.AnimationDrawable;
    import android.media.MediaPlayer;
    import android.os.Bundle;
    import android.text.Editable;
    import android.text.TextWatcher;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ImageView;
    import android.widget.Spinner;


    public class testActivity extends Activity {
        int MediaState;
        ImageView animation;
        String EMAILTEXT;
        EditText box_email, box_password, box_username;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Eula.show(this);
    IntroMedia(0);
            animation = (ImageView)findViewById(R.id.imageAnimation);
            animation.setBackgroundResource(R.drawable.fpanim);     // the frame-by-frame animation defined as a xml file within the drawable folder
            Button d;
            (d = (Button)findViewById(R.id.next1button)).setBackgroundDrawable(this.getResources().getDrawable(R.drawable.next));
        }

        public void myClickHandler1(View view) {
            setContentView(R.layout.credentials);
            IntroMedia(1);
            Spinner spinner = (Spinner) findViewById(R.id.box_state);    
            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.states_array, android.R.layout.simple_spinner_item);    
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);    
            spinner.setAdapter(adapter);
            EditText box_email = (EditText) findViewById(R.id.box_email);

            //Button mainNext = (Button) findViewById(R.id.nextScreenMain); 
    //Filter Username
            EditText box_username = (EditText) findViewById(R.id.box_username); 

            box_username.addTextChangedListener(new TextWatcher() {

                public void afterTextChanged(Editable s) {

                    String filtered_str = s.toString();

                        if (filtered_str.matches(".*[^a-z^0-9^A-Z].*")) {

                        filtered_str = filtered_str.replaceAll("[^a-z^0-9^A-Z]", "");

                        s.clear();
                        s.append(filtered_str);



                    }

                }

                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

                    public void onTextChanged(CharSequence s, int start, int before, int count) {}
                });
    //End Filter Username
    //Filter Password
            EditText box_password = (EditText) findViewById(R.id.box_password); 
            box_password.addTextChangedListener(new TextWatcher() {

                public void afterTextChanged(Editable s) {

                    String filtered_str = s.toString();

                        if (filtered_str.matches(".*[^a-z^0-9^A-Z].*")) {

                        filtered_str = filtered_str.replaceAll("[^a-z^0-9^A-Z]", "");

                        s.clear();
                        s.append(filtered_str);


                    }

                }

                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

                    public void onTextChanged(CharSequence s, int start, int before, int count) {}
                });
    //End Filter Password
    //Filter Email


            box_email.addTextChangedListener(new TextWatcher() {

                public void afterTextChanged(Editable s) {

                    String filtered_str = s.toString();

                        if (filtered_str.matches(".*[^a-z^0-9^A-Z.@_/-].*")) {

                        filtered_str = filtered_str.replaceAll("[^a-z^0-9^A-Z.@_/-]", "");

                        s.clear();
                        s.append(filtered_str);

                    }

                }

                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

                    public void onTextChanged(CharSequence s, int start, int before, int count) {}
                });
    //End Filter Email 
            Button cred_submit;
            cred_submit = (Button)findViewById(R.id.cred_submit);
            cred_submit.setOnClickListener(myClickHandler_Cred_Submit);    


        }

        private OnClickListener myClickHandler_Cred_Submit = new OnClickListener()   
        {   

            public void onClick(View v)   
            {          
                IntroMedia(1); 
                EMAILTEXT = box_email.getText().toString();   

                //Validate Email Pattern
                if (checkEmail(EMAILTEXT)){
                    //is valid
                    setContentView(R.layout.validinput);
                } else {
                    //is not
                    setContentView(R.layout.invalidinput);
                }
                //End Validate EMail Pattern

                //process & validate data
                //submit data to website
                //enter data into prefs   

            }   

        };   



        public void myClickHandler_Cred_Cancel(View view) {
        finish();   
        }
        @Override
        /**
         * This method is called whenever the Activity becomes visible or invisible to the user.
         * During this method call its possible to start the animation.
         */
        public void onWindowFocusChanged (boolean hasFocus) {
            super.onWindowFocusChanged(hasFocus);
            AnimationDrawable frameAnimation = 
                (AnimationDrawable) animation.getBackground();
            if(hasFocus) {
                frameAnimation.start();
            } else {
                frameAnimation.stop();
            }
        }

        public void IntroMedia(int MediaState) {

             MediaPlayer mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.smallmusicfile);
            if (MediaState == 1){
                mPlayer.pause();
                mPlayer.seekTo(mPlayer.getDuration()); 
                mPlayer.stop();
                mPlayer.release();
             }
             if (MediaState == 0){
                    mPlayer.start();
                   MediaState = 1;
                 } 

            }

        public final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile("[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" + "\\@" + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" + "\\." + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + ")+"); 

        private boolean checkEmail(String email) {return EMAIL_ADDRESS_PATTERN.matcher(email).matches(); } 
    }

Это мой main.xml

    <?xml version="1.0" encoding="utf-8"?>

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:layout_width="fill_parent" 
    android:id="@+id/mainLayout"
    android:layout_height="fill_parent" 
    android:orientation="vertical"
    android:layout_centerVertical="true"


    >

    <ImageView android:id="@+id/imageAnimation"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:layout_gravity="center"
    android:adjustViewBounds="true"

    />
    <RelativeLayout 
    android:layout_width="fill_parent" 
    android:id="@+id/relativeLayout1" 
    android:layout_height="fill_parent" 
    android:layout_alignParentBottom="true"
    android:layout_centerVertical="true">   
      <com.google.ads.AdView android:id="@+id/adView"
                             android:layout_width="wrap_content"
                             android:layout_height="wrap_content"
                             ads:adUnitId="XXXXXXXXXXXXXXX"
                             ads:adSize="BANNER"
                             ads:loadAdOnCreate="true"
                             android:layout_alignParentBottom="true"/>
      <Button android:layout_height="wrap_content" android:onClick="myClickHandler1" android:layout_width="wrap_content" android:id="@+id/next1button" android:layout_above="@+id/adView" android:layout_centerHorizontal="true"></Button>

    </RelativeLayout> 
    </RelativeLayout>

Это мой файл credentials.xml

    <?xml version="1.0" encoding="utf-8"?>

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:layout_width="fill_parent" 
    android:id="@+id/mainLayout"
    android:layout_height="fill_parent" 
    android:orientation="vertical"
    android:layout_centerVertical="true"


    >

    <TextView android:text="Username: REQUIRED - Unique and Alpha Numeric " android:layout_height="wrap_content" android:id="@+id/label_username" android:layout_width="fill_parent" android:layout_alignParentTop="true" android:layout_centerHorizontal="true"></TextView>
    <EditText android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/box_username" android:layout_below="@+id/label_username" android:layout_alignParentRight="true" android:layout_alignParentLeft="true"></EditText>
    <TextView android:text=" " android:layout_height="wrap_content" android:id="@+id/blank_1" android:layout_width="fill_parent" android:layout_below="@+id/box_username" android:layout_centerHorizontal="true"></TextView>
    <TextView android:text="Password: REQUIRED - Alpha Numeric" android:layout_height="wrap_content" android:id="@+id/label_password" android:layout_width="fill_parent" android:layout_below="@+id/blank_1" android:layout_centerHorizontal="true"></TextView>
    <EditText android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/box_password" android:layout_below="@+id/label_password" android:layout_alignParentRight="true" android:layout_alignParentLeft="true" android:inputType="textPassword"></EditText>
    <TextView android:text=" " android:layout_height="wrap_content" android:id="@+id/blank_2" android:layout_width="fill_parent" android:layout_below="@+id/box_password" android:layout_centerHorizontal="true"></TextView>
    <TextView android:text="Email: Optional" android:layout_height="wrap_content" android:id="@+id/label_email" android:layout_width="fill_parent" android:layout_below="@+id/blank_2" android:layout_centerHorizontal="true"></TextView>
    <EditText 
    android:layout_height="wrap_content" 
    android:layout_width="wrap_content" 
    android:id="@+id/box_email" 
    android:layout_below="@+id/label_email" 
    android:layout_alignParentRight="true" 
    android:layout_alignParentLeft="true" 
    android:inputType="textEmailAddress">
    </EditText>
    <TextView android:text=" " android:layout_height="wrap_content" android:id="@+id/blank_3" android:layout_width="fill_parent" android:layout_below="@+id/box_email" android:layout_centerHorizontal="true"></TextView>
    <TextView android:text="State: Optional - If in the U.S. only." android:layout_height="wrap_content" android:id="@+id/label_state" android:layout_width="fill_parent" android:layout_below="@+id/blank_3" android:layout_centerHorizontal="true"></TextView>
    <Spinner android:layout_height="wrap_content" android:id="@+id/box_state" android:layout_below="@+id/label_state" android:layout_width="fill_parent" android:prompt="@string/state_prompt" android:layout_alignParentLeft="true" android:layout_alignParentRight="true"></Spinner>
    <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Submit" android:id="@+id/cred_submit" android:layout_below="@+id/box_state" android:layout_alignParentLeft="true" android:onClick="myClickHandler_Cred_Submit"></Button>
    <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Cancel" android:id="@+id/cred_cancel" android:layout_below="@+id/box_state" android:layout_alignParentRight="true" android:onClick="myClickHandler_Cred_Cancel"></Button>




    <RelativeLayout 
    android:layout_width="fill_parent" 
    android:id="@+id/relativeLayout1" 
    android:layout_height="fill_parent" 
    android:layout_alignParentBottom="true"
    android:layout_centerVertical="true">   
      <com.google.ads.AdView android:id="@+id/adView"
                             android:layout_width="wrap_content"
                             android:layout_height="wrap_content"
                             ads:adUnitId="XXXXXXXXXXXXXXX"
                             ads:adSize="BANNER"
                             ads:loadAdOnCreate="true"
                             android:layout_alignParentBottom="true"/>


    </RelativeLayout> 




    </RelativeLayout> 

Буду признателен за любую помощь.Спасибо.

1 Ответ

3 голосов
/ 21 августа 2011

Ваш почтовый ящик имеет значение null, поскольку вы инициализируете локальную переменную box_email

EditText box_email = (EditText) findViewById(R.id.box_email);

, а не поле класса. Так что просто замените указанную строку на:

box_email = (EditText) findViewById(R.id.box_email);

И это сработает.

И несколько советов.

  1. Не забывайте о соглашениях Java-кода.

  2. Вы не должны вызывать setContentView с различными раскладками в разных местах в вашей деятельности без достаточных причин, потому что вам будет головной болью быть уверенным, что поля представления находятся в реальном состоянии, а не в нулевом. Используйте несколько действий вместо этого. Один вид деятельности - один макет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...