Android String.format() Returns Question Mark (??) - android

I have an app which downloads some files from internet. The source file name is dynamically generated depending on user selection. I use following method to create source file name. Note that fileId is an integer (1-99).
final String fileName = "file_" + String.format("%02d", fileId) + "_download.jpg";
The issue is I have seen some users are unable to download files (and of course they leave 1 start ratings :( ). When I check my server log I see some download requests came with file names like file_??_download.jpg. It looks like String.format() has returned ?? instead of two digit number.
I searched everywhere and could not find a solution for this. Can anybody tell me what's wrong with this code? I could not even re-produce this error on any of my devices.
Thanks!

You have to do it instead:
final String fileName = "file_" + String.format("%d", fileId) + "_download.jpg";
or
final String fileName = "file_" + fileId + "_download.jpg";
if you really want only the two last digits, do it:
int formattedFileId = fileId % 100;
final String fileName = "file_" + (formattedFileId < 10 ? '0' : '') + String.format("%d", formattedFileId) + "_download.jpg";
or
int formattedFileId = fileId % 100;
final String fileName = "file_" + (formattedFileId < 10 ? '0' : '') + formattedFileId + "_download.jpg";

String.format will use the digits for the default locale which are not necessarily 0-9. Use the version that permits setting a locale, and pass in Locale.ROOT.
String.format(Locale.ROOT, "%02d", fileId)

Related

how to remove special character from string except + in android?

I am fetching number from contact book and sending it to server. i get number like this (+91)942 80-60 135 but i want result like this +9428060135.+ must be first character of string number.
Given your example you want to replace the prefix with a single + character. You also want to remove other non-numeric characters from the number string. Here's how you can do that:
String number = "(+91)942 80-60 135";
number = "+" + number.replaceAll("\\(\\+\\d+\\)|[^\\d]", "");
The regex matches any prefix (left paren followed by a + followed by one or more digits, followed by a right paren) or any non digit character, and removes them. This is concatenated to a leading + as required. This code will also handle + characters within the number string, e.g. +9428060135+++ and +(+91)9428060135+++.
If you simply wanted to remove any character that is not a digit nor a +, the code would be:
String number = "(+91)942 80-60 135";
number = number.replaceAll("[^\\d+]", "");
but be aware that this will retain the digits in the prefix, which is not the same as your example.
You can use String.replace(oldChar, newChar). Use the code below
String phone = "(+91)942 80-60 135"; // fetched string
String trimmedPhone = phone.replace("(","").replace(")","").replace("-","").trim();
I hope it will work for you.
check this. Pass your string to this function or use as per code goes
String inputString = "(+91)942 80-60 135";
public void removeSpecialCharacter(String inputString) {
String replaced = inputString.replaceAll("[(\\-)]", "");
String finalString = replaced.replaceAll(" ", "");
Log.e("String Output", " " + replaced + " " + second);
}

How to extract particular part of a string?

I have a Link which never changes. The only thing which changes is the file name (in bold). so how do I get the file name from this link? I want to display this in a textview or toast-
http://apkins.aptoide.com/aptoide-8.1.0.1.apk?=x
Here is a regex-less solution:
public static String getFileName(String link) {
int endIndex = link.lastIndexOf('?');
return link.substring(26, endIndex);
}
It's pretty simple. It first gets where the file name ends i.e. the position of the last "?". Then it "cuts out" a new string from the link starting from the 27th character to the end of the file name.
This should do the trick
String fileName = url.substring(url.lastIndexOf('/') + 1);
You can also try URLUtil.guessFileName(url, null, null)
Edit 1
String url = "any url"
String given = "http://apkins.aptoide.com/aptoide-8.1.0.1.apk?=x";
String extractedAppName = given.substring(given.lastIndexOf("/") + 1, given.lastIndexOf("?"));
This should work. It takes the position of the / before the name and then the position of the ?. It takes the string (substring) between those two characters. Just give it a try and you'll see.

I Build a Brain Trainer app but Not Showing my TEXTVIEW when i run my app and warning is showing do not concatenate text display with setText

sumTextView.setText(Integer.toString(a) + " + " + Integer.toString(b));
This Line show warning you see in pic..
Use String.format();
sumTextView.setText(String.format("%1$d + %2$d", a, b));
With this you can format a string correctly with multiple variables, no matter whether they are strings or integers. This example takes the value of variable a and replaces the placeholder %1$d with it. Same goes for the other variable.
take an string copy whole line in it, then show string in setText
String str = (Integer.toString(a) + " + " + Integer.toString(a));
sumTextView.setText(str);
1. The First String Says that do not concate string with setText property.
String txt = String.valueOf(a) + " + " + String.valueOf(b);
sumTextView.setText(str);
2. Second warning says that your program have possibility to crash or genearte an exception in case if value of a or b is null or not an integer.
So check condition if(a!=null and b!=null) then display text in if condition.

How to get substrings from a string in android?

Hello I have a long string and its having html tags like "" and "" and ,I want to get values from this strings,can anyone give me solution how to get values from it?
my string is:
<strong>1 king bed</strong><br /> <b>Entertainment</b> - Wired Internet access and cable channels <br /><b>Food & Drink</b> - Refrigerator, minibar, and coffee/tea maker<br /><b>Bathroom</b> - Shower/tub combination, bathrobes, and slippers<br /><b>Practical</b> - Sofa bed, dining area, and sitting area<br />
my try
int start = description_long.indexOf("Food");
int end = description_long.indexOf("<br />");
String subString = description_long.substring(start,
end);
System.out
.println("===============MY SUB STRING FROM STRING============="
+ start
+ ""
+ "============end======="
+ end + "");
i want to get values of Food & Drink and Bathroom,can any one please tell me how to get these values in a seperate string in android programatically.
Better you could use a regular expression or try to parse.
<a[^>]*>([^<]*)<[^>]*>(.*)
http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
Try this but values must end with <br />
String key = "<b>Bathroom</b>"; //<b>Food & Drink</b>
int start = htmlInput.lastIndexOf(key);
String value = htmlInput.substring(start + key.length(), htmlInput.indexOf("<br />", start));
System.out.println(value);

Android PDF Writer(APW) Enconding

I am using Android PDF Write(APW) to create a PDF, but it doesn't work with some special characters(portuguese).
mypdf.addText(170, 50, 40,"Coração");
The standard enconding is:
mypdf.setFont(StandardFonts.SUBTYPE, StandardFonts.COURIER, StandardFonts.WIN_ANSI_ENCODING);
outputToFile("helloworld.pdf",pdfcontent,"ISO-8859-1");
I'v tried
outputToFile("helloworld.pdf",pdfcontent,"UTF-8");
outputToFile("helloworld.pdf",pdfcontent,"UTF-16");
outputToFile("helloworld.pdf",pdfcontent,"Cp1252");
and didn't succeed.
Any ideas what should I do?
EDIT
The method outputToFile is defined as:
private void outputToFile(String fileName, String pdfContent, String encoding) {
File newFile = new File(Environment.getExternalStorageDirectory() + "/" + fileName);
try {
newFile.createNewFile();
try {
FileOutputStream pdfFile = new FileOutputStream(newFile);
pdfFile.write(pdfContent.getBytes(encoding));
pdfFile.close();
} catch(FileNotFoundException e) {
//
}
} catch(IOException e) {
//
}
}
The method addText is defined as:
public void addText(int leftPosition, int topPositionFromBottom, int fontSize, String text, String transformation) {
addContent(
"BT\n" +
transformation + " " + Integer.toString(leftPosition) + " " + Integer.toString(topPositionFromBottom) + " Tm\n" +
"/F" + Integer.toString(mPageFonts.size()) + " " + Integer.toString(fontSize) + " Tf\n" +
"(" + text + ") Tj\n" +
"ET\n"
);
}
Besides, I change the font color to white adding the following rawcontent:
mypdf.addRawContent("1 1 1 rg\n");
Then I come back to the black font color:
mypdf.addRawContent("0 0 0 rg\n");
I took all the information provided, wrote the following simple unit test method and ran it.
public void test19192108()
{
PDFWriter mPDFWriter = new PDFWriter(PaperSize.FOLIO_WIDTH, PaperSize.FOLIO_HEIGHT);
mPDFWriter.setFont(StandardFonts.SUBTYPE, StandardFonts.COURIER, StandardFonts.WIN_ANSI_ENCODING);
mPDFWriter.addText(170, 50, 40,"Coração");
String pdfcontent = mPDFWriter.asString();
outputToFile("helloworld19192108.pdf",pdfcontent,"ISO-8859-1");
}
(outputToFilebeing the helper method from the APW PDFWriterDemo class)
The result looks like this:
This seems pretty much to fulfill the expectations.
Thus, in whichever way it doesn't work with some special characters(portuguese) for the OP, some vital information is missing for reproducing the issue.
PS: Depending on the setup of the development environment, there might be an issue with non-ASCII characters in the source code. Thus, it might be a good idea to replace
mPDFWriter.addText(170, 50, 40,"Coração");
with
mPDFWriter.addText(170, 50, 40,"Cora\u00e7\u00e3o");
PPS: Adobe Reader after viewing a file generated like this wants to repair it. The reason is that the cross reference table is broken. The code generating entries for it is this:
public void addObjectXRefInfo(int ByteOffset, int Generation, boolean InUse) {
StringBuilder sb = new StringBuilder();
sb.append(String.format("%010d", ByteOffset));
sb.append(" ");
sb.append(String.format("%05d", Generation));
if (InUse) {
sb.append(" n ");
} else {
sb.append(" f ");
}
sb.append("\r\n");
mList.add(sb.toString());
}
(from CrossReferenceTable.java)
Counting the characters in this entry we get 10 + 1 + 5 + 3 + 2 = 21.
According to the specification, though:
Each entry shall be exactly 20 bytes long, including the end-of-line marker
(from section 7.5.4 Cross-Reference Table of ISO 32000-1)
When using (the current version of) the Android PDF Writer, you should fix this code, too.

Categories

Resources