I have some different language html file for different language environment, and all of those html files contain images. Now I want to show suitable html files with WebView adapt to current language of Android. How can I do that? Thanks.
You can give special names for non-English files like file-de.html for German and then use the following code:
private static String getFileName() {
Configuration config = getResources().getConfiguration();
InputStream stream = null;
try {
String name = "file-" + config.locale.getLanguage() + ".html";
stream = getAssets().open(name);
return name;
} catch (IOException exception) {
return "file.html";
} finally {
if (stream != null) {
stream.close();
}
}
}
You might use "string values" to get Android language dependent HTML file names without using any additional java code and just using getString(). Here's an example for 2 languages:
In file values/strings.xml:
<string name="html_help_basepage">en_help.html</string>
In file de/strings.xml:
<string name="html_help_basepage">some_german_help.html</string>
And so on...
For your Java code (loading from local file in asset folder as in question)
helpView = (WebView) findViewById(R.id.wv_help);
String adaptedToLanguage = getString(R.string.html_help_basepage)
helpView.loadUrl("file:///android_asset/" + adaptedToLanguage);
No additional Java code is needed. I hope this is helpful and answers the question.
Added a new answer, which should be more precise by providing an example.
Related
I need to read a text stream by using StreamReader from file on android platform. File is about 100k lines, so even editor is getting stuck if i try to load it all to TextAsset or if i use WWW.
I simply need to read that file line by line without loading it all to a string. Then i'll do a tree generation from the lines that i got from the file. (But probably that part doesn't matter, i just need help on file reading part.)
I'm giving the code that i wrote down below. It works perfectly on editor, but fails on android.
I would be glad if anyone tell me, what am i missing.
(ps. english is not my native and this is my first question on the site. so sorry for the any mistakes that i may have done.)
private bool Load(string fileName)
{
try
{
string line;
string path = Application.streamingAssetsPath +"/";
StreamReader theReader = new StreamReader(path + fileName +".txt", Encoding.UTF8);
using (theReader)
{
{
line = theReader.ReadLine();
linesRead++;
if (line != null)
{
tree.AddWord(line);
}
}
while (line != null);
theReader.Close();
return true;
}
}
catch (IOException e)
{
Debug.Log("{0}\n" + e.Message);
exception = e.Message;
return false;
}
}
You can't use Application.streamingAssetsPath as a path on Android because streaming assets are stored within the JAR file with the application.
From http://docs.unity3d.com/Manual/StreamingAssets.html:
Note that on Android, the files are contained within a compressed .jar
file (which is essentially the same format as standard zip-compressed
files). This means that if you do not use Unity’s WWW class to
retrieve the file then you will need to use additional software to see
inside the .jar archive and obtain the file.
Use WWW like this in a coroutine:
WWW data = new WWW(Application.streamingAssetsPath + "/" + fileName);
yield return data;
if(string.IsNullOrEmpty(data.error))
{
content = data.text;
}
Or, if you really want to keep it simple (and your file is only a few 100k, stick it in a resource folder:
TextAsset txt = (TextAsset)Resources.Load(fileName, typeof(TextAsset));
string content = txt.text;
I want to write XPKeywords in a Jpeg Image. Till now I am using Sansaleen java api for writing Exif tags in Jpeg images. I am able to write most of the tags like subject, comment, author, rating but I am not able to write Windows XP Keywords. I am using below code:
public static TiffOutputField getTiffOutputFieldKeyword(
TiffOutputSet outputSet, String metaDataToChange) {
TiffOutputField imageHistoryPre = outputSet
.findField(TiffConstants.EXIF_TAG_XPKEYWORDS);
if (imageHistoryPre != null) {
outputSet.removeField(TiffConstants.EXIF_TAG_XPKEYWORDS);
}
TiffOutputField tiffOutputField = new TiffOutputField(
TiffConstants.EXIF_TAG_XPKEYWORDS,
TiffFieldTypeConstants.FIELD_TYPE_BYTE,
metaDataToChange.length(), metaDataToChange.getBytes("UTF-16"));
return tiffOutputField;
}
I have googled this issue and came to know that XP_Keyword accept special encoded in UCS2 so I have updated my code. But still not able to write complete tags. Tags are semi-colon separated.
Please let me know if there present any resolution for the above issue or is there any other java/android lib which can write Tags in Jpeg files.
Got it working:
public static TiffOutputField getTiffOutputFieldKeyword(
TiffOutputSet outputSet, String metaDataToChange) {
TiffOutputField imageHistoryPre = outputSet
.findField(TiffConstants.EXIF_TAG_XPKEYWORDS);
if (imageHistoryPre != null) {
outputSet.removeField(TiffConstants.EXIF_TAG_XPKEYWORDS);
}
TiffOutputField tiffOutputField = new TiffOutputField(
TiffConstants.EXIF_TAG_XPKEYWORDS,
TiffFieldTypeConstants.FIELD_TYPE_BYTE,
metaDataToChange.getBytes("UTF-16").length, metaDataToChange.getBytes("UTF-16"));
return tiffOutputField;
}
Just use length of Bytes in "UTF-16" and then write. Also, Make sure you trim the characters to not include any spaces. Also, please give a try by separating string with Semicolon(;) as By default Windows take semicolon separated keywords.
Is it possible to load strings.xml from sd card instead of application res/values/... Search on the web but didn't find any tutorials. My thought is download the xml to sd card then save the strings element to an array.
public void stringsxml(){
File file = new File(Environment.getExternalStorageDirectory()
+ ".strings.xml");
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(file));
try {
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
String data= contents.toString();
}
Well, actually it is semi-possible, but you have to create a derivate LayoutInflater which will replace string codes with thus read strings.
I have documented my attempts and failings together with initial implementation here.
Summary: simple strings work, string arrays do not
No, this is not possible. Check Android decoumentation about resources:
The Android SDK tools compile your application's resources into the application binary at build time. To use a resource, you must install it correctly in the source tree (inside your project's res/ directory) and build your application.
Resources are built-in into the application binary and you can't read them from a file.
i am using a properties file to get the url of various webservices i am calling from my android. I want to provide a congiguration option so that ip address for web service can be modified.
how to proceed ?
i have a resource folder in src folder which have the following values
update=http://10.52.165.226:50000/android/rest/get/updateSfc
ShopOrder=http://10.52.165.226:50000/android/rest/getShopOrder/bySite?site=
i am using resource bundle to use this values in android.?
I am thinking of reading the file and replace all occrence of Ip address. how to rad the properties file and edit it in android
Here is a complete solution for you to use .properties file in your project.
1 Create a file named app.properties in assets folder of your android project
2 edit the file and write with in properties that you want to use for example as
test=success
And Save file
3 Write this Method with in your Activity Class
private Properties loadPropties() throws IOException {
String[] fileList = { "app.properties" };
Properties prop = new Properties();
for (int i = fileList.length - 1; i >= 0; i--) {
String file = fileList[i];
try {
InputStream fileStream = getAssets().open(file);
prop.load(fileStream);
fileStream.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "Ignoring missing property file " + file);
}
}
return prop;
}
4 With in OnCreate Method write some thing like this
Properties prop = null;
try {
prop = loadPropties();
} catch (IOException e) {
Log.e(TAG, "Exception", e);
}
Toast.makeText(getApplicationContext(), "Result " + prop.getProperty("test"),
Toast.LENGTH_LONG).show();
5 add necessary imports
Hope this helps :)
Read about Data Storage in Android and more specifically Shared Preferences. For more complete usage of saving user preferences, read about the PreferenceActivity.
A tutorial on using Shared Preferences can be found here
Resources, Assets and other files/folders that form the part of Apk cannot be modified.You can use a database for depending on nos of rows that you will use
I created a simple html file that loads some images from my local hard-drive (ubuntu).
It is enough to put
<img src=/home/user/directory/image.jpg></img>
Now I need to know if it is the same when Html5 is displayed on a tablet like Android or iOS, or Html5 is used in offline app.
I mean, if html5 can load an image from the device's filesystem just like on my computer, without localStorage or sessionStorage.
If you deploy the application as native application it is possible (wrap it with Phonegap).
For saved HTML files it is not possible.
On Android, it can be done even though it looks a bit tricky at first. Say you have defined a WebView in your layout.xml, which you want to fill with an html file shipped with your application, which in turn should import a png also shipped with your application.
The trick is to put the html file into res/raw and the png into assets.
Example.
Say you have hello.html which should include buongiorno.png.
Within your project, say MyProject, place buongiorno.png into MyProject/assets.
The hello.html goes into MyProject/res/raw (because we want to avoid having it 'optimised' by the android resource compiler), and could look like this:
<html>
<head></head>
<body>
<img src="file:///android_asset/buongiorno.png"/>
<p>Hello world.</p>
</body>
</html>
In your java code, you would put this code:
WebView w = (WebView) findViewById(R.id.myWebview);
String html = getResourceAsString(context, R.raw.hello);
if (html != null) {
w.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null);
}
where getResourceAsString() is defined as follows:
public static String getResourceAsString(Context context, int resid) throws NotFoundException {
Resources resources = context.getResources();
InputStream is = resources.openRawResource(resid);
try {
if (is != null && is.available() > 0) {
final byte[] data = new byte[is.available()];
is.read(data);
return new String(data);
}
} catch (IOException ioe) {
throw new RuntimeException(ioe);
} finally {
try {
is.close();
} catch (IOException ioe) {
// ignore
}
}
return null;
}