#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editTextName);
textView = findViewById(R.id.textViewOne);
button = findViewById(R.id.buttonOne);
view = findViewById(R.id.snackbar_action);
String x = editText.getText().toString();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {//Checking if edit text field is left empty.
if (editText.getText().toString().equals("")) {
Snackbar.make(view, R.string.text_label, Snackbar.LENGTH_SHORT).show();
}//Checking if editText field is numeric.
else if (TextUtils.isDigitsOnly(x)){
Snackbar.make(view, R.string.text_number, Snackbar.LENGTH_SHORT).show();
} else {
textView.setText(NATOConverter("" + editText.getText().toString()));
}
}
});
}
Hello guys im struggling trying to figure out how to check if a my edittext value contains letters and numbers im trying to display a snackbar if the user enters for example "JDF23D" telling them to remove the numbers but my error is no matter what it stays on that else if what would you suggest?
Try next code
if (editText.getText().toString().matches(".*[0-9].*")){
//some code
}
else{
//some code
}
If you want to check whether the string contains a number, you should use this,
public boolean containsDigit(String x){
for(int i = 0; i < x.length(); i++){
if(48 <= (int) (x.charAt(i)) <= 57)
return true;
}
return false;
}
Returns true if even one character is a number, else false.
Try more simplest
boolean match = Pattern.compile("\\d+").matcher(s).find();
You use this method:
TextUtils.isDigitsOnly(x)
but this method checks if your string only contains digits. So your example "JDF23D" will return false.
You can take a look at this post
Related
I am new working with this customized Dialog in android. I may not be able to clarify my problem properly by writing, So it humble request to understand what i want from given code.
In MainActivity i have Button to delete an element of an ArrayList and setting the info from the ArrayList to a Layout.
Code from CustomDialog:
public class PermissionToDelete extends Dialog implements View.OnClickListener {
public Button btnYes, btnNo;
public TextView txtPermToDelete;
public PermissionToDelete(Context context){
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.permission_delete);
initialize();
}
public void initialize(){
btnYes = findViewById(R.id.btnYes);
btnNo = findViewById(R.id.btnNo);
txtPermToDelete = findViewById(R.id.txtPermToDelete);
btnYes.setOnClickListener(this);
btnNo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnNo){
dismiss();
}
else if(v.getId() == R.id.btnYes){
MainActivity.deleteOrErase = "delete";
dismiss();
}
}
}
There is a static String variable in MainActivity named deleteOrErase.
From dialog it returns the string delete if Button Yes is clicked.
Code from MainActivity:
tv.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
String text = tv.getText().toString();
PermissionToDelete permissionToDelete = new PermissionToDelete(MainActivity.this);
permissionToDelete.show();
if(deleteOrErase.equals("delete")){
String index = "";
for(int i = 1; text.charAt(i) != ')'; i++){
index += text.charAt(i);
}
tasksList.remove(Integer.parseInt(index) - 1);
File rootFile = new File(rootFolder);
if(rootFile.exists()){
String[]entries = rootFile.list();
for(String s: entries){
File currentFile = new File(rootFile.getPath(),s);
currentFile.delete();
}
rootFile.delete();
}
dailyTasksLayout.removeAllViews();
makePrimaryFileAndFolder();
saveDataToFile();
setTaskList();
deleteOrErase = "";
}
But the problem is before button from dialog is clicked, if(deleteOrErase.equals("delete")) is encountered when the value of deleteOrErase is still null.
Therefore data isn't deleted at the first click.
Its need second click to delete, because now the value of deleteOrErase is "delete".
How can i delete it from first click?
Or is there any other way???
thanks dear honorable members! <3
(I don't know either i could clarify my problem or not.
Even i can't understand from mty writings :P )
My question is simple. What method can I use to tell my program that a button is pressed? I'm trying some codelines but its not really working (I tryed with isPressed). in my logs I can read the line --> TAMAÑO DEL CONTADOR: < the numbers until it reaches max.> before I can I even place a value, so I understand the loop doesnt wait for my inputs.
Here is my code:
public class navegador extends AppCompatActivity {
public String Sdat;
public EditText ET2;
int tam;
ArrayList<String> Medidas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navegador);
ET2 = findViewById(R.id.ET1);
Button bot = findViewById(R.id.bot);
tam = getIntent().getIntExtra("numero",0);
Medidas = new ArrayList<>();
int contador = 0;
System.out.println("TAMAÑO DEL ARRAY: "+ tam);
while ( contador <= tam){
System.out.println("TAMAÑO DEL CONTADOR: " + contador);
bot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View bot) {
if(bot.isPressed()){
MeterMedida();
}
}
});
contador++;
if(contador == tam){
Toast.makeText(this, "Distancia máxima alcanzada. Toca Crear tabla.", Toast.LENGTH_SHORT).show();
}
}
}
public void MeterMedida(){
Sdat = ET2.getText().toString();
Medidas.add(Sdat);
ET2.setText("");
}
public void LanzarLista (View view){
Intent A = new Intent(this, Lista.class);
A.putStringArrayListExtra("Lista", Medidas);
startActivity(A);
}
}
Thanks a lot, ask me for more information if you think you need it.
EDIT
As usual, less is more, I removed the while, and contador variable, now it works like I wanted and its pretty much simple. Thank you so much.
You said that you wanted to tell your app when a button is pressed, do something. There's no need to use isPressed() method. Just do it like this.
bot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View bot) {
//When you press this button (bot), codes here will be executed.
MeterMedida();
}
});
You don't need a while loop:
//a list to keep all the entered floats
private List<Float> floats = new ArrayList<Float>();
//each time you click the listener is invoked
bot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View bot) {
//every time the button is clicked, fill the current typed float
floats.add(Float.parseFloat(ET2.getText().toString()));
ET2.setText("");
}
});
Well, I’m not gonna give complete answer. Just a few hints for yourself to figure out.
Declare int contador = 0; in class level
Remove while ( contador <= tam)
Remove if(bot.isPressed())
Remove contador++; in your onCreate
Inside MeterMedida() check for if(contador <= tam). If true, add to ArrayList and increment contador. Else show error Toast.
So I made a custom dialog where it asks for information(like a feedback.
I want the app to check if all the EditTexts have value,
this is my java for opening feedback dialog
private void dialog() {
myDialog.setContentView(R.layout.activity_pop_up);
editTextEmailValue = (EditText) myDialog.findViewById(R.id.editTextEmail);
editTextMessageValue = (EditText) myDialog.findViewById(R.id.editTextMessage);
editTextNumeValue = (EditText) myDialog.findViewById(R.id.editTextNume);
Button btnSend = (Button) myDialog.findViewById(R.id.sendBtn);
Button btnClose = (Button) myDialog.findViewById(R.id.close);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//This is what I've tried (the check method is bewlow)
if (check() > 1) {
editTextNumeValue.setError("Obligatoriu!");
editTextMessageValue.setError("Obligatoriu!");
editTextEmailValue.setError("Obligatoriu!");
} else if (check() == 0) {
sendMail();
}
}
});
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myDialog.dismiss();
}
});
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
myDialog.show();
}
And this is my check method :
private int check() {
int counter = 0;
if (editTextEmailValue.equals("")) {
editTextEmailValue.setError("Obligatoriu!");
counter++;
} else if (editTextMessageValue.equals("")) {
counter++;
editTextMessageValue.setError("Obligatoriu!");
} else if (editTextNumeValue.equals("")) {
editTextNumeValue.setError("Obligatoriu!");
counter++;
}
return (counter);
}
When I press the send button(for email) it enters the check method and goes out with 0 1 2 3 (I have only 3 textView) but when it checks in the btnSend.onClickListener if the condition are met it still send the mail so from that I can say from check method the counter have value 0 all the time so can you help me?
Your logic above is wrong. You are checking
if(counter > 1)
but your counter will never be greater than 1. Change it to
if(counter > 0) or if(count >= 1)
also use editText.getText().toString() for the correct editText entries !
and use .isEmpty() instead of .equals("")
i agree with Luis Fernando Scripcaru .
and i suggest you one thing try editTextEmailValue.getText().toString().equals("") instead of editTextEmailValue.equals("").
You can remove your check() method and try like this It might work :)
int Counter = 0;
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//This is what I've tried (the check method is bewlow)
if(TextUtils.isEmpty(editTextEmailValue)){
editTextEmailValue.setError("Error");
Counter = 1;
}
if(TextUtils.isEmpty(editTextMessageValue)){
editTextMessageValue.setError("Error");
Counter = 2;
}
if(TextUtils.isEmpty(editTextNumeValue)){
editTextNumeValue.setError("Error");
Counter= 3;
}
if(Counter > 1){
sendMail();
//you can add other operations for 123 numbers too
}
}
});
You check
if (check() > 1)
It will never be true. Because check() has IF ELSE, so only one increment will be performed and return value will never be more than 1, maximum value of our check is 1.
so, change this to
if (check() > 0)
or
if (check() >= 1)
So I'm creating an app that validates a users input but when I did it for the password all it says is Required boolean found int
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
submit = (Button)findViewById(R.id.submit);
name = (EditText)findViewById(R.id.name);
pass = (EditText)findViewById(R.id.pass);
number = (EditText)findViewById(R.id.number);
email = (EditText)findViewById(R.id.email);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final String Name = name.getText().toString();
final String Pass = pass.getText().toString();
if(name.length()==0)
{
name.requestFocus();
name.setError("Field cannot be empty");
}
else if(!Name.matches("[a-zA-Z]+"))
{
name.requestFocus();
name.setError("ENTER ONLY ALPHABETICAL CHARACTERS");
}
else if (pass.length())
{
pass.requestFocus();
pass.setError("FIELD CANNOT BE EMPTY");
}
else {
Context context = getApplicationContext();
CharSequence text = "Thank you, your request is being processed!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
});
}
The error is happening on the line where it says pass.length. Could anyone please help in what the problem is
Use
else if (pass.length()>0)
instead so that you get a boolean value to use inside the if condition
While using conditional statements you have to use boolean variable to check the condition is valid or not.
else if (pass.length())
Here pass.length() returns the length of the variable, which is an integer. You should not use the integer to check the condition.
In contrast with e.g. C/C++ language, Java does not allow numeric values to be used instead of boolean values (0/1 != false/true).
when clicking on the button it does nothing ,,,after testing I concluded the problem is with the equal method statment ,,,the whole issue is when comparing string array to string any solutions?
EditText coderead = (EditText)findViewById(R.id.editText1);
Button go = (Button)findViewById(R.id.button1);
final String mn=coderead.getText().toString();
final String code[] = {"m1","n2"};
final double pointx[] ={23.666666,65.22222};
final double pointy[] ={31.55555,29.665544};
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent transfercode = new Intent(getApplicationContext(), FeenbezabtActivity.class);
for (int i=0; i<code.length; i++) {
if(code[i].equals(mn)) {
transfercode.putExtra("lat2", pointx[i]);
transfercode.putExtra("long", pointy[i]);
startActivity(transfercode);
}
else{Toast.makeText(getBaseContext(), "code not found", 5000);}
}
}
});
Your mn variable should be read after your button has been clicked.
Button go = (Button) findViewById(R.id.button1);
final String code[] = {"m1", "n2"};
final double pointx[] = {23.666666, 65.22222};
final double pointy[] = {31.55555, 29.665544};
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent transfercode = new Intent(getApplicationContext(), FeenbezabtActivity.class);
// mn should be read after the button click!
EditText coderead = (EditText) findViewById(R.id.editText1);
final String mn = coderead.getText().toString();
for (int i = 0; i < code.length; i++) {
if (code[i].equals(mn)) {
transfercode.putExtra("lat2", pointx[i]);
transfercode.putExtra("long", pointy[i]);
startActivity(transfercode);
} else {
Toast.makeText(getBaseContext(), "code not found", 5000);
}
}
}
});
So if I understand your code correctly you are trying to respond to a button click and take the text that has been input and do something based on that?
You are setting the value of mn at the time you are creating the button, rather than when the button is pressed. At that time the text will be empty (or null). You should move the code to get the value of the entered text to within the onClickListener.
Should your "code not found" message happen outside the for loop?
What do you mean by nothing happens? Do you get a Toast message or not? Did you make sure that no error is being generated? If you are not getting the Toast Message and you have no errors, then make sure the intent is correct. I would recommend you debug the code from the line of Intent transfercode = new Intent(getApplicationContext(), FeenbezabtActivity.class);
Then, report what is happening back here.
Something I don't get. With these two lines:
final String mn=coderead.getText().toString();
final String code[] = {"m1","n2"};
Why don't you just compute the (final) index to code right then and there, vs waiting until onClick?