I want to convert a text in English to Hindi and display it in the TextView.I followed the following URL http://android-er.blogspot.com/2009/10/androidtranslate-using-google-translate.html but it dosen't seems to work.
Is there any other method to do it?Help me out.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.read_view);
mTts = new TextToSpeech(this,this);
try {
setTranslate();
} catch (Exception e) {
e.printStackTrace();
}
}
private void setTranslate() throws Exception {
String OutputString = Translate.execute("hello",
Language.ENGLISH, Language.HINDI);
TextView tv = (TextView) findViewById(R.id.translate);
tv.setText(OutputString);
}
Here I am trying to display hindi text in the TextView id "translate"
make sure your application does have internet permission
android.permission.INTERNET
add google translate api jar i.e google.api.translate-java-0.90.jar
Also check this client api it comes useful some times when u want to handle certain events and requests with ease
Microsoft Bing Translator offers a translator for this english-hindi and its completely free for a limited searches.
http://www.microsoft.com/web/post/using-the-free-bing-translation-apis.
Related
I am creating an android application wherein I have mentioned the phone number, email, website of the business similar to the screenshot of google maps as attached.
Just like in the g maps where
Single click makes an intent to the respective app (opens dialer with phone number copied) etc.
Long Click/Press & hold will copy the number to clipboard displaying a toast that "Phone number is copied to clicpboard".
Now I have set up the intents properly and they are working fine --> step-1 achieved.
When I try to display the toast using "OnLongClickListener" method it is taking quite some time to display the toast message. Is there any way we can speed this up or am I missing something or should I use some other alternative like onTouch() method?
(Stuck with this, yet to learn and try out copying to clipboard thing. Inputs in this regards are also welcome!)
In the g maps app, the toast message appears almost instantly on press & hold. So the same is to be achieved.
The code extract from MainActivity.java (The website, phone number, email id are text views with drawableLeft. And I found out that we cannot use setOnItemLongClick on TextView as it is only for ListView)
// This method is called when the website text view is clicked and opens the compnay website
public void openWebsite(View v) {
TextView textView = (TextView) findViewById(R.id.webURL_text_view);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent openWebsiteIntent = new Intent(Intent.ACTION_VIEW);
openWebsiteIntent.setData(Uri.parse("https://www.company.com"));
if (openWebsiteIntent.resolveActivity(getPackageManager()) != null) {
startActivity(openWebsiteIntent);
}
}
});
textView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
showMessage();
return true;
}
});
}
public void showMessage(){
Toast.makeText(this,"Information copied to Clipboard", Toast.LENGTH_LONG).show();
}
I am new to android development and just trying out something, so please be as elaborative as possible. Thank You.
I have a problem that I want to use jsoup to grab news but always fail.
this is news website.
https://www3.nhk.or.jp/news/
this is my picture . which I circle is I wanted data.
https://drive.google.com/open?id=1KJAyOSdHO8APPD6_A9MjxkoFjekcQLXt
but no matter what I do. it always get wrong data or empty.
this is my program.
public class News extends AppCompatActivity {
Button ok;
private static final String url ="https://www3.nhk.or.jp/news/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news);
ok=(Button)findViewById(R.id.ok);
ok.setOnClickListener(okbtn);
}
private Button.OnClickListener okbtn=new Button.OnClickListener(){
public void onClick(View v){
try{
Connection.Response response = Jsoup.connect(url).execute();
String body = response.body();
Document data = Jsoup.parse(body);//visible-phone print_hide
Elements country=data.select("main");
Elements main=data.select("div[id=module module--news-main index-main]");
for(Element e1: country)
{
mytoast(e1+"");
}
}
catch(Exception ex){ex.printStackTrace() ;}
}
};
private void mytoast(String str)
{
Toast toast=Toast.makeText(this, str, Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
please help me
thanks
You can try to see it's HTML first.
If you can't see it, you don't use jsoup.
There's a small hint in its comment:
このページではJavaScriptを使用しています
=>This is generated by JavaScript
If it's generated, you can't find it from Jsoup.
In this case, I'll use Chrome's tool to monitor the XHR tab
Look into each XHR request, and find the most possible one,
for example, I see this
https://www3.nhk.or.jp/news/json16/syuyo.json?_=1559183885640
A part of the response:
"id":"193411",
"title":"三菱UFJ銀行 新規口座は原則デジタル通帳に",
"pubDate":"Thu, 30 May 2019 04:03:11 +0900",
"cate":"5",
...
"id":"193437",
"title":"エアレース世界選手権 今季限りで終了",
"pubDate":"Thu, 30 May 2019 09:40:37 +0900",
So this is exactly what you want. It comes from another link!
You don't need Jsoup, just HttpGet the link
https://www3.nhk.or.jp/news/json16/syuyo.json?_=1559183885640
And I think the numbers looks like UnixTime,
So I check the current time is : 1559184830782, that's it.
Just use that link as API and time as parameter.
I have a website which only shows one line of text which I need to extract the text form in android studio, I would prefer to get it as a string. How do I do this?
Something such as webView.getTitle() would work but than for the content of the site, is there such a quick way to get this or how should I else do it?
specific info
the site I need to get the information form is:
"<html> <head></head> <body> #4d636f </body> </html> "
from this I only need the text in the body, in this case a color as text.
You can use any Web Scraper/Crawler API to fetch data from web site.
For example:
JSOUP API For Java And Android
Update
Step By Step guide to solve the mentioned problem
Add Jsoup dependency to the app level of your build.gradle.
implementation 'org.jsoup:jsoup:1.11.1'
Add Internet permission to the Android Manifest file for internet access.
<uses-permission android:name="android.permission.INTERNET" />
Add button and text view in your app to get data from website on button click and display the result on text view.
Below is the sample code:
public class MainActivity extends AppCompatActivity {
private TextView result;
private Button fetch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
fetch = (Button) findViewById(R.id.fetch);
fetch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getBodyText();
}
});
}
private void getBodyText() {
new Thread(new Runnable() {
#Override
public void run() {
final StringBuilder builder = new StringBuilder();
try {
String url="http://www.example.com";//your website url
Document doc = Jsoup.connect(url).get();
Element body = doc.body();
builder.append(body.text());
} catch (Exception e) {
builder.append("Error : ").append(e.getMessage()).append("\n");
}
runOnUiThread(new Runnable() {
#Override
public void run() {
result.setText(builder.toString());
}
});
}
}).start();
}
}
This type of process is known as web scrubbing. And you could do more research to see different methods. One methd I would suggest is getting the HTML from source and searching the DOM for any tags unique to the text you want.
By getting the HTML you avoid rendering the whole page (images, javascript, ect..)
Do you have a snippet of the source code you want to scrub from?
Sure here is an example. P.S. I'm not familiar with javascript, correct him for your case.
webView.evaluateJavascript("return document.getElementById(your_id)", new ValueCallback<String>() {
#Override
public void onReceiveValue(String value) {
// value is your result
}
});
Is there any way in Java to detect if an Android device has an offline speech recognition language installed, and if it does not prompt the user to download it?
I know you can ask to speech to text to prefer offline speech to text, but how do you know if the device has the language installed?
This question is not on how to use offline speech, this works.
The question is "how to detect and download/install offline speech languages" from Java app code. i.e. have the app detect if they have offline German language installed, and if not prompt the user to download/install it.
This is not the answer you are hoping for, as at the time of writing, I don't believe there is a straight forward solution to this. I very much hope to be proved wrong.
I requested an enhancement to provide this information programmatically a long time ago - here
The enhancement suggested an additional parameter RecognizerIntent.EXTRA_SUPPORTED_OFFLINE_LANGUAGES:
It would surely be trivial for this to be added and used in the following way:
final Intent vrIntent = new Intent(RecognizerIntent.ACTION_GET_LANGUAGE_DETAILS);
getContext().sendOrderedBroadcast(vrIntent, null, new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent intent) {
final ArrayList<String> vrStringLocales = intent.getExtras().getStringArrayList(
RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES);
// This would be nice
final ArrayList<String> vrStringOfflineLocales = intent.getExtras().getStringArrayList(
RecognizerIntent.EXTRA_SUPPORTED_OFFLINE_LANGUAGES);
}
}, null, 1234, null, null);
Alas, it has never happened.
You do have two other options to attempt to handle this gracefully.
In the unlikely event you application runs with root permissions, you can check the location of /data/data/com.google.android.googlequicksearchbox/app_g3_models/ which contains the offline files, labelled quite handily by their locale.
The second involves knowing when the user needs a prompt to install the missing offline files.
From my experience, the recognition error of SpeechRecognizer.ERROR_SERVER most often denotes this, but it is not foolproof.
#Override
public void onError(final int error) {
switch (error) {
case SpeechRecognizer.ERROR_SERVER:
// TODO - prompt to install offline files
break;
}
}
When detected, you can guide the user to the correct installation screen.
public static final String PACKAGE_NAME_GOOGLE_NOW = "com.google.android.googlequicksearchbox";
public static final String ACTIVITY_INSTALL_OFFLINE_FILES = "com.google.android.voicesearch.greco3.languagepack.InstallActivity";
public static boolean showInstallOfflineVoiceFiles(#NonNull final Context ctx) {
final Intent intent = new Intent();
intent.setComponent(new ComponentName(PACKAGE_NAME_GOOGLE_NOW, ACTIVITY_INSTALL_OFFLINE_FILES));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
ctx.startActivity(intent);
return true;
} catch (final ActivityNotFoundException e) {
} catch (final Exception e) {
}
return false;
}
Using hard-coded values such as this, is of course not ideal, but neither is this situation!
Once you've messed around with all of the above and think you have a good interim solution - think again! Regardless of whether the user has correctly installed the missing offline files, it is highly likely it still won't work.....
My answer here describes the process I still have to guide my user's with. It's very frustrating.
Finally one more bug to throw into the mix - RecognitionListener.onError(int) can be thrown when there isn't an error. Check my gist from the answer here to use a BugRecognitionListener so you can check the callbacks are being sent in the correct order and ignore those that aren't. This remains a problem, despite my answer suggesting a fix in a previous release.
The above should keep you busy! Good luck....
To detect whether needed Language(German) is available, please follow below :
Iterate the Locale list and check whether Locale available for German language.
If you didn't get any Locale object in return, you can conclude that German language is not available offline. Then you can write code to download and do other stuff.
I did below implementation for my project. Hope below code helps you !!!
private TextToSpeech t1;
private void setForOtherLangAudio() {
Locale[] locales = Locale.getAvailableLocales();
Locale loc = null;
for (Locale locale : locales) {
// Replace XXX with your German codes
if (locale.getDisplayCountry().equals("XXX") && locale.getDisplayLanguage().equals("XXX")) {
loc = locale ;
break;
}
}
final Locale germanLocale = loc;
t1 = new TextToSpeech(getContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
t1.setLanguage(germanLocale);
}
}
});
}
How can you read data, i.e. convert simple text strings to voice (speech) in Android?
Is there an API where I can do something like this:
TextToVoice speaker = new TextToVoice();
speaker.Speak("Hello World");
Using the TTS is a little bit more complicated than you expect, but it's easy to write a wrapper that gives you the API you desire.
There are a number of issues you must overcome to get it work nicely.
They are:
Always set the UtteranceId (or else
OnUtteranceCompleted will not be
called)
setting OnUtteranceCompleted
listener (only after the speech
system is properly initialized)
public class TextSpeakerDemo implements OnInitListener
{
private TextToSpeech tts;
private Activity activity;
private static HashMap DUMMY_PARAMS = new HashMap();
static
{
DUMMY_PARAMS.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "theUtId");
}
private ReentrantLock waitForInitLock = new ReentrantLock();
public TextSpeakerDemo(Activity parentActivity)
{
activity = parentActivity;
tts = new TextToSpeech(activity, this);
//don't do speak until initing
waitForInitLock.lock();
}
public void onInit(int version)
{ //unlock it so that speech will happen
waitForInitLock.unlock();
}
public void say(WhatToSay say)
{
say(say.toString());
}
public void say(String say)
{
tts.speak(say, TextToSpeech.QUEUE_FLUSH, null);
}
public void say(String say, OnUtteranceCompletedListener whenTextDone)
{
if (waitForInitLock.isLocked())
{
try
{
waitForInitLock.tryLock(180, TimeUnit.SECONDS);
}
catch (InterruptedException e)
{
Log.e("speaker", "interruped");
}
//unlock it here so that it is never locked again
waitForInitLock.unlock();
}
int result = tts.setOnUtteranceCompletedListener(whenTextDone);
if (result == TextToSpeech.ERROR)
{
Log.e("speaker", "failed to add utterance listener");
}
//note: here pass in the dummy params so onUtteranceCompleted gets called
tts.speak(say, TextToSpeech.QUEUE_FLUSH, DUMMY_PARAMS);
}
/**
* make sure to call this at the end
*/
public void done()
{
tts.shutdown();
}
}
Here you go . A tutorial on using the library The big downside is that it requires an SD card to store the voices.
A good working example of tts usage can be found in the "Pro Android 2 book". Have a look at their source code for chapter 15.
There are third-party text-to-speech engines. Rumor has it that Donut contains a text-to-speech engine, suggesting it will be available in future versions of Android. Beyond that, though, there is nothing built into Android for text-to-speech.
Donut has this: see the android.speech.tts package.