UnitTesting for EditText , testing multiple values - android

Hi I am trying to test the edit Text placing 2 different values but the second test is failing .reasons unknown...below is my code
TestCase1
public void testvalues1() {
// clearing the edit text
mTextView.clearComposingText();
TouchUtils.tapView(this, mTextView);
// sending input as 7
sendKeys("7");
String userInput1;
String expected = "158269.3778";
String parameterFrom1 = "0.0027";
String parameterTo1 = "61.04676";
// getting the input from the mTextView reference
userInput1 = mTextView.getText().toString();
String resultset = UnitCalculation.Converter(parameterFrom1,userInput1,parameterTo1);
assertEquals(resultset, expected);
}
In the above test case iam sending value 7 and output is as expected
TestCase2
public void testvalues2() {
// clearing the edit text
mTextView.clearComposingText();
TouchUtils.tapView(this, mTextView);
// sending input as 23
sendKeys("23");
String userInput1;
String expected = "150.5011";
String parameterFrom1 = "1.092607";
String parameterTo1 = "7.149502";
// getting the input from the mTextView reference
userInput1 = mTextView.getText().toString();
String resultset1 = UnitCalculation.Converter(parameterFrom1,userInput1,parameterTo1);
System.out.println("printing resilt set "+ resultset1);
assertEquals(resultset1, expected);
}
But the method is returning value 0 instead of 150.5011
Iam using the same methos to calculate, When i give User value hardcoded like this String userInput1="23"; it is working, but when is taking the value from edittext its is not working.
can i send multiple values to edit text on the same testfile??

sendKeys with more than one character is what messed it up. See this reference.
To sum up, sendKeys needs a String which contains space separated keys. Your sendKeys("23")is trying to find a key in the soft keyboard called 23, though there isn't. Try using this:
sendKeys("2 3");
As it will send these two key strokes individually, instead of trying to find a key named 23. That's why sending just a 7 worked, because 7 is the key name for "7".

Related

smiley validation not working in android

I have EditText, in that we can enter all keyboard characters like alphanumerics, smileys, special characters.
I have to validate for some special characters and all smileys not to be allowed. Needs to show all the entered non-allowed characters as alert dialog.
I tried with many smileys, for smileys it is taking only empty spaces inside the below function and for validation it is showing only one smiley, sometimes it is showing two.
Below is the code.
public static String validateSpecialCharacters(String message, Pattern messagePattern){
StringBuilder matchedCharacters = new StringBuilder();
Map<Character, Integer> uniqueSpecialCharacters = new HashMap<>();
Matcher m = messagePattern.matcher(message);
while (m.find()){
if(!uniqueSpecialCharacters.containsKey(message.charAt(m.start()))) {
uniqueSpecialCharacters.put(message.charAt(m.start()), 1);
matchedCharacters.append(message.substring(m.start(),m.end()));
}
}
return matchedCharacters.toString();
}
Inside the while the if condition is getting true only once or twice. But I have entered different smileys. The issue is the previous key added for the first smiley is similar with the second. But actually the smiley's are not similar. How to solve this.

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")

adding some elements to edittext i.e some character between any word

I need to receive user's input from an edittext, then add some elements inside it?
how can I do it programmatically?
let me explain:
user enters this phrase : ( Hello World )
I want my app change it to : ( Hoelplom wwoerlldc) for example
Any suggestion?
get the text from your edittext
String userInput = myEditText.getText().toString();
and then modify it as you want
To 'Modify' the String you can do it in many ways
You can use substrings , replace() , ... etc
also you can convert it to char array and modify it , then build your string again
String userInput = myEditText.getText().toString();
char[] myArray = userInput.toCharArray();
// your modification(s) here
userInput = new String(myArray);

Calling a phone number provided by GooglePlaces in Android

So using google places reference (detailed web-service) i retrieved a "formatted phone number" its in the form of (256) 922-0556. The goal is to call this number. The way I am trying is be using an intent. However, the number above is not a in the format to use Uri parse method. Anyone know a solution to call this number? Is there a different intent or a good way to turn this into Uri data? I have seen the opposite of this done like so:
1234567890 → (123) 456-7890
String formattedNumber = PhoneNumberUtils.formatNumber(unformattedNumber);
But i want to do the reverse of this. any ideas or alternative solutions?
Here is my code:
protected void onPostExecute(Boolean result){
Intent callintent = new Intent(Intent.ACTION_CALL);
callintent.setData(Uri.parse(phoneNum));
try {
startActivity(callintent);
}catch (Exception e) {e.printStackTrace();}
}
Where phoneNum is a formatted phone number string retrieved from GooglePlaces via JSON
To expand on Peotropo's comment: is there a better way to replace values than the following?
phoneNum = phoneNum.replace(" ", ""); // gets rid of the spaces
phoneNum = phoneNum.replace("-", ""); // gets rid of the -
phoneNum = phoneNum.replace("(", ""); // gets rid of the (
phoneNum = phoneNum.replace(")", ""); // gets rid of the )
This is simple string. Use String.replace() method to remove extra chars.
You can also use replaceAll method:
String phoneNumber = "(123)123-456465"
return phoneNumber.replaceAll("[^0-9]", "");
Not tested docs are here:
replaceAll
Java regular expressions
You don't need to do a string replace. You can use the Spannable code below to have your phone automatically recognize the number and call it. It adjusts for parentheses, spaces and dashes.
// call the phone
SpannableString callphone = new SpannableString("Phone: " + phone);
callphone.setSpan(new StyleSpan(Typeface.BOLD), 0, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
callphone.setSpan(new URLSpan("tel:"+phone), 7, 21, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView zphone = (TextView) findViewById(R.id.phone);
zphone.setText(callphone);
zphone.setMovementMethod(LinkMovementMethod.getInstance());
It will display
Phone: (123) 456-7890
Where you see 7,21 in the code above it is saying to start at the 8th character, which is the ( and end at the 21st character which is the last digit in the phone number. Adjust it to display how you want.
Nothing special to do in your view:
<!-- Phone Number Label -->
<TextView
android:id="#+id/phone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"/>

Removing space from Edit Text String

In my android app, I am getting the String from an Edit Text and using it as a parameter to call a web service and fetch JSON data.
Now, the method I use for getting the String value from Edit Text is like this :
final EditText edittext = (EditText) findViewById(R.id.search);
String k = edittext.getText().toString();
Now normally it works fine, but if we the text in Edit Text contains space then my app crashes.
for eg. - if someone types "food" in the Edit Text Box, then it's OK
but if somebody types "Indian food" it crashes.
How to remove spaces and get just the String ?
Isn't that just Java?
String k = edittext.getText().toString().replace(" ", "");
try this...
final EditText edittext = (EditText) findViewById(R.id.search);
String k = edittext.getText().toString();
String newData = k.replaceAll(" ", "%20");
and use "newData"
String email=recEmail.getText().toString().trim();
String password=recPassword.getText().toString().trim();
In the future, I highly recommend checking the Java String methods in the API. It's a lifeline to getting the most out of your Java environment.
You can easily remove all white spaces using something like this. But you'll face another serious problem if you just do that. For example if you have input
String input1 = "aa bb cc"; // output aabbcc
String input2 = "a abbcc"; // output aabbcc
String input3 = "aabb cc"; // output aabbcc
One solution will be to fix your application to accept white spaces in input string or use some other literal to replace the white spaces. If you are using only alphanumeric values you do something like this
String input1 = "aa bb cc"; // aa_bb_cc
String input2 = "a abbcc"; //a_abbcc
String input3 = "aabb cc"; //aabb_cc
And after all if you are don' caring about the loose of information you can use any approach you want.

Categories

Resources