2015-03-07 4 views
0

Поправьте меня, если мой Validation неправильноКакова правильная проверка?

if (sqlName.getText().toString().length() == 0) { 
     sqlName.setError("Name is required!"); 
    } else if (sqlAge.getText().toString().length() == 0) { 
     sqlAge.setError("Age is required!"); 
    }else if(statusbutton.getText().toString().length() == 0){ 
     statusbutton.setError("Please Select Status before you Proceed"); 
    }else if (sqlcycle.getText().toString().length() == 0) { 
     sqlcycle.setError("Cycle Lenght is required!"); 
    }else if (sqlperiod.getText().toString().length() == 0) { 
     sqlperiod.setError("Period is required!"); 
    } 
} catch (Exception e) { 
    didItWork = false; 
    String error = e.toString(); 
    Dialog d = new Dialog(this); 
    d.setTitle("FACK"); 
    TextView tv = new TextView(this); 
    tv.setText(error); 
    d.setContentView(tv); 
    d.show(); 
} finally { 
    if (didItWork) { 
     Toast.makeText(Main.this, "USER Information has been Save", 1000).show(); 
    } 
    else { 
     Intent main = new Intent(this, CalendarMain.class); 
     startActivity(main); 
     finish(); 
    } 
} 

Проблема: Я хочу vaidate сначала, прежде чем перейти к следующему действию , но до сих пор, несмотря на то EditText пустой, он по-прежнему идти к следующей деятельности.

+0

Вы должны улучшить свой стандарт кодирования. Это совсем не выглядит хорошо – Fahim

+1

Какое значение по умолчанию имеет 'didItWork'? Похоже, что это всегда «ложь». –

+0

Что означает u, всегда всегда ложное? я не понимаю? im beginner and still learning –

ответ

0

Инициализация вашего didItWork = false;

и вставить еще код также как ниже

else if (sqlperiod.getText().toString().length() == 0) { 
    sqlperiod.setError("Period is required!"); 
} 
else 
{ 
    didItWork=true; 
} 

и в вашем, наконец, блок

finally { 
if (didItWork) { 
    Toast.makeText(Main.this, "USER Information has been Save", 1000).show(); 
    Intent main = new Intent(this, CalendarMain.class); 
    startActivity(main); 
    finish(); 
} 
else { 
    Toast.makeText(Main.this, "Error", 1000).show(); 
} 

}

0

Прежде всего использовать этот

sqlName.getText().toString().trim().length() 

вместо

sqlName.getText().toString().length() 

это не будет перейти к следующему экрану, если вы начнете с пробелами

Я понятия не имею, где ваш код будет исключения нулевого указателя, но я просто пытался реализовать его и я не получаю такие исключения , Вот код

public class MainActivity extends Activity { 
    EditText edt1, edt2, edt3, edt4, edt5; 
    Button btn; 
    boolean didItWork = true; 
    Dialog d; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     btn = (Button) findViewById(R.id.btn); 
     edt1 = (EditText) findViewById(R.id.edt1); 
     edt2 = (EditText) findViewById(R.id.edt2); 
     edt3 = (EditText) findViewById(R.id.edt3); 
     edt4 = (EditText) findViewById(R.id.edt4); 

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

     btn.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       try { 
        if (edt1.getText().toString().length() == 0) { 
         // sqlName.setError("Name is required!"); 
        } else if (edt2.getText().toString().length() == 0) { 
         // sqlAge.setError("Age is required!"); 
        } else if (edt3.getText().toString().length() == 0) { 
         // statusbutton.setError("Please Select Status before you Proceed"); 
        } else if (edt4.getText().toString().length() == 0) { 
         // sqlcycle.setError("Cycle Lenght is required!"); 
        } else if (edt5.getText().toString().length() == 0) { 
         // sqlperiod.setError("Period is required!"); 
        } 
       } catch (Exception e) { 
        didItWork = false; 
        String error = e.toString(); 
        d = new Dialog(getApplicationContext()); 
        d.setTitle("FACK"); 
        TextView tv = new TextView(getApplicationContext()); 
        tv.setText(error); 
        d.setContentView(tv); 
        d.show(); 
        Toast.makeText(MainActivity.this, 
          "USER Informatisdefsdfon has been Save", 1000) 
          .show(); 
       } finally { 
        if (didItWork) { 
         Toast.makeText(MainActivity.this, 
           "USER Information has been Save", 1000).show(); 
        } else { 
         Intent main = new Intent(getApplicationContext(), 
           CalendarMain.class); 
         startActivity(main); 
         finish(); 
        } 
       } 
      } 
     }); 

    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 

} 

И раскладка идет как этот

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
> 

    <EditText 
     android:id="@+id/edt1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/hello_world" /> 
     <EditText 
     android:id="@+id/edt2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/hello_world" /> 
      <EditText 
     android:id="@+id/edt3" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/hello_world" /> 
       <EditText 
     android:id="@+id/edt4" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/hello_world" /> 

        <EditText 
     android:id="@+id/edt5" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/hello_world" /> 
         <Button 
     android:id="@+id/btn" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/hello_world" /> 

</LinearLayout> 
+0

tnx ,, .. я получаю ее но возникает другая проблема, .. новой проблемой является NullPointerException? Вы можете определить проблему? –

+0

Знаете ли вы, что указывает на проблему? * THE STACKTRACE *, он буквально сообщает вам, в какой строке он столкнулся с ошибкой. – EpicPandaForce