Replacing string in html dynamically in Android - html

I am using "loadDataWithBaseUrl(...)" to load a html file, stored in assets, to Webview. that contains a string "Loading..." and a rotating GIF. String "Loading..." is hard coded, and it'll not be localized. How to replace that string dynamically, so that it can be localized?
Please help me to resolve this.

There are various solutions I could think of :
Load a different asset file according to the current language (get the current language using Locale.getDefault()), This way you can translate your HTML files independently.
Use place holders in your HTML file (for instance #loading_message#), then load the asset file in a String, replace all the occurences of the placeholder by the appropriate localised message (String.replaceAll("#loading_message#", getText(R.string.loading_message).toString())), finally load the processed HTML into the WebView using the loadData(String data, String mimeType, String encoding) function.
To load the asset file, you can do something like that:
File f = new File("file:///android_asset/my_file.html");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
StringBuffer sb = new StringBuffer();
String eachLine = br.readLine();
while(eachLine != null) {
sb.append(eachLine);
sb.append("\n");
eachLine = br.readLine();
}
// sb.toString is your HTML file as a String

I had a similar problem when using the WebView to show help text that should be translated.
My solution was to add multiple translated HTML files in assets and loading them with:
webView.loadUrl("file:///android_asset/" + getResources().getString(R.string.help_file));
For more details go to: Language specific HTML Help in Android

String str = "Loading ..."
String newStr = str.substring("Loading ".length());
newStr = context.getResourceById(R.string.loading) + newStr;
I hope the code is sufficiently clear to understand the idea: extract the string without "Loading " and concatenate it with the localized version of "Loading" string

Related

Superscript characters are resulting in to junk characters in generated CSV file when using ICsvListWriter

I am trying to write superscript characters in .csv file. I am using method write(List<?> columns)of org.supercsv.io.ICsvListWriter. In generated .csv file the superscript character is coming along with junk character before it.
List columns = new ArrayList();
String myString = "abcd1";
columns.add(myString.replaceAll("1", "¹"));
csvWriter.write(columns);
In the generated .csv file it is coming as
abcd¹
I also tried with unicode but it is not helping.
columns.add(myString.replaceAll("1", "\u00B9"));
Any suggestion here please?
Found a solution for this problem. Correction was needed in creating ICsvListWriter object. Previously I was having this code where 'response' is HttpServletResponse.
CsvPreference preference = new CsvPreference.Builder(CsvPreference.STANDARD_PREFERENCE).useEncoder(new DefaultCsvEncoder()).build();
ICsvListWriter csvWriter = new CsvListWriter(response.getWriter(), preference);
This code is enhanced to this:
ServletOutputStream output = response.getOutputStream();
output.write(new byte[] { (byte)0xEF, (byte)0xBB, (byte)0xBF });
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"));
CsvPreference preference = new CsvPreference.Builder(CsvPreference.STANDARD_PREFERENCE).useEncoder(new DefaultCsvEncoder()).build();
ICsvListWriter csvWriter = new CsvListWriter(writer, preference);
This fixed the issue and all of the superscript characters are now coming properly in generated CSV file without any junk characters. No mater whether I use actual superscript characters or their Unicode, this fix works.

How to replace special symbols in a binary?

I am trying to read a pdf from a URL, return it as a binary and replace some characters. This is working for plain text with the following code but if the pdf has any special symbols like Trademark, copyright etc then my webservice is unable to return the result. Can some one please help me how to achieve this. The output should definitely be a binary output :
String html="";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream in = new URL(jsonobj.getString("xBody")).openStream();
int reads = in.read();
while(reads != -1){
baos.write(reads);
reads = in.read();
}
html= baos.toString();
The method baos.toString() internally calls new String(buffer), which uses the default encoding (the encoding actually being used by your system, probably not UTF-8). Try to provide the encoding explicitly, as follows:
String html = new String(baos.toByteArray(), "UTF-8");

JSON keeping the existing content while writing new ones into it (txt file)

So im making this memory game and im trying to add a scoreboard and i want to write the data to a txt file using JSON. I got all of that to work but now i have a small issue, everytime i run my program the existing data in my txt file gets overwritten by the new data.
Here is the code that i use:
public static void Score(String gamescore, string loginname)
{
List<Highscore> Myhighscores = new List<Highscore>();
Myhighscores.Add(new Highscore { Score = gamescore, Name = loginname });
string Jstr = JsonConvert.SerializeObject(Myhighscores);
File.WriteAllText(#"c:\temp\hs.txt", Jstr);
}
does anyone know how i can keep the existing data and also write the new data into the txt file?
I figured it out my self all i needed to do is read the existing data like this:
string hs = File.ReadAllText(#"c:\temp\hs.txt");
and put it back into my list "Myhighscores" like this:
Myhighscores = JsonConvert.DeserializeObject<List<Highscore>>(hs);
No thanks to Sagar V who just bitched that i put the jquery tag in.

Javascript does not accept HTML String from MVC?

Javascript does not accept HTML String from MVC?
My MVC contoller from where I am sending the HTML template in string from txt file
using (StreamReader sr = new StreamReader(#"D:\Templates\NewGridTemplate.txt"))
{
// Read the stream to a string, and write the string to the console.
obj.sGridTemplate = sr.ReadToEnd().Replace(Environment.NewLine, " ");
//Console.WriteLine(line);
}
return View(obj);
Actual code in csHTMl Javascript
var sHTML=$(#Model.sGridTemplate);
Below is screen shot for error . HTML string is not accepted by Javascript. shows character "<" etc.. Please help let me know what I missed.Image 3
You need to put your content within quotes so that it becomes a Javascript string, otherwise it'll be interpreted as syntax and you get the error because it's not valid JS syntax
var sHTML=$('#Model.sGridTemplate');
And the problematic line in the resulting client-side code should look more like this:
var sHTML=$(' < ...
... than:
var sHTML=$( < ...

Read text from webpage without html

I'm trying to extract the text of an url using WebClient in C#.
But the content contains html tags and I only want raw text.
My code is as follows:
string webURL = "https://myurl.com";
WebClient wc = new WebClient();
byte[] rawByteArray = wc.DownloadData(webURL);
string webContent = Encoding.UTF8.GetString(rawByteArray);
I get the following error with the above code:
'The remote server returned an error: (403) Forbidden.
and change my code to:
string webURL = "https://myurl.com";
WebClient wc = new WebClient();
wc.Headers.Add("user-agent", "Only a Header!");
byte[] rawByteArray = wc.DownloadData(webURL);
string webContent = Encoding.UTF8.GetString(rawByteArray);
The above code has no error, but the result contains html tags. html tags can be removed using Regex:
var result= Regex.Replace(webContent, "<.*?>", String.Empty);
But this method is not accurate and does not good performance. Is there a better way to extract just the text without the html tags from an url?
The Navigate function doesn't block execution. You need to register for the DocumentCompleted event, then you should be able to grab the contents within that.
It's not the way you're using that. First of all you should know you have to use Web Client
Now you can try this code :
WebClient client = new WebClient();
string content = client.DownloadString("https://stackoverflow.com/search?q=web+browser+c%23");