Use Edit Text for password change - android

I'm new android developer and i want to check is two Edit Text match with each other or not ,I want it for password change.
here is my code [edited] :
String ChPassword1=ChangePassword1_Box.getText().toString();
String ChPassword2=ChangePassword2_Box.getText().toString();
if(ChPassword1==ChPassword2){
savePreferences("PASSWORD", ChPassword1);
Toast msg = Toast.makeText(getBaseContext(),"رمز تغییر کرد", Toast.LENGTH_LONG);
msg.show();
}
but it doesn't work !!

use the equals method from String to compare strings
if (ChPassword1.equals(ChPassword2)) {
}
== compares strings reference

Better use
ChPassword1.equals(ChPassword2)

Use equals for String matching
if(ChPassword1.equals(ChPassword2)

Related

Android java compare xml string with edittext

I want to compare a xml string with a string from an edittext oder button.
first I set the text of the button:
button1.setText(getString(R.string.okey));
and now I want to check if the text from the button is the same as R.string.okey from the xml file. Like this I can leave out a new variable.
Is it possible to check if the strings are the same with something like this?
if (button1.getText().toString().equals(getString(R.string.okey))){
}
But that doesn't work for me.
Thank you in advance.
this must work, its just to simple. you must change somehow text on button or maybe getString returns different text (Locale changed?). use logging or debugger to check what is button1.getText().toString() and getString(R.string.okey) at the moment of comparison (equals call)
boolean areEqual = button1.getText().toString().equals(getString(R.string.okey));
Log.i("justChecking", "getString:" + getString(R.string.okey) +
", button1.getText:" + button1.getText().toString() +
", are equal:" + areEqual);
if (areEqual){
}
How to Write and View Logs with Logcat
Store them in variables
String a = button1.getText()+"";
String b = getString(R.string.str)+"";
if(a.equals(b)){ }

Remove all <tag></tag> with text between

I'm trying to remove all text tagged like this (including the tags)
<tag>TEXT</tag>
from a String.
I have tried
.replaceAll("<tag>.+/(tag)*>", "")
or
.replaceAll("<tag>.*(tag)*>", "")
but neither works correctly and I can't replace the tagged text with ""
I don't know exactly what you want, so here are a few options:
String text = "ab<tag>xyz</tag>cd";
// Between
text.replaceAll("<tag>.+?<\/tag>", "<tag></tag>"); // ab<tag></tag>cd
// Everything
text.replaceAll("<tag>.+?<\/tag>", ""); // abcd
// Only tags
text.replaceAll("<\/?tag>", ""); // abxyzcd
EDIT:
The problem was the missing ? after the .+. The question mark only matches the first occurence, so it works when multiple tags are present which was the case.
Change to this ,
String nn1="<tag>TEXT</tag>";
nn1=nn1.replace("<tag>","");
nn1=nn1.replace("</tag>","");
OR
String nn1="<tag>TEXT</tag>";
nn1=nn1.replaceAll("<tag>","");
nn1=nn1.replaceAll("</tag>","");
Output : TEXT
I hope this helps you.
public static void removeTAG()
{
String str = "<tag>Your Long String</tag>";
for(int i=0;i<str.length();i++)
{
str = str.replace("<tag>", "");
str = str.replace("</tag>", "");
}
System.out.println(str);
}
Here what i did and output was as expected
Output Your Long String
You can use the below regular expression.
.replaceAll("<tag>.+?<\/tag>", "<tag></tag>");
This removes all the tags whether it's an HTML or an XML tag.

How to ignore spaces between text editview Android

I am trying to ignore spaces in editview between text, I am not quite sure how I can go about doing this. I know I can use trim feature to ignore spaces before and after the full text but how do I ignore space between strings if there is any;
String myTextEdited myText.getText().toString().trim();
For example, if I have / user types in this;
Allan Bob
3523 JKO
NY1 U90
I want to ingore spaces when I read this in my if statement or put it in another variable for example;
String name = "AllanBob"
For example, to ignore upper and lower cases I am doing this;
if (myText.getText().toString().trim().equalsIgnoreCase(userInput)) {
// do something
} else {
// do something
}
What I would like to do is add another feature in here that also ignores spaces before, between and after text e.g. instead of;
myname is Henry . (space until here)
It should read it as mynameishenry but to the user it still appears as they have written it.
Please let me know if my question was not clear, I will try explaining it better
EDITED:
is it possible to ignore spaces in string that I have inside my if statement. For example;
if (myText.getText().toString().trim().equalsIgnoreCase("Henry 0887")) {
// do something
} else {
// do something
}
but currently if the user types in henry0887, the if statement does not validate it because I added a space inside my validation text and therefoe its looking for a space in the text, is it possible to over come this, so even if I have space inside my validation it ignores it.
Did you try this:
String myString = myEditText.getText().toString();
myString = myString .replace(" ", "");
Hope it helps
EDIT:
if (myText.getText().toString().replace(" ", "").equalsIgnoreCase(userInput) || myText.getText().toString().equalsIgnoreCase(userInput)) {...
Try this,
if(myText.getText().toString().trim().replace(" ","").equalsIgnoreCase(userInput)) {
// do something
} else {
// do something
}
Hope this helps.
use replaceAll() method.
str = str.replace(" ","");
or for all space chars:
str = str.replace("\\s+","");
EDIT
if (myText.getText().toString().replace("\\s+","").equalsIgnoreCase(userInput)) {
// do something
} else {
// do something
}
EDIT2
if (myText.getText().toString().replace("\\s+","").equalsIgnoreCase("Henry 0887".replace("\\s+",""))) {
// do something
} else {
// do something
}

Android TextView : "Do not concatenate text displayed with setText"

I am setting text using setText() by following way.
prodNameView.setText("" + name);
prodOriginalPriceView.setText("" + String.format(getString(R.string.string_product_rate_with_ruppe_sign), "" + new BigDecimal(price).setScale(2, RoundingMode.UP)));
In that First one is simple use and Second one is setting text with formatting text.
Android Studio is so much interesting, I used Menu Analyze -> Code Cleanup and i got suggestion on above two lines like.
Do not concatenate text displayed with setText. Use resource string
with placeholders. less... (Ctrl+F1)
When calling TextView#setText:
Never call Number#toString() to format numbers; it will not handle fraction separators and locale-specific digits properly. Consider
using String#format with proper format specifications (%d or %f)
instead.
Do not pass a string literal (e.g. "Hello") to display text. Hardcoded text can not be properly translated to other languages.
Consider using Android resource strings instead.
Do not build messages by concatenating text chunks. Such messages can not be properly translated.
What I can do for this? Anyone can help explain what the thing is and what should I do?
Resource has the get overloaded version of getString which takes a varargs of type Object: getString(int, java.lang.Object...). If you setup correctly your string in strings.xml, with the correct place holders, you can use this version to retrieve the formatted version of your final String. E.g.
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
using getString(R.string.welcome_message, "Test", 0);
android will return a String with
"Hello Test! you have 0 new messages"
About setText("" + name);
Your first Example, prodNameView.setText("" + name); doesn't make any sense to me. The TextView is able to handle null values. If name is null, no text will be drawn.
Don't get confused with %1$s and %2$d in the accepted answer.Here is a few extra information.
The format specifiers can be of the following syntax:
%[argument_index$]format_specifier
The optional argument_index is specified as a number ending with a “$” after the “%” and selects the specified argument in the argument list. The first argument is referenced by "1$", the second by "2$", etc.
The required format specifier is a character indicating how the argument should be formatted. The set of valid conversions for a given argument depends on the argument's data type.
Example
We will create the following formatted string where the gray parts are inserted programmatically.
Hello Test! you have 0 new messages
Your string resource:
< string name="welcome_messages">Hello, %1$s! You have %2$d new
messages< /string >
Do the string substitution as given below:
getString(R.string.welcome_message, "Test", 0);
Note:
%1$s will be substituted by the string "Test"
%2$d will be substituted by the string "0"
I ran into the same lint error message and solved it this way.
Initially my code was:
private void displayQuantity(int quantity) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + quantity);
}
I got the following error
Do not concatenate text displayed with setText. Use resource string with placeholders.
So, I added this to strings.xml
<string name="blank">%d</string>
Which is my initial "" + a placeholder for my number(quantity).
Note: My quantity variable was previously defined and is what I wanted to append to the string. My code as a result was
private void displayQuantity(int quantity) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText(getString(R.string.blank, quantity));
}
After this, my error went away. The behavior in the app did not change and my quantity continued to display as I wanted it to now without a lint error.
Do not concatenate text inside your setText() method, Concatenate what ever you want in a String and put that String value inside your setText() method.
ex: correct way
int min = 120;
int sec = 200;
int hrs = 2;
String minutes = String.format("%02d", mins);
String seconds = String.format("%02d", secs);
String newTime = hrs+":"+minutes+":"+seconds;
text.setText(minutes);
Do not concatenate inside setText() like
text.setText(hrs+":"+String.format("%02d", mins)+":"+String.format("%02d", secs));
You should check this thread and use a placeholder like his one (not tested)
<string name="string_product_rate_with_ruppe_sign">Price : %1$d</string>
String text = String.format(getString(R.string.string_product_rate_with_ruppe_sign),new BigDecimal(price).setScale(2, RoundingMode.UP));
prodOriginalPriceView.setText(text);
Don't Mad, It's too Simple.
String firstname = firstname.getText().toString();
String result = "hi "+ firstname +" Welcome Here";
mytextview.setText(result);
the problem is because you are appending "" at the beginning of every string.
lint will scan arguments being passed to setText and will generate warnings, in your case following warning is relevant:
Do not build messages by
concatenating text chunks. Such messages can not be properly
translated.
as you are concatenating every string with "".
remove this concatenation as the arguments you are passing are already text. Also, you can use .toString() if at all required anywhere else instead of concatenating your string with ""
I fixed it by using String.format
befor :
textViewAddress.setText("Address"+address+"\n"+"nCountry"+"\n"+"City"+"city"+"\n"+"State"+"state")
after :
textViewAddress.setText(
String.format("Address:%s\nCountry:%s\nCity:%s\nState:%s", address, country, city, state));
You can use this , it works for me
title.setText(MessageFormat.format("{0} {1}", itemList.get(position).getOppName(), itemList.get(position).getBatchNum()));
If you don't need to support i18n, you can disable this lint check in Android Studio
File -> Settings -> Editor -> Inspections -> Android -> Lint -> TextView Internationalization(uncheck this)
prodNameView.setText("" + name); //this produce lint error
val nameStr="" + name;//workaround for quick warning fix require rebuild
prodNameView.setText(nameStr);
I know I am super late for answering this but I think you can store the data in a varible first then you can provide the variable name. eg:-
// Java syntax
String a = ("" + name);
String b = "" + String.format(getString(R.string.string_product_rate_with_ruppe_sign);
String c = "" + new BigDecimal(price).setScale(2, RoundingMode.UP));
prodNameView.setText(a);
prodOriginalPriceView.setText(b, c);
if it is textView you can use like that : myTextView.text = ("Hello World")
in editText you can use myTextView.setText("Hello World")

Comparing two EditText values in android

I'm trying to make an app where the user enters a word into an EditText box. Then, they enter something into another box and it checks to see if they are the same word. Here's the code that I used:
String word = textfield1.getText().toString();
String answer = textfield2.getText().toString();
textfield2.setText(textfield2.getText().toString());
if(word == answer){
Toast.makeText(getApplicationContext(), "correct",
Toast.LENGTH_LONG).show();
}else
Toast.makeText(getApplicationContext(), "incorrect", Toast.LENGTH_LONG).show();
}
However, it always says that the two strings aren't the same even if they are. Is there a way to fix this?
You can't compare strings with the == operator.
Use .equals() instead:
if(word.equals(answer)) {
//do whatever
}
Use String.equalsIgnoreCase for comparing content of both string variables.:
if(word.equalsIgnoreCase(answer)){
}
Use:
String word = textfield1.getText().toString();
String answer = textfield2.getText().toString();
if(answer.contentEquals(word)){
// Do something if equals
}
else{
// Do something if not equals
}
I think the best way to do this is using TextUtils:
if(TextUtils.equals(textfield1.getText(),textfield2.getText())){
//do something
}
instead of
if(word.contentEquals(answer)){
}
Use
if(word.equals(answer))
as we cant compare strings with Equal to (==) operator
Try This::
String word = textfield1.getText().toString();
String answer = textfield2.getText().toString();
if(word.equals(answer)){
Toast.makeText(getApplicationContext(), "correct",
Toast.LENGTH_LONG).show();
}else
Toast.makeText(getApplicationContext(), "incorrect", Toast.LENGTH_LONG).show();
}

Categories

Resources