I want to translate my text into device language.
So I tried below code
String InputString="My text";
String OutputString = null;
Language fromLanguage = Language.ENGLISH;
Language toLanguage = Language.valueOf(Locale.getDefault().getDisplayLanguage().toUpperCase());
try {
Translate.setHttpReferrer("http://android-er.blogspot.com/");
OutputString = Translate.execute(InputString,
fromLanguage, toLanguage);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
OutputString = InputString;
}
return OutputString;
If device language is English it executes well but i changed to any other language then it shows
java.lang.IllegalArgumentException: FRANÇAIS is not a constant in the enum type class com.google.api.translate.Language
not FRANCAIS if I select any language except English it shows IllegalArgumentException with selected language.
What have I done wrong, or is there another way to translate text into device language?
Read this document, it explains all you need to know: Android Localization
Related
On Android, can we change the keyboard input language (English(US), Hindi, French, etc.) from Java/C++ or the terminal(like the imein /system/bin?
For those who said not possible here it is, it's very much possible but device needs to be rooted or your app needs to be system signed.
protected static void changekeyboard(String keyboardID, ContentResolver contentResolver)
{
String oldDefaultKeyboard = Secure.getString(contentResolver, "default_input_method");
Secure.putString(contentResolver, "enabled_input_methods", keyboardID);
Secure.putString(contentResolver, "default_input_method", keyboardID);
}
in keyboardID you need to pass the keyboardID of the keyboard you want to set.
or you may get the list of all keyboards and get the ID from there and pass it
Like this:
List<InputMethodInfo> InputMethods = ((InputMethodManager) getApplicationContext().getSystemService("input_method")).getInputMethodList();
this.keyboard_name = new ArrayList();
int numOfKeEyboards = InputMethods.size();
for (int i = 0; i < numOfKeEyboards; i++)
{
fullKeyboardName = ((InputMethodInfo) InputMethods.get(i)).toString();
keyboard_package = fullKeyboardName.substring(fullKeyboardName.indexOf("{") + 1, fullKeyboardName.indexOf("/"));
try
{
// by package name getting app name
inputKeyboardName = getPackageManager().getApplicationInfo(keyboard_package, 0).loadLabel(getPackageManager()).toString();
}
catch (NameNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
this.keyboard_name.add(inputKeyboardName);
}
I am kind of learning android...and I would like to know if there is a way to access 3 letter words or 4 letter words or some specif type of words at random from the android User Dictionary class??Considering the fact that android has an auto correct feature I'm guessing it also has a dictionary in it...thus how do I use that...where can I find a proper tutorial?
i have no idea about the code...searched around a lot...please help me with the code and also the explanation possibly :)
I don't know how to access the android dictionary but you can have a "custom" dictionary as a txt file in the app's assets folder. This link has several word lists from around 20,000 words to 200,000 words. You could find more lists with google.
Afterwards, you can read the txt file and add it to an Array List if it matches the word length. A random word can then be selected from the dictionary list. The following code will create the dictionary and select a random word from it.
private ArrayList<String> dictionary;
private int wordLength; //Set elsewhere
private void createDictionary(){
dictionary = new ArrayList<String>();
BufferedReader dict = null; //Holds the dictionary file
AssetManager am = this.getAssets();
try {
//dictionary.txt should be in the assets folder.
dict = new BufferedReader(new InputStreamReader(am.open("dictionary.txt")));
String word;
while((word = dict.readLine()) != null){
if(word.length() == wordLength){
dictionary.add(word);
}
}
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
dict.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Precondition: the dictionary has been created.
private String getRandomWord(){
return dictionaryList.get((int)(Math.random() * dictionaryList.size()));
}
I am new to android,In my application i have to parse the data and i need to display in screen.But in one particular tag data i can't able to parse why because some special character also coming inside that tag.Here below i display my code.
My parser function:
protected ArrayList<String> doInBackground(Context... params)
{
// context = params[0];
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
test = new ArrayList<String>();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new java.net.URL("input URL_confidential").openConnection().getInputStream());
//Document document = builder.parse(new URL("http://www.gamestar.de/rss/gamestar.rss").openConnection().getInputStream());
Element root = document.getDocumentElement();
NodeList docItems = root.getElementsByTagName("item");
Node nodeItem;
for(int i = 0;i<docItems.getLength();i++)
{
nodeItem = docItems.item(i);
if(nodeItem.getNodeType() == Node.ELEMENT_NODE)
{
NodeList element = nodeItem.getChildNodes();
Element entry = (Element) docItems.item(i);
name=(element.item(0).getFirstChild().getNodeValue());
// System.out.println("description = "+element.item(2).getFirstChild().getNodeValue().replaceAll("<div><p>"," "));
System.out.println("Description"+Jsoup.clean(org.apache.commons.lang3.StringEscapeUtils.unescapeHtml4(element.item(2).getFirstChild().getNodeValue()), new Whitelist()));
items.add(name);
}
}
}
catch (ParserConfigurationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SAXException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return items;
}
Input:
<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
<channel>
<title>my application</title>
<link>http:// some link</link>
<atom:link href="http:// XXXXXXXX" rel="self"></atom:link>
<language>en-us</language>
<lastBuildDate>Thu, 20 Dec 2012</lastBuildDate>
<item>
<title>lllegal settlements</title>
<link>http://XXXXXXXXXXXXXXXX</link>
<description> <div><p>
India was joined by all members of the 15-nation UN Security Council except the US to condemn Israel’s announcement of new construction activity in Palestinian territories and demand immediate dismantling of the “illegal†settlements.
</p>
<p>
UN Secretary General Ban Ki-moon also expressed his deep concern by the heightened settlement activity in West Bank, saying the move by Israel “gravely threatens efforts to establish a viable Palestinian state.â€
</p>
<p>
</description>
</item>
</channel>
Output:
lllegal settlements ----> title tag text
India was joined by all members of the 15-nation UN Security Council except the US to condemn Israel announcement of new construction activity in Palestinian territories and demand immediate dismantling of the illegal settlements. -----> description tag text
UN Secretary General Ban Ki-moon also expressed his deep concern by the heightened settlement activity in West Bank, saying the move by Israel gravely threatens efforts to establish a viable Palestinian state. ----> description tag text.
Your text node contains both escaped HTML entities (> is >, greater then) and garbage characters (“grosslyâ€). You should first adjust the encoding according to your input source, then you can unescape the HTML with Apache Commons Lang StringUtils.escapeHtml4(String).
This method (hopefully) returns an XML which you can query (for example with XPath) to extract the wanted text node, or you can give the whole string to JSOUP or to the Android Html class
// JSOUP, "html" is the unescaped string. Returns a string
Jsoup.parse(html).text();
// Android
android.text.Html.fromHtml(instruction).toString()
Test program (JSOUP and Commons-Lang required)
package stackoverflow;
import org.apache.commons.lang3.StringEscapeUtils;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;
public class EmbeddedHTML {
public static void main(String[] args) {
String src = "<description> <div><p> An independent" +
" inquiry into the September 11 attack on the US Consulate" +
" in Benghazi that killed the US ambassador to Libya and" +
" three other Americans has found that systematic failures" +
" at the State Department led to “grossly†inadequate" +
" security at the mission. </p></description>";
String unescaped = StringEscapeUtils.unescapeHtml4(src);
System.out.println(Jsoup.clean(unescaped, new Whitelist()));
}
}
Is there anything wrong with simply replacing the offending characters?
string = string.replaceAll("<", "");
string = string.replaceAll("div>", "");
string = string.replaceAll("p>", "");
Run the node value with Html.fromHTML() two or three times and it wil be fine.
EXPLANATION: The built-in Html.fromHTML() method will convert wild and broken HTML into usable content. Pseudo code here:
sHTML = node.getNodeValue()
sHTML = Html.fromHTML(sHTML)
sHTML = Html.fromHTML(sHTML)
sHTML = Html.fromHTML(sHTML)
By the the third or fourth time unreadable content will become readable again. You can display it in a textview or loaddata with a webview.
i am a new Android developer, I have a UTF-16LE encoded string. I would like to print that string in Textview of my activity. However, the string in Hindi Language. and when i get Sysout for the string it shows write format and words(Eg: 05-07 12:31:53.050: I/System.out(22887): str = बसंत पंचमी, str = मकर संक्रान्ति / पोंगल). but in the TextView of device it shows only BOXES.
here is the code:-
String myString = मकर संक्रान्ति / बसंत पंचमी;
String correct = null;
try {
byte[] utf16le = myString .getBytes("UTF-16");
correct = new String(utf16le, "UTF-16");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("str = "+correct);
Any help is appreciated.
Thanks
Hey,
I have Arabic text in a txt file that I would like to show in a simple EditText,
Though when I do that here is what I get:
http://i55.tinypic.com/66g09z.png
Here is the code I use to get the text from the .txt file:
txt1 =(EditText) findViewById(R.id.EditText01);
try{
File f = new File(Environment.getExternalStorageDirectory()+"/1.txt");
FileInputStream fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
String readString = new String();
//just reading each line
while((readString = buf.readLine())!= null){
txt1.setText(txt1.getText().toString()+readString);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
How can I get proper Arabic letters into the EditText?
Thanks
You need to make sure that a font with Arabic characters is installed, and set the font of the EditText to it. The former is the annoying part. (I think I made SwiftKey do it for me by telling it to download the appropriate language modules.)
What version of android do you run? Android has no support for Arabic locales up until 2.3 version. You can find more info about locales supported on corresponding SDK pages. For example, list of SDK 2.3 supported locales is here.