Verify that at least one of the three TextView is written - java

hi everyone I hello everyone I have an application
with three TextView in a fragment and I want at least one of the three TextView is never empty, that is, at least one of the three extview must always be written.
My code is:
TextView comment_text = getActivity().findViewById(R.id.addtext_comment);
TextView mymenu = getActivity().findViewById(R.id.mymenu);
TextView mymenu2 = getActivity().findViewById(R.id.mymenu2);
String comment = String.valueOf(comment_text.getText());
String mymenu_text= String.valueOf(mymenu.getText());
String mymenu2_text= String.valueOf(mymenu2.getText());
if (validate(mymenu_text) && validate(mymenu2_text) && comment.length()==0||
validate(mymenu_text) || validate(mymenu2_text)||comment.length()!=0) {
Log.d("main_activity_spinner", "it's ok");
}
public boolean validate(String text) {
if (text.contains("null")) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Attenction!");
builder.setMessage("please insert at leat comment or delat or status");
builder.show();
return false;
}else
return true;
}
Now my code, if I write in one of the three textView, it returns the alert "please insert at least comment or delay or status" and then Log("it's ok"),but I want that if I don't write in any of the TextView, I get back an alert and if I write in one of the three TextView (or if I write in two or in all three TextView), I return the Log "it's ok". How can i do?

To check that at least one of them has text, you just have to check whether all the strings are empty. If so, show your warning, and if not, "it's ok":
EditText comment_text = getActivity().findViewById(R.id.addtext_comment);
EditText mymenu = getActivity().findViewById(R.id.mymenu);
EditText mymenu2 = getActivity().findViewById(R.id.mymenu2);
String comment = comment_text.getText().toString();
String mymenu_text= mymenu.getText().toString();
String mymenu2_text= mymenu2.getText().toString();
// if all three strings are empty, show the alert, otherwise log "it's ok"
if( comment.isEmpty() && mymenu_text.isEmpty() && mymenu2_text.isEmpty() ) {
// all of them are empty
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Attenction!");
builder.setMessage("please insert at leat comment or delat or status");
builder.show();
}
else {
// at least one has text
Log.d("main_activity_spinner", "it's ok");
}
Note 1: I assume these are actually EditText views, not pure TextView instances, since TextView is not editable by a user at runtime.
Note 2: For this to work, you have to call it at the time of validation. If you put this in something like onCreate it will be meaningless since the user wouldn't have had time to enter anything anyway.

Related

How to pause the execution of the entire program until a button is pressed in JAVA?

I have been making an android app in which I want to take advantage of some previously written Java code which is written entirely to run on its own with its own main method.
When I call the main method from my MainActivity.java's onCreate method it is still being called fine. But instead of interfacing with the console, I want the main() method to interface with the EditText, Buttons and views of android. MainActivity and the Java code are in separate classes.
What I want is basically the execution of the program to be stopped until I enter my entry in the EditText and resume when I press a button and then take the string I entered in the EditText. Just like in BufferdReader when we call the reader.readLine() method, the execution stops until pressed enter and then takes in whatever inputted before pressing enter.
There are three function calls one after another to promptString():
case TdApi.AuthorizationStateWaitPhoneNumber.CONSTRUCTOR: {
String phoneNumber = promptString("Please enter phone number: ");
client.send(new TdApi.SetAuthenticationPhoneNumber(phoneNumber, false, false), new AuthorizationRequestHandler());
break;
}
case TdApi.AuthorizationStateWaitCode.CONSTRUCTOR: {
String code = promptString("Please enter authentication code: ");
client.send(new TdApi.CheckAuthenticationCode(code, "", ""), new AuthorizationRequestHandler());
break;
}
case TdApi.AuthorizationStateWaitPassword.CONSTRUCTOR: {
String password = promptString("Please enter password: ");
client.send(new TdApi.CheckAuthenticationPassword(password), new AuthorizationRequestHandler());
break;
}
Each call returns a string which is then sent for the API calls. If buffered reader is used the code will stop executing until someone enters a string and presses enter and correct value(according to the user) is inputted and then is returned by promptString() and then sent to API calls.
I want to replicate this buffered reader type functionality in android where when promptString() is called, the program waits until the user enters in the edit text and when a button is pressed then promptString() return the string and then further execution is carried on.
What is happening right now is that the execution proceeds without giving the user a chance to enter in the edit text and hence wrong (empty string) values are sent to the API calls and hence causing errors.
promptString() Code which is responsible for taking input and returning the inputted string (non modified):
private static String promptString(String prompt) {
System.out.print(prompt);
currentPrompt = prompt;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String str = "";
try {
str = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
currentPrompt = null;
return str;
}
I know what I ask is quite unconventional and stupid but I need this because I am facing some deadlines and I don't have time to fully understand the API calls.
If the question is unclear to you please comment that which part you want to be elaborated.
I am open to solutions which are not exactly as mine but will do the job that I am looking for and help me to let the program wait until the user is finished entering the string in the edit text.
I am using the telegram api's java example.
Please Help.
Android is event driven, you can replace the promptString behavior with something like this: and of course the promptString must have Android context, resist in an Activity or have access to Activity context
private void promptString(String prompt, callback) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(prompt);
// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
callback.setValue(input.getText().toString());
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
You can use the Java code as is but you have to modified some and call out to Android asking for input and at the same the hand over a callback handler that, when the input is done, will callback/send back the input value to use.
Looking at the onAuthorizationStateUpdated() method in the java code, every switch case must call this method and supply the callback at the same this.
So each switch case have it´s own callback or they can use the same and you can switch case again over the response from the AlertDialog, of course then you need some identifier for that, maybe easier to use different callback handler
case TdApi.AuthorizationStateWaitPhoneNumber.CONSTRUCTOR: {
String phoneNumber = yourAndroidContextActivity.promptString
("Please enter phone number: ", callback);
break;
}
The code:
client.send(new TdApi.SetAuthenticationPhoneNumber(phoneNumber, false, false), new AuthorizationRequestHandler());
must go into the callback, there you go hope it helps

Else If textfield (Android)

I am creating a else if statement for a textfield i have on my view, i am using this code right now. But i'm running into a few errors
private EditText editText;
editText = findViewById(R.id.your_custom_id);
//then something like this
Sting text = editText.getText();
if(text.equals("foo") {
// do something
else if(text.equals("bar") {
// do something else
} else {
// something else
}
The errors consist of "Can't resolve symbol for 'sting' or 'equals'. 'Unknown class "editText" in the 'editText = findViewbyid...'. And the last one is 'Else without if' on the "else if(text.equals("bar")" code. How can i resolve this?
See Sting text = editText.getText(); This is totally incorrect.
There is no such thing as Sting it's String.Equal method apply on object types and String is an Object.
Also you need to use toString().
Use String text = editText.getText().toString();
you need to use editText = (EditText)findViewById(R.id.your_custom_id);
instead of editText = findViewById(R.id.your_custom_id);.

multiple if statement with different conditions

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);
}

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();
}

if statement problems in android

I have a method that checks for a null value from an editText on a click of a button like so:
public void myClickHandler09(View chv){
if (text9.equals("")){
text9.setText("0");
}else{
converter(text9);
}}
The
converter(text9);
method is as shown:
public void converter(View view){
switch (view.getId()) {
case R.id.Button09:
RadioButton RadioButtons = (RadioButton) findViewById (R.id.RadioButton901);
float inputValue = Float.parseFloat(text9.getText().toString());
if (RadioButtons.isChecked()) {
text9.setText(String
.valueOf(convertRadioButtons(inputValue)));
}
break;
}}
private double convertRadiobuttons(float inputValue){
return inputValue * 6.4516;
}
The method is larger but here i've only called one radiobutton to shorten it.
Right now though the if statement seems to do absolutely nothing and so non of the rest of the code works. If i remove the method and rename
converter(View view){
to
myClickHandler09(View view){
then the code works and until you enter a null value into the EditText (then it crashes)
What am I doing wrong exactly here?
NOTE: the method name "myClickHandler09" is linked to the button as android:onClick in the xml
You need to do if("".equals(text9.getText().toString())) { ...
The toString() is there because the TextView will return a CharSequence which may or may not be a String.
Right now you are comparing the TextView itself to "", and not the String it is showing.
Edit - As far as the crash goes, you also want to catch the NumberFormatException that Float.parseFloat() throws.
float inputValue = 1.0f; // some default value, in case the user input is bad.
try {
inputValue = Float.parseFloat(text9.getText().toString());
} catch (NumberFormatException e) {
// possibly display a red flag next to the field
}
Why not try
if ("".equals(text9.getText())) {
} else {
}
You essentially have to do a getText() from a TextView and not equals a String with a TextView.
One thing I don't understand with your code is that you call:
converter(text9);
passing in the EditText, but by replacing converter(View view) with the function name myClickHandler09 (like so):
myClickHandler09(View view) {
the button being pressed with call this function (if you defined it in the xml layout onClick paramter).
So to match this behaviour with your current code, try this out:
public void myClickHandler09(View btnView){
if (text9.equals("")){
text9.setText("0");
} else {
converter(btnView);
}
}
I may have missed the point of you're post, but I think that is part of your issue. Also in stead of .equals("") I prefer (text9.toString().length() > 0) just seems a bit more logical, but that's me being a bit pedantic.

Categories

Resources