multiple if statement with different conditions - java

I try to check user input on my EditText, if there's one or more null value, the validation image will be changed into red color and it the page will be not moved until all field is filled. I'm using multiple if statement with different conditions in my case but
I get a problem, when I input into two EditText and another EditText is null, the page move from current page into new page, when it should not be moved.
this is my code :
if (nama_pp.getText().toString().length()==0){img_namalengkap_pp.setImageResource(R.drawable.espaj_red_checklist);}
if (ibu_pp.getText().toString().length()==0){img_namaibu_pp.setImageResource(R.drawable.espaj_red_checklist);}
if (nomor_bukti_pp.getText().toString().length()==0){img_nomeridentitas_pp.setImageResource(R.drawable.espaj_red_checklist);}
if (tempat_pp.getText().toString().length()==0){img_tempat_pp.setImageResource(R.drawable.espaj_red_checklist);}
if (ttl_pp.getText().toString().length()==0){img_tgllahir_pp.setImageResource(R.drawable.espaj_red_checklist);}
if (alamat_pp.getText().toString().length()==0){img_alamat_pp.setImageResource(R.drawable.espaj_red_checklist);}
if (kota_pp.getText().toString().length()==0){img_kota_pp.setImageResource(R.drawable.espaj_red_checklist);}
if (kdtlp1_pp.getText().toString().length()==0){img_telepon_pp.setImageResource(R.drawable.espaj_red_checklist);}
if (telp1_pp.getText().toString().length()==0){img_telepon_pp.setImageResource(R.drawable.espaj_red_checklist);}
else {
getFragmentManager().beginTransaction().replace(R.id.frame_container, new TertanggungPolis()).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
}
is there a faster way to code things like that and the best solution for my problem? thank you very much.

You can put all the edit text in one array list and the corresponding image views in another one.
For empty string we can use, TextUtils.isEmpty(string) which returns true if the string is null or empty.
Try this:
ArrayList<EditText> editTexts = new ArrayList<EditText>();
editTexts.add(nama_pp);
editTexts.add(editetext2);
ArrayList<ImageView> imageViews = new ArrayList<ImageView>();
imageViews.add(image1);
imageVioew.add(Image2);
boolean nextPage = true;
for (int i = 0; i < editTexts.length();i++)
if (editText[i].isEmpty(editText[i].getText.toString())) {
imageViews[i].setImageResource(R.drawable.espaj_red_checklist);
nextPage = false;
}
}
Before moving to next page , You can check something like this:
if (nextPage) {
//Move to next page
}

You can put all your objects in a list, and iterate through that list like so:
ArrayList<EditText> editTexts = new ArrayList<>(9);
editTexts.add(nama_pp);
editTexts.add(...);
boolean ready = true;
for (EditText editText : editTexts)
if (editText.getText().toString().length() == 0) { ready = false; break; }
if (ready)
getFragmentManager().beginTransaction().replace(R.id.frame_container, new TertanggungPolis()).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
else img_telepon_pp.setImageResource(R.drawable.espaj_red_checklist);
It's less typing at least.
Sebastien Bianchi's idea is a good, also.

why not add a textWatcher? It's more objective.you dont need to conside the condition, you just ask each EditText is your input is valid.less work, more expansibility.You will never bothered there are so many edittexts

It's moving to the next page because your else is only matched up with the last if. So as long as the last if test fails, it will transition to the next page.
A simple fix would be to replace all but the first if statement with else if:
if (condition1) {
} else if (condition2) {
} else {
getFragmentManager() ...
}

You could make it more readable by using || and creating an isEmpty() method:
private boolean isEmpty(EditText et) {
return et.getText().toString().length() == 0;
}
then
if (isEmpty(ibu_pp) || isEmpty(nomor_bukti_pp) || ... ) {
img_telepon_pp.setImageResource(R.drawable.espaj_red_checklist);
}

Related

How to get all required strings in a string array before a break

We were given a task to make a program that takes the input of the user. there two types of input the user can use, 1st is the "Type in the Size" and the second is "Type in the style" either way the user can just input in the 1st field or the 2nd field. when the users clicks ok the two inputs will be use to sortout a arraylist which contains the type of size and style in it.
public void viewResult(String style, String size) {
style = style.toLowerCase();
size = size.toLowerCase();
new_list = new ArrayList<>();
for(Items_container items:current_arrayList)
{
if (items.getStyle().toLowerCase().contains(style) && items.getSize().toLowerCase().contains(size))
{
new_list.add(items);
break;
}
else if (items.getSize().toLowerCase().contains(size)) {
new_list.add(items);
break;
}
else if (items.getStyle().toLowerCase().contains(style)) {
new_list.add(items);
break;
}
}
current_arraylist.clear();
adapter.filterSearch(new_list);
if (new_list.size() == 0) {
results.setText("Search not found");
} else {
results.setText("Results");
}
}
this is the method that I use to sortout out the Items_container now it does work fine (I guess)
but the problem is for example the user inputs "large" in the size input field and "blazzing" in the style input field the program must sort the items_container using the given inputs but it is not working because the program also includes all the items that has the same size or the same style.
I tried adding a break to the loop but now it only shows one data and what if there two or more data that matches the givens inputs, how can I do that?
You should check first if both conditions are set. That way you can separate if either one matches and if both match. Maybe put singular matches in a separate list in case no items match both conditions, but that's up to you.
And as others already said, break stops the loop, continue moves to the next item.
like code below:
for (int i = 0; i <current_arrayList.size() ; i++) {
if(current_arrayList.get(i).getStyle().toLowerCase().contains(style)
&& current_arrayList.get(i).getSize().toLowerCase().contains(size))
{
new_list.add(current_arrayList.get(i));
//if used break ,stop loop
}
else if (current_arrayList.get(i).getSize().toLowerCase().contains(size)) {
new_list.add(current_arrayList.get(i));
}
else if (current_arrayList.get(i).getStyle().toLowerCase().contains(style)) {
new_list.add(current_arrayList.get(i));
}
}
current_arraylist.clear();
adapter.filterSearch(new_list);
adapter.notifyDataSetChanged();

My TextView to display an array isn't working?

In my app I have a method that is designed to put a new string into a string array in the first empty index. It is then designed to display that array in a textbox that has ten lines. For some reason, this is not working. I have used a Log to display the array contents in Logcat, but this is not appearing. So I thought I'd come here and ask if anyone can see any obvious errors that would cause it not to work? If you need any more details, such as the class from which the array is used, let me know! :)
The method:
String playerInvTemp[] = thePlayer.getPlayerInv();
for (int i=0; i < playerInvTemp.length; i++)
{
if ((!playerInvTemp[i].isEmpty()) || playerInvTemp[i] == null)
{
thePlayer.setPlayerInv("Torch", i);
Log.i(tag,thePlayer.getPlayerInv(1));
playerInvTemp = thePlayer.getPlayerInv();
Log.i(tag,playerInvTemp[1]);
StringBuilder builder = new StringBuilder();
for (String s : playerInvTemp) {
builder.append(s + " ");
invText.setText(builder.toString());
}
break;
}
}
It is a very bad practice to change the array you are iterating on inside loop.
Probably, you have an array of empty strings, in that case you condition:
((!playerInvTemp[i].isEmpty()) || playerInvTemp[i] == null)
remains false. Maybe you meant:
(!(playerInvTemp[i].isEmpty() || playerInvTemp[i] == null))

EditText text cannot be converted to int as there is no text there

Basically I need to check that the user input from inputET (an EditText) is equal to the integer, correctAnswer. The problem I'm getting is that "" (which is the text in the EditText field) cannot be converted to an int. Is there any other ways of achieving this or catching the error, I've tried the following code which to my understanding asks if the string in the EditText is not equal to "". Am i going the right way about this or is there an easier way?
// check the input
if (inputET.getText().toString() != "") {
if (correctAnswer == Integer.parseInt(inputET.getText()
.toString())) {
inputET.setText("");
newSum();
}
}
if the user inputs the same int as the correctAnswer integer then the EditText text is reset to "".
Thanks for any help.
try this:
if (!inputET.getText().toString().equals("")) {
if (correctAnswer == Integer.parseInt(inputET.getText()
.toString())) {
inputET.setText("");
newSum();
}
}
Used .equals() method for String comparison.
Based on your requirement I think using TextUtil class will be right way to go for checking the edittext is empty or not.
if(!TextUtils.isEmpty( inputET.getText().toString())){
if (correctAnswer == Integer.parseInt(inputET.getText()
.toString())) {
inputET.setText("");
newSum();
}
}
rather tha doing if (inputET.getText().toString() != "") have a try with
if (!inputET.getText().toString().equals(""))
print the "inputET.getText().toString()" to console and see what it returns. I would hope you need to check the following
String str = inputET.getText().toString()
if (null!=str && str.trim().equals("")) {
if(inputET.getText().toString()!=null&&!(inputET.getText().toString().isEmpty())){
//code for mot null
}else{
//code for null
}

Android: How to check/uncheck a RadioButton inside a RadioGroup programmatically in Java

I have to activities, MainActivity and settingsActivity. Because of that I'm using the methods onPause and onResume in the settingsActivity. So that the things I have done in the settingsActivity are saved after switching to MainActivity and back again.
settingsActivity:
Here I have a TextView (called "settings2") as a kind of variable and my three RadioButtons (radio0, radio1 and radio2) which are inside a RadioGroup.
After switching to the MainActivity my programe puts "0" in a file (which is saved on the sdcard) if radio0 was last checked. But if radio1 was last checked, it puts 1 in that file. And if radio2 was last checked, it puts 2 in that file.
I used this in the method onPause.
Then in the method onResume I read the text of that file and put it in the TextView "settings2".
After this code (still in onResume) I want to check/uncheck my RadioButtons. So if the text of the TextView "settings2" is "0" the RadioButton "radio0" shall be checked and the others not. If the text of this TextView is "1" the RadioButton "radio1" shall be checked and the others not. And if the text of this TextView is "2" the RadioButton "radio2" shall be checked and the others not.
To do this I used the following two codes but unfortunately they didn't work.
First code:
if (settings2.getText().equals("0")) {
radio0.setChecked(true);
radio1.setChecked(false);
radio2.setChecked(false);
} else if (settings2.getText().equals("1")) {
radio0.setChecked(false);
radio1.setChecked(true);
radio2.setChecked(false);
} else if (settings2.getText().equals("2")) {
radio0.setChecked(false);
radio1.setChecked(false);
radio2.setChecked(true);
}
Second code:
if (settings2.getText().equals("0")) {
radioGroup1.check(R.id.radio0);
} else if (settings2.getText().equals("1")) {
radioGroup1.check(R.id.radio1);
} else if (settings2.getText().equals("2")) {
radioGroup1.check(R.id.radio2);
}
Can someone help with this little problem please? I'm looking forward to your help!
Thanks in advance!
Here's the problem.
EditText et = ....
et.getText() // Does not return a string, it returns an Editable.
Try:
String str = et.getText().toString;
Then using str to do your comparisons.
Edit: See source code below on why u have to use Strings to compare. The default is to compare by reference, but Strings have overriden equals to compare based on string values. If you aren't using String u won't get matches.
public boolean More ...equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
Are you sure the TextView text is either 0, 1, or 2? And for a setting like this, you should look into SharedPreferences! It is much easier to use and much faster too.
2nd thing you should do is instead of getting the settings2.getText().toString () you should do
int input = Integer.parseInt (settings2.getText().toString()
and then use
switch(input) {
case 0:
// code when text equals 0
break;
case 1:
// code when text equals 1
break;
case 2:
// code when text equals 2
break;
}
Look into this. . I'm on mobile at the moment
EDIT: Formatted text for better view.
EDIT 2 : SharedPreferences example
//get your app's Preference Manager
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); // If you are coding this in your Activity class, you have to use getDefaultSharedPreferences(this) instead!
public int getPrefs(String key) {
//get an Integer from the preferences
return prefs.getInt(key, defaultValue);
//defaultValue is in case a value for the given key is not found, for example, the user runs the app for the 1st time.
}
public void setPrefs() {
//You need a SharedPreference editor
SharedPreferences.Editor prefsEditor = prefs.edit();
//SharedPreference work with a key and its value
prefsEditor.putInt(key, value);
//You have to commit the preferences, or they don't get saved!
//If you want to use a save button, you can make the Editor variable into a Global var (class variable) and in your save button's onClick, just commit!
prefsEditor.commit();
}

Java - Can't get getText in jTextArea to work properly

I have a seperate JFrame where there is a text box (jTextArea) that takes numbers as inputs, each separated with a new line. Upon closing the JFrame with the text box, the data is supposed to be stored in an ArrayList of integers. The ArrayList is checked when clicking a button in the main JFrame and errors are logged if they happen.
The code for the JFrame with the jTextArea looks like this:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
boolean success = false;
try{
selectedTime = Long.parseLong(jTextField1.getText());
if(selectedTime >= 10000){
success = true;
if(!jTextArea1.equals("") && !jTextArea1.equals(null)){
try{
for(int i = 0; i < jTextArea1.getLineCount(); i++){
n = Integer.parseInt(jTextArea1.getText(jTextArea1.getLineStartOffset(i),jTextArea1.getLineEndOffset(i)));
if(n <= 172){
worldsChosen.add(n);
}
}
}catch(Exception e){
errorsHappened = true;
}
}
}else{
javax.swing.JOptionPane.showMessageDialog(null,"The specified time was not above or equal to 10000 ms. Please try again.");
success = false;
}
}catch(Exception e){
javax.swing.JOptionPane.showMessageDialog(null,"The specified time was not set in numbers exclusively. Please try again.");
success = false;
}
if(success){
gui.hideWorlds();
}
}
Note: it also checks whether a text box has a number input equal to or above 10000 (this works).
The code for the main JFrame:
if(jCheckBox5.isSelected()){
checkWorld = true;
if(!worldsChosen.isEmpty()){
changeWorlds = true;
}else{
log("You've selected the option for automatic world switching,");
log("but all of your inputs weren't formatted correctly.");
errorsHappened = true;
}
}else{
errorsHappened = false;
}
if(errorsHappened == true){
log("One or multiple worlds weren't added due to incorrect formatting.");
log("Retry to make script automatically change worlds.");
}
Whenever I run the script with the check box selected and something formatted correctly in the text area
(like this):
1
2
3
4
5
etc.
It outputs all of the log messages (as if the check box had been selected but none of the inputs were formatted correctly).
I've tried to the best of my knowledge to fix this, but I just can't see how it messes up.
Any help appreciated :).
Mike Haye.
Read the api doc of getText(int, int): the second argument is not an offset. It's a length.
Side note 1: it should probably be easier to get all the text as a single string and split on newline chars, and the parse every string into an integer.
Side note 2: The test if (jTextArea1.equals("")) can't succeed. A JTextArea instance will never be equals to a String instance.
I didn't check the complete program, but this is wrong:
if(!jTextArea1.equals("") && !jTextArea1.equals(null)){
Did you forget to add the call of getText() ? The line as it is will always be evaluated to true, because the instance object of JTextArea is never equal to "" or null. The latter would imply that the jTextArea1 object was null itself. Which would give you a NPE when you call the equals method.
Do you reset the flag before checking the conditions? Consider the following case:
//suppose errorsHappened is true here
if(jCheckBox5.isSelected()){ //we get true here
checkWorld = true;
if(!worldsChosen.isEmpty()){ //not empty, so this branch is taken
changeWorlds = true;
}else{ //worldsChosen is not empty, so this would not be logged
log("You've selected the option for automatic world switching,");
log("but all of your inputs weren't formatted correctly.");
errorsHappened = true;
}
}else{ //checkbox is selected, so no reset to false here
errorsHappened = false;
}
//due to the checkbox being selected and worldsChosen not being empty,
//errorsHappend is still true (which is wrong)

Categories

Resources