hex to decimal conversion in java - android

I want to ask how can i convert from hex to decimal in Java ?
I tried using parseInt by getting the number from the user in an edit text and view the result in a text view after splitting the long spaced number but its not working
any ideas ?
String s=et.getText().toString();
String[] F=s.split(" ");
String last=F[F.length-1] ;
int i=Integer.parseInt(last, 16);
tv1.setText(i);

You're close... just make sure to convert i to a string like this:
tv1.setText(i + "");
Hope this helps :)

Related

how to remove special characters when i paste +1-xxx-xxx-xxxx from another source in android edit text with 10 digits length in android

copy from another source is : +1-541-xxx-3010
when i paste in my edit text i need to get the result as follow :
541xxx3010
need to remove special characters and also need to remove +1 (country code)
i need to display only 10 digits actual number after removing special chars
#Override
public void onTextChanged(CharSequence s, int start, int before, int count){
String edit = s.toString();
System.out.println("##"+edit);
edit = edit.replaceAll("[^0-9]", "");
String result = edit.replaceAll("[|?*<\":>+\\[\\]/'-]","");
System.out.println(result);
}
You can try SubString to get only 10 digit from your string.
For E.g. Your String is +1-541-xxx-3010. Now as you want you need to remove the + and country code.
String phone = "+1-541-xxx-3010"
result = phone.substring(Math.max(phone.length() - 12, 0)).replaceAll("-", ""));
From the above code it returns the result like this.
Result: 541xxx3010
NOTE : Before apply this code you need to check if your string is not
empty or its size is greater than or equal 12.
OR
If you don't want to use + and - then why don't you restrict the character using android:digits just apply below property in edittext.So it will not allow to enter the character apart from 0-9.
android:digits="0123456789"
First you need to remove country code from the string using substring() method,
For remove special character in your case it is "-" you can refer below code snippet
String result = inputString.replaceAll("[-]","");

change hex of integer resource to String

I am new in android.
in my value resource i create an xml layout and put this line in to it:
<integer name="mode_happy"> 0x1F60A</integer>
in my activity I want convert 0x1F60A to String. for this i create a method:
private String getStringOfEmojiCode(int emogiCode) {
StringBuilder sb = new StringBuilder();
//convert hex to char
sb.append(Character.toChars(emogiCode));
return sb.toString();
}
when I pass mode_happyto my method:
mSelectedMode =
getStringOfEmojiCode(getResources().getInteger(R.integer.mode_happy));
I receive this :
mSelectedMode: ��
but i want to get like this:0x1F60A
where is my mistake?
A formatter may be used to build the string from hex characters in a particular format:
String mSelectedMode
= String.format("0x%05X", getResources().getInteger(R.integer.mode_happy));
This worked for me, the hex which you stored as an integer was being converted to a decimal for me, but using the formatter worked. This also meant I did not have to use any other method.
Explanation:
The format 0x%05X takes in a 5 digit hex character signified by %05X with 'X' indicating hex. A lowercase x may be used which in this case would give out the output in lower case: 0x1f60a. The 0x is added to the format so as to have it as a prefix for each string. Refer to this for further details on formatting.

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

How to roud off a String value "5571.329849243164" in android

I'm getting below error while converting String array to Long array.
java.lang.NumberFormatException: Invalid long: "5571.329849243164". How to round off this value like 5571.
Use this
String.format("%.2f", d)
//try this way, hope this will help you...
String value = "5571.329849243164";
Toast.makeText(MyActivity.this,""+Math.round(Double.parseDouble(value)),Toast.LENGTH_SHORT).show();
round(Double value)`
see here
String string = "5571.329849243164";
Double value1 = Double.parseDouble(string);
tv.setText(Math.round(value1) + "/");
I understand you want to convert a String representing a floating point value to an Integer with rounding, not truncation. Perfectly reasonable.
Two choices.
Convert the string to a Double first (Double.valueOf()), then convert to Integer (intValue()) using a rounding algorithm. Usually it's enough to just add 0.5 to the Double.
Round the String using string operations, then convert to Integer. Split the string at the first ".", convert it to Integer (getInteger()). If the digit after the "." is in the range 5-9 then add one.
I'm sure you can write the code.

How can I pull individual characters from a string and convert them to numbers?

What I'm trying to do is find a way I can take the word "camel" for example from a EditText field and make for instance c=2 a=1 m=4 e=5 l=3. Is there anyway I can pull the individual characters from a string and convert them to numbers?
I've tried using "split" to separate each character into an array but I can't figure out how to convert the letters into numbers
so I can do something like:
a=1
b=2
c=3
int temp = (int)(array[1]+array[2]+array[3]+etc...)
using the example of "camel" would equal 15
This is what I have so far:
String name = inputarea.getText().toString();
String[] array = name.split("");
for(int i =0; i < array.length ; i++)
The biggest problem I keep having is if I try to pull from the 7th position in the array and nothing is there. (camel only has 5 characters) then I get a nice big error.
Thank you for any help that can be provided.
Edit: I figured it out after a few hours of playing with it here is my working code:
String firstname = inputarea.getText().toString();
char[] array = firstname.toCharArray();
final char[] array2 = new char[15];
System.arraycopy(array, 0, array2, 0, array.length);
if (array2[0] == 'A' ) {
array2[0] = '1';
}
suggestion:
first, need define all letter, from a-z (A-Z), the ASCII code 'a' to 'z' is 97 to 122, if you want support the upper letter, you need add A-Z.
then, get the letter in the string, u can use this:
for(int i=0;i<string.length();i++){
int number = string.charAt(i);
}
when you get the number size, you can reduce to the base number('a' is 97), you will get the individual number
Does String.charAt() works for you?
As for converting to number, if the numbers are consecutive you can define a fixed string with all the characters you want to map and use String.indexOf(). If not, you can have a parallel array with ints or use a Map.

Categories

Resources