Необходимо отображать некоторые поля edittext, если пользователь установлен на флажок, иначе не отображать его

Мне нужно разработать одну регистрационную форму для Android-приложения. Здесь мне нужно ввести поле edittext, которое автоматически сохраняется в базе данных my sql с помощью мыльных веб-сервисов.

Здесь я должен следовать моим дополнительным требованиям

  1. Адрес доставки и выставления счета - это то же самое, что означает, что необходимо установить флажок, также необходимо вводить поле edittext адреса выставления счета только в то время, когда поле edittext адреса доставки должно отображать невидимое, а адрес выставления счета также должен сохраняться в полях базы данных адресов доставки.

  2. Адрес для выставления счета и доставки отличается, поэтому необходимо снять флажок, а также отобразить адрес доставки.

    (т.е.) мне нужно отобразить некоторые поля edittext, если пользователь установлен на флажок, иначе не отображать его.

Как я могу развить это. Пожалуйста, помогите мне.

Я использовал ниже код:

public class NewCustomer extends Activity{
private final String NAMESPACE = "http://xcart.com";
private final String URL = "http://10.0.0.75:8085/XcartLogin/services/RetailerWs?wsdl";
private final String SOAP_ACTION = "http://xcart.com/insertData";
private final String METHOD_NAME = "insertData";
CheckBox chkRememberMe;

Button btninsert;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.new_customer);

    btninsert = (Button)findViewById(R.id.register);
    btninsert.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {

             EditText Baddress = (EditText) findViewById(R.id.tf_address);
             EditText Bcity = (EditText) findViewById(R.id.tf_city);
             EditText Bstate = (EditText) findViewById(R.id.tf_state);
             EditText Bcountry = (EditText) findViewById(R.id.tf_country);
             EditText Bzipcode = (EditText) findViewById(R.id.tf_zipcode);
             EditText Saddress = (EditText) findViewById(R.id.tf_address1);
             EditText Scity = (EditText) findViewById(R.id.tf_city1);
             EditText Sstate = (EditText) findViewById(R.id.tf_state1);
             EditText Szipcode = (EditText) findViewById(R.id.tf_zipcode1);
             EditText Scountry = (EditText) findViewById(R.id.tf_country1);
        if(!(Baddress.getText().toString().length() == 0)){
                         if(!(Bcity.getText().toString().length() == 0)){
                             if(!(Bstate.getText().toString().length() == 0)){
                                 if(!(Bcountry.getText().toString().length() == 0)){
                                    if((checkZipcode1(zipcode1))){
                                         if(!(Saddress.getText().toString().length() == 0)){
                                             if(!(Scity.getText().toString().length() == 0)){
                                                 if(!(Sstate.getText().toString().length() == 0)){
                                                     if(!(Scountry.getText().toString().length() == 0)){
                                                         if((checkZipcode(zipcode))){
                     insertValues();
                       }   
                                                         else{
                                                              showAlertbox("Enter the 5 or 6 digit valid zipcode)!!"); 

                                                      }
                                                    }
                                                     else{
                                                             showAlertbox("Country is Required!!"); 

                                                  }
                                                }
                                                 else{
                                                      showAlertbox("State is Required!!"); 

                                              }
                                            }
                                             else{
                                                  showAlertbox("City is Required!!"); 

                                          }
                                        }else{
                                               showAlertbox("Address is Required!!"); 

                                       }
                                     }
                                     else{
                                          showAlertbox("Enter the 5 or 6 digit valid zipcode)!!"); 

                                  }
                                }
                                 else{
                                      showAlertbox("Country is Required!!"); 

                              }
                            }
                             else{
                                  showAlertbox("State is Required!!"); 

                          }
                        }
                         else{
                              showAlertbox("City is Required!!"); 

                      }
                    }else{
                           showAlertbox("Address is Required!!"); 

                   }
            }

         });

     }

         public void showAlertbox(String erroMessage) {
                 AlertDialog alertdialog = new AlertDialog.Builder(this.getParent())
    .create();
           // Setting Dialog Message
            alertdialog.setTitle("Error Message");
           alertdialog.setMessage(erroMessage);
          alertdialog.setButton("OK",
                  new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog,
                int which) {
            // TODO Auto-generated method stub
            //finish();
            return;
        }
    });

        alertdialog.show();

}




public void insertValues(){
 SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
  EditText Baddress = (EditText) findViewById(R.id.tf_address);
 String baddr = Baddress.getText().toString();
 EditText Bcity = (EditText) findViewById(R.id.tf_city);
 String bcity = Bcity.getText().toString();
 EditText Bstate = (EditText) findViewById(R.id.tf_state);
 String bstate = Bstate.getText().toString();
 EditText Bcountry = (EditText) findViewById(R.id.tf_country);
 String bcountry = Bcountry.getText().toString();
 EditText Bzipcode = (EditText) findViewById(R.id.tf_zipcode);
 String bzipcode = Bzipcode.getText().toString();
 EditText Saddress = (EditText) findViewById(R.id.tf_address1);
 String saddr = Saddress.getText().toString();
 EditText Scity = (EditText) findViewById(R.id.tf_city1);
 String scity = Scity.getText().toString();
 EditText Sstate = (EditText) findViewById(R.id.tf_state1);
 String sstate = Sstate.getText().toString();
 EditText Scountry = (EditText) findViewById(R.id.tf_country1);
 String scountry = Scountry.getText().toString();
 EditText Szipcode = (EditText) findViewById(R.id.tf_zipcode1);
 String szipcode = Szipcode.getText().toString();
  PropertyInfo baddress =new PropertyInfo();
    baddress.setName("Baddress");//Define the variable name in the web service method
    baddress.setValue(baddr);//Define value for fname variable
    baddress.setType(String.class);//Define the type of the variable
    request.addProperty(baddress);//Pass properties to the variable

  //Pass value for userPassword variable of the web service
    PropertyInfo bci =new PropertyInfo();
    bci.setName("Bcity");
    bci.setValue(bcity);
    bci.setType(String.class);
    request.addProperty(bci);
    PropertyInfo bsta =new PropertyInfo();
    bsta.setName("Bstate");//Define the variable name in the web service method
    bsta.setValue(bstate);//Define value for fname variable
    bsta.setType(String.class);//Define the type of the variable
    request.addProperty(bsta);//Pass properties to the variable

  //Pass value for userPassword variable of the web service
    PropertyInfo bcoun =new PropertyInfo();
    bcoun.setName("Bcountry");
    bcoun.setValue(bcountry);
    bcoun.setType(String.class);
    request.addProperty(bcoun); 
    PropertyInfo bzip =new PropertyInfo();
    bzip.setName("Bzipcode");
    bzip.setValue(bzipcode);
    bzip.setType(String.class);
    request.addProperty(bzip); 
    PropertyInfo saddress =new PropertyInfo();
    saddress.setName("Saddress");//Define the variable name in the web service method
    saddress.setValue(saddr);//Define value for fname variable
    saddress.setType(String.class);//Define the type of the variable
    request.addProperty(saddress);//Pass properties to the variable

  //Pass value for userPassword variable of the web service
    PropertyInfo sci =new PropertyInfo();
    sci.setName("Scity");
    sci.setValue(scity);
    sci.setType(String.class);
    request.addProperty(sci);
    PropertyInfo ssta =new PropertyInfo();
    ssta.setName("Sstate");//Define the variable name in the web service method
    ssta.setValue(sstate);//Define value for fname variable
    ssta.setType(String.class);//Define the type of the variable
    request.addProperty(ssta);//Pass properties to the variable

  //Pass value for userPassword variable of the web service
    PropertyInfo scoun =new PropertyInfo();
    scoun.setName("Scountry");
    scoun.setValue(scountry);
    scoun.setType(String.class);
    request.addProperty(scoun); 
    PropertyInfo szip =new PropertyInfo();
    szip.setName("Szipcode");
    szip.setValue(szipcode);
    szip.setType(String.class);
    request.addProperty(szip);
       SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.setOutputSoapObject(request);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

    try{
     androidHttpTransport.call(SOAP_ACTION, envelope);
        SoapPrimitive response = (SoapPrimitive)envelope.getResponse();

        TextView result = (TextView) findViewById(R.id.textView2);
        result.setText(response.toString());
        chkRememberMe = (CheckBox) findViewById(R.id.addresscheckbox);
           //testing if it is checked or unchecked
            if (chkRememberMe.isChecked())
            {
                //if it is check
                Saddress.setVisibility(View.VISIBLE);

            }else{
                Saddress.setVisibility(View.GONE);

        }


 }
 catch(Exception e){

 }

}

}

Как я могу развиваться выше моих требований. Пожалуйста, дайте мне несколько решений.

РЕДАКТИРОВАТЬ:

Я изменил мой код ниже, выглядит так:

chkIos = (CheckBox) findViewById(R.id.addresscheckbox);

    chkIos.setOnClickListener(new OnClickListener() {

      public void onClick(View v) {
                //is chkIos checked?
        if (((CheckBox) v).isChecked()) {
            Saddress.setEnabled(false);
        }

      }
    });

Теперь я должен запустить приложение и установить флажок означает, что мое окно консоли показывает следующую ошибку.

01-24 13:39:12.034: E/AndroidRuntime(1327): FATAL EXCEPTION: main
01-24 13:39:12.034: E/AndroidRuntime(1327): java.lang.NullPointerException
01-24 13:39:12.034: E/AndroidRuntime(1327):     at com.ssmobileproductions.catalogue.NewCustomer$1.onClick(NewCustomer.java:69)
01-24 13:39:12.034: E/AndroidRuntime(1327):     at android.view.View.performClick(View.java:2408)
01-24 13:39:12.034: E/AndroidRuntime(1327):     at android.widget.CompoundButton.performClick(CompoundButton.java:99)
01-24 13:39:12.034: E/AndroidRuntime(1327):     at android.view.View$PerformClick.run(View.java:8816)
01-24 13:39:12.034: E/AndroidRuntime(1327):     at android.os.Handler.handleCallback(Handler.java:587)
 01-24 13:39:12.034: E/AndroidRuntime(1327):    at android.os.Handler.dispatchMessage(Handler.java:92)
 01-24 13:39:12.034: E/AndroidRuntime(1327):    at android.os.Looper.loop(Looper.java:123)
  01-24 13:39:12.034: E/AndroidRuntime(1327):   at android.app.ActivityThread.main(ActivityThread.java:4627)
  01-24 13:39:12.034: E/AndroidRuntime(1327):   at java.lang.reflect.Method.invokeNative(Native Method)
   01-24 13:39:12.034: E/AndroidRuntime(1327):  at java.lang.reflect.Method.invoke(Method.java:521)
  01-24 13:39:12.034: E/AndroidRuntime(1327):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
   01-24 13:39:12.034: E/AndroidRuntime(1327):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
   01-24 13:39:12.034: E/AndroidRuntime(1327):  at dalvik.system.NativeStart.main(Native Method)

Я получил вышеупомянутую ошибку, в то время как я установил флажок. Как я могу решить эту ошибку. Пожалуйста, помогите мне.

РЕДАКТИРОВАТЬ:

chkIos = (CheckBox) findViewById(R.id.addresscheckbox);

    chkIos.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        if (((CheckBox) v).isChecked())
        {
             S_address = (TextView)findViewById(R.id.address1);  
             S_address.setVisibility(View.GONE);  

        Saddress = (EditText)findViewById(R.id.tf_address1);  
        Saddress.setVisibility(View.GONE);  
      }
        else
        {
             S_address = (TextView)findViewById(R.id.address1);  
             S_address.setVisibility(View.VISIBLE);  

       Saddress = (EditText)findViewById(R.id.tf_address1);  
        Saddress.setVisibility(View.VISIBLE);
      }
     }
    });

Теперь мне нужно запустить приложение и установить флажок означает, что адрес доставки невидим... Я должен снять флажок означает, что адрес доставки виден.

Теперь я сомневаюсь, что если мне нужно установить флажок, я могу сохранить значение saddress в базе данных. Здесь я должен сохранить значение baddress и сохранить в поле saddress...

1 ответ

Я хотел бы иметь все поля редактирования на экране все время, но есть те, которые вы не хотите, чтобы они вводили данные в отключенный (вызывая editText.setEnable(false)), если флажок установлен. Чтобы сделать это, зарегистрируйте onClickListener для флажка и в своем слушателе получите текущее состояние флажка и включите / отключите соответственно.

Другие вопросы по тегам