Showing empty space for integer - java

String s1 = sh.getString("name", "");
int a = sh.getInt("age", 0);
For this code I would like to show empty spaces for s1 and a if there is no input entered. When I run the application String s1 it shows empty space but int a showd 0 since the default value is 0.
Is there any way to show empty space instead of 0?
I have tried puting
Integer.parseInt("")
But it was not working.
Is there any solution for this?
Thank you.

You can add a condition to check if it is 0 or not. Using null as suggested by answer by Frank can be used but it is not preferred. Instead you can try this:
String text = a == 0 ? "" : String.valueOf(a);
textView.setText(text);
button.setText(text);

You just n need to parse it as string you can't check empty if you are using int variable So just get your age as String and also send it with string via intent you can also parse it as int after getting it from intent
Like option 1
Intent intent =new Intent(this,B.class);
intent.putExtra("name", name);
intent.putExtra("age", age.toString);
Here you can get Like
String s1 = sh.getString("name", "");
String age= sh.getString("age", "");
Here you can check age is empty then if you want this value as int you can Parse it as int a=Integer.parseInt(age);
Hope this will help you

Related

I want to print a Forward Slash, but i am getting a warning , how to solve [duplicate]

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 parse integer from a long string

I want to parse two values from a string in android studio.
I cannot change the data type from web so I need to parse an Intt.The string that I receive from web is
5am-10am.
How can I get these values i.e. 5 and 10 from the string "5am-10am".
Thanks in advance for help.
its work only this kind of format "Xam-Yam".
String value="5am-10am";
value.replace("am","");
value.replace("pm","");//if your string have pm means add this line
String[] splited = value.split("-");
//splited[0]=5
//splited[1]=10
Here is the trick you should use:-
String timeValue="5am-10am";
String[] timeArray = value.split("-");
// timeArray [0] == "5am";
// timeArray [1] == "10am";
timeArray [0].replace("am","");
// timeArray [0] == "5";// what u needed
timeArray [1].replace("am","");
// timeArray [1] == "10"; // what u needed
So, the code below shows step by step how to parse the format you are given. I also added in the steps to use the newly parsed Strings as ints so you can perform arithmetic on them. Hope this helps.
`/*Get the input*/
String input = "5am-10am"; //Get the input
/*Separate the first number from the second number*/
String[] values = input.split("-"); //Returns 'values[5am, 10am]'
/*Not the best code -- but clearly shows what to do*/
values[0] = values[0].replaceAll("am", "");
values[0] = values[0].replaceAll("pm", "");
values[1] = values[1].replaceAll("am", "");
values[1] = values[1].replaceAll("pm", "");
/*Allows you to now use the string as an integer*/
int value1 = Integer.parseInt(values[0]);
int value2 = Integer.parseInt(values[1]);
/*To show it works*/
int answer = value1 + value2;
System.out.println(answer); //Outputs: '15'`
I will use some regex to remove the other String and leave only the numeric data. sample code below:
public static void main(String args[]) {
String sampleStr = "5am-10pm";
String[] strArr = sampleStr.split("-"); // I will split first the two by '-' symbol.
for(String strTemp : strArr) {
strTemp = strTemp.replaceAll("\\D+",""); // I will use this regex to remove all the string leaving only numbers.
int number = Integer.parseInt(strTemp);
System.out.println(number);
}
}
The advantages of this is you don't need to specifically remove "am" or "pm" because all of the other character will be remove and the numbers will only be left.
I think that this way can be the faster. Please consider that the regex doesn't validates so it will parse values as "30am-30pm" for example. Validation comes apart.
final String[] result = "5am-10pm".replaceAll("(\\d)[pa]m", "$1").split("-");
System.out.println(result[0]); // -- 5
System.out.println(result[1]); // -- 10

How to escape special characters from JSON when assign it to Java String

im tring to assign value from json to java String. but JSON value is including some special charactor ("\"). when i was try to assigen it to the string it gives error.
this is the JSON value,
"ValueDate":"\/Date(1440959400000+0530)\/"
this is how i trying to use it.
HistoryVO.setValueDate(DataUtil.getDateForUnixDate(historyJson.getString("ValueDate")));
or
Given that
I want ... to get [the] Date(1440959400000+0530) part,
I would use
String value = "/Date(1440959400000+0530)/";
int pos1 = value.indexOf("Date(");
if (pos1 > -1) {
int pos2 = value.indexOf(")", pos1);
if (pos2 > pos1) {
value = value.substring(pos1, pos2 + 1);
System.out.println(value);
}
}
Output is
Date(1440959400000+0530)
Note: This works by looking for "Date(" and then the next ")", and it removes everything not between those two patterns.
If you have specific character, ( and ), use substring method to get the value.
String value = "\\/Date(1440959400000+0530)\\/";
int start = value.indexOf("(");
int last = value.lastIndexOf("0");
value = value.substring(start + 1, last + 1);
System.out.println(value); <--- 1440959400000+0530
DataUtil.getDateForUnixDate(value);
I don't know DataUtil.getDateForUnixDate() method, but take care of + character because of it is not number string.
Update
To remove / character use replace method.
String value = "/Date(1440959400000+0530)/";
value = value.replace("/", "");
System.out.println(value);
output
Date(1440959400000+0530)
Mac,
As you asked for something like
String ValueDate = "\/Date(1440959400000+0530)\/";
The above one is not possible in java string, As it shows as invalid escape sequence, So replace the slash '\' as double slash '\' as below,
String ValueDate = "\\/Date(1440959400000+0530)\\/";
If am not clear of our question, pls describe it clearly
Regards,
Hari
i found the answer for my own question.
historyJson.getString("ValueDate");
this return the String like /Date(1440959400000+0530)/
now i can split it. thank you all for the help.
regards, macdaddy

Read yes/no field from access - Display on java as String

I am having trouble converting an int to string.
I use java to connect to a database (Access).
Now I'm trying to retrieve the value from a YES/NO Field Access but it'sa check box
jlbABC.setText(rs.getString("RightWrong"));
The answer I get is 1 if it is True(YES), and 0 if is False (NO)
How do I change the answer from 1 to YES and 0 to NO?
I don't understand at all what you want, but here is how I normally convert any integer into a string literal.
String values[] = new String[]{"NO", "YES"};
int myValue = ... wherever it comes from;
String myConvertedValue = values[myValue];
You may also check if myValue is in bounds of the array of values.
If you are trying to set the value of a string based on if it is a 0 or a 1 you could use this.
int i = rs.getInt("RightWrong");
String yesno = i == 1 ? "YES" : "NO";
This has the benefit of saying that the result will be "YES" if the value is 1 or "NO" otherwise.

string tokenizing from textview

I have TextView with text that changed dynamically.
i want tokenizing this text with delimiter space " " and send to another textview
this is my code
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId()==R.id.button5){
Intent i = new Intent(this, Tokenizing.class);
String test = ((TextView)findViewById(R.id.textView6)).getText().toString();
String result = null;
StringTokenizer st2 = new StringTokenizer(test," ");
while (st2.hasMoreTokens()) {
String st3 = st2.nextToken();
System.out.println(st3);
result = st3;
}
i.putExtra("result", result);
startActivity(i);
Log.i("Test Klik Next", result);
but i have just last word in the textview.
text before tokenizing:
Examples of paradoxes can be humorous and confusing
text after tokenizing:
confusing
where is the part of my coding is wrong?
You are overwriting the result every time you read a new token
result = st3;
So it's always equal to the last value. Change the type of result from String to StringBuilder and just build it as you go
result.append(st3 + " "); //re-adding the space as the StringTokenizer will remove it
Then after the StringTokenizer loop just get the built String using result.toString()
Why not result += st3?
Some other answers suggest you do this. The reason not to do this is that in Java, String is immutable. This means they can't be changed so any time you append two String objects, a new String object is created.
So every step through the loop you are creating a new String object which is inefficient and unnecessary. StringBuilder is not immutable and Strings can be appended to it without the overhead of creating new objects every time.
StringTokenizer
Worth noting -as #RGraham said in the comments- that this class is deprecated. This means it's no longer in common use, use of it is discouraged and it could be removed at some point.
More information here.
Tokens - in or out
As other answers assumed the opposite of me and after discussion on one of said answers and on meta, I feel I need to clarify this. I
'm not sure if your intention was to get rid of the tokens (in this case spaces " ") and end up with
Examplesofparadoxescanbehumorousandconfusing
or to replace them when outputting the final String and get out what you put in. So I assumed you wanted to preserve the original meaning and replace them. Otherwise a quicker way to get the result above would be to simply skip all the tokenizing and do
test.replaceAll(" ","");
while (st2.hasMoreTokens()) {
String st3 = st2.nextToken();
System.out.println(st3);
result = st3; // Everytime you are reassigning result to some other String
}
Replace
result = st3; by (initialize String result=" ";)
result+=st3+" "
and then replace
i.putExtra("result", result); with i.putExtra("result", result.trim());
Try this , it will show perfect result.
You can also do this result.append(st3+" "); and then i.putExtra("result", result.trim());

Categories