I want to ask how I can use speech to text code on my emulator. My codes work on real device but not work on emulator. The error said :
No Activity found to handle Intent { act=android.speech.action.RECOGNIZE_SPEECH (has extras) }
What can I do?
package net.viralpatel.android.speechtotextdemo;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
protected static final int RESULT_SPEECH = 1;
private ImageButton btnSpeak;
private TextView txtText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtText = (TextView) findViewById(R.id.txtText);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, RESULT_SPEECH);
txtText.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"Ops! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtText.setText(text.get(0));
}
break;
}
}
}
}
You need to install onto your emulator an app that contains an Activity that handles the RECOGNIZE_SPEECH-intent. You might be able to find Google's VoiceSearch.apk on the web.
There are certain things you can't test using an emulator. Speech to text is on of them.
I'm not sure about this, but you can't use this android feature with the emulator.
No matter what, you should handle this exception with a try/ catch an give some feedback to the user.
You can check if there is that Activity in current device running your app doing something like:
PackageManager pm = context.getPackageManager();
List<ResolveInfo> infoList = pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (infoList.size() == 0) {
/** Show some feedback to user if there is the activity. Something like "Your device is not abl to run this feature..."*/
}else{
/**Your current code goes here.*/
}
Let me know if it helps.
You need to install com.google.android.voicesearch application on target device which has no voice recognition activity like:
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.voicesearch"));
startActivity(browserIntent);
if you try to install Google's Search app - it won't help since it doesn't contain the VR engine inside and thus it will try to do the same - install com.google.android.voicesearch app but it could fail due to a bug in package name (pname:com.google.android.voicesearch instead of just pure package name). However com.google.android.voicesearch installation might be impossible due to "Not available in your country".
You might need a virtual SD Card. You can refer here
Related
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 1 year ago.
I am new to android dev
I have made as simple app in android (for api_version greater than 23) which fetches the name of all running apps. But the app doesn't work properly. When I click the button the functionality registered in "onClickListner" is not working.
package com.sakthi.appban;
import androidx.appcompat.app.AppCompatActivity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
displayAllApps();
}
});
}
private void displayAllApps(){
PackageManager pm = getPackageManager();
List<ApplicationInfo> installedApplications = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for(ApplicationInfo application : installedApplications){
Toast.makeText(this, application.name, Toast.LENGTH_SHORT).show();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Toast.makeText(this, "Task Ended", Toast.LENGTH_SHORT).show();
}
Hope I will get help
Thanks in advance
I think you might have seen these message in logs if you run this code you will get this error when you click on the button
Error:
java.lang.IllegalStateException: You must either set a text or a view
Here application.name may get null for some of the apps. This may cause IllegalStateException because you are passing null to a Toast.
To fix this simply add an if condition to null check like this:
if(application.name != null) {
Toast.makeText(this, application.name, Toast.LENGTH_SHORT).show();
}
Then it should work.
Update:
You can remove this code from your code which causing ANR:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
The problem is that I am trying to loop in the UI thread.
So the UI thread cannot handle the UI operation..
and my program crashed.More info here
I tried my best to find the solution before asking, however, I can't seem to locate a similar situation.
I've implemented a QR scanner for an app I am working on. I'm using the zxing library, specifically using the imports below. Also, the apps uses "Barcode Scanner" from play store (I was prompted to install).
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
The issue is that the scanner only works 1 out every 3-6 scans. I either get a null return, or no output. It always returns back to my source screen, and never produces an actual error.
I used this tutorial as a source: Android SDK: Create a Barcode Reader
Here is the relevant info from mainactivity:
public void onClick(View v){
//respond to clicks
if(v.getId()==R.id.scanQRButton){
//scan
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
formatTxt.setText( "Scan Initiated");
contentTxt.setText(" Scan Results: " + scanContent);
if(scanContent != null){
String userid,medname,tabstaken,dob;
StringTokenizer st = new StringTokenizer(scanContent, ",");
// token 0
dob = st.nextToken();
//token 1
medname = st.nextToken();
//token 2
tabstaken = st.nextToken();
//token 3
//rxnumber
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap<String,String> user = new HashMap<String, String>();
user = db.getUserDetails();
//Store the userlog by passing to UserLogEntry
userid = user.get("uid");
//debug.setText("Userid: "+ userid+ " medname: " + medname + " tabs: " +tabstaken);
UserLogEntry userlog = new UserLogEntry(getApplicationContext(),userid,medname,tabstaken);
userlog.addUserLog();
}
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
scanContent = scanningResult.getContents();
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
And here are the ZXing classes from the library package I'm using:
IntentResults:
https://code.google.com/p/zxing/source/browse/trunk/android-integration/src/com/google/zxing/integration/android/IntentResult.java?r=1273
IntentIntegrator:
https://code.google.com/p/zxing/source/browse/trunk/android-integration/src/com/google/zxing/integration/android/IntentIntegrator.java?spec=svn2260&r=2260
Any ideas on how to get this to work %100 of the time?
Thanks!
So I tried several different ways to get the scanner to work with zxing, and nothing would work. It just felt buggy no matter what I did. That on top of the fact that integrating the scanner so it doesn't need a third party app (as in Barcode scanner) was a major pain. I decided to look for an alternative and found ZBar.
If anyone has any problems using zxing for QR scanning I'd recommend using Zbar instead. The code itself is much simpler. You can use the example given on the zbar page and pretty much copy and paste it into your project without changes(or very little). Also, integrating it as an all inclusive scanner is simple as can be.
I'm including the instructions here for a more inclusive answer. This information is available in tutorials, and at the ZBar page, however, it doesn't hurt to include them here in my answer.
First download the zip here: https://github.com/dm77/ZBarScanner
Then add "ZBarScannerLibrary" as an existing android project.
For ZBarScannerLibrary: Right click->properties->android and check "Is Library"
Select your project (the one you're adding qr scanner to), right click->properties->android->Add select ZBarScannerLibrary.
Now add the ZBar code given on the page: https://github.com/dm77/ZBarScanner (shown below to be helpful.
Enjoy qr scanning without pulling out your hair
Here is the main activity for the sample provided with ZBar. Don't forget to add the appropriate lines to android manifest:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" />
Within the application element, add the activity declaration:
<activity android:name="com.dm.zbar.android.scanner.ZBarScannerActivity"
android:screenOrientation="landscape"
android:label="#string/app_name" />
I used a String Tokenizer to pull apart the QR results and sort them into specific variables.
package com.dm.zbar.android.examples;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;
import com.dm.zbar.android.scanner.ZBarConstants;
import com.dm.zbar.android.scanner.ZBarScannerActivity;
import net.sourceforge.zbar.Symbol;
public class MainActivity extends Activity {
private static final int ZBAR_SCANNER_REQUEST = 0;
private static final int ZBAR_QR_SCANNER_REQUEST = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void launchScanner(View v) {
if (isCameraAvailable()) {
Intent intent = new Intent(this, ZBarScannerActivity.class);
startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
} else {
Toast.makeText(this, "Rear Facing Camera Unavailable", Toast.LENGTH_SHORT).show();
}
}
public void launchQRScanner(View v) {
if (isCameraAvailable()) {
Intent intent = new Intent(this, ZBarScannerActivity.class);
intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{Symbol.QRCODE});
startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
} else {
Toast.makeText(this, "Rear Facing Camera Unavailable", Toast.LENGTH_SHORT).show();
}
}
public boolean isCameraAvailable() {
PackageManager pm = getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ZBAR_SCANNER_REQUEST:
case ZBAR_QR_SCANNER_REQUEST:
if (resultCode == RESULT_OK) {
Toast.makeText(this, "Scan Result = " + data.getStringExtra(ZBarConstants.SCAN_RESULT), Toast.LENGTH_SHORT).show();
} else if(resultCode == RESULT_CANCELED && data != null) {
String error = data.getStringExtra(ZBarConstants.ERROR_INFO);
if(!TextUtils.isEmpty(error)) {
Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
}
}
break;
}
}
}
I have developed a application connect with wi-fi. In that app portrait/landscape transition restart the activity when rotate the phone and interrupt the socket connection. Then I add portrait to AndroidManifest.xml file then problem have been solved. I want to know that is portrait/landscape transition effect to Async-Task also?
<activity
android:name="login"
android:label="#string/login_title"
android:configChanges="orientation|screenSize" >
</activity>
Login.java file
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class login extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
try{
Button buttonSignin = (Button) this.findViewById(R.id.btnSignIn);
//This is the place gives nullpointerException
buttonSignin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText user=(EditText) findViewById(R.id.txtUserName);
EditText pass=(EditText) findViewById(R.id.txtPassword);
if(user.getText().toString()== "")
{
return;
}
else if(pass.getText().toString()== "")
{
return;
}
else
{
LoginRequest reqs_login = new LoginRequest(login.this,login.this);
reqs_login.where="Login_Data";
reqs_login.title="Login";
reqs_login.username=user.getText().toString();
reqs_login.password=pass.getText().toString();
reqs_login.execute();
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
//Toast.makeText(getBaseContext(), "Error:1 on uplod file", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
//Toast.makeText(getBaseContext(), "Error:2 File may be already exists", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
Use this in your AndroidManifest.xml activity,
android:configChanges="orientation|screenSize"
working for me in AsyncTask also
I guess the Answer would be NO because the Async task (Background task) once started executing inBackground it will not stop until complete execution of that code in background. No matter App is in whichever State , Even the App is minimized it does not affect the Async Task. So Changing Landscape / Portrait mode will not affect the AsyncTAsk (InBackground) method. hope this will help...
What is the best way to retain active objects—such as running Threads, Sockets, and AsyncTasks—across device configuration changes?
Deprecated: Override onRetainNonConfigurationInstance()
transferring an active object across Activity instances was merely a matter of returning the active object in onRetainNonConfigurationInstance() and retrieving it in getLastNonConfigurationInstance(). As of API 13, these methods have been deprecated in favor of the more Fragment's setRetainInstance(true/false)
Recommended: Manage the Object Inside a Retained Fragment
Fragment#setRetainInstance(true) allows us to bypass this destroy-and-recreate cycle
For more details please go through the below
Handling Configuration Changes
Hope this will help you.
Im trying to do this tutorial
But keep getting this error:
08-21 14:12:49.599: E/AndroidRuntime(714):
java.lang.NoClassDefFoundError:
com.akiraapps.LicenseCheck$MyLicenseCheckerCallback
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings.Secure;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.vending.licensing.AESObfuscator;
import com.google.android.vending.licensing.LicenseChecker;
import com.google.android.vending.licensing.LicenseCheckerCallback;
import com.google.android.vending.licensing.Policy;
import com.google.android.vending.licensing.ServerManagedPolicy;
public class LicenseCheck extends Activity {
private static final String BASE64_PUBLIC_KEY = "no";
private static final byte[] SALT = new byte[] { no};
private TextView mStatusText;
private Button mCheckLicenseButton;
private LicenseCheckerCallback mLicenseCheckerCallback;
private LicenseChecker mChecker;
// A handler on the UI thread.
private Handler mHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.main);
mStatusText = (TextView) findViewById(R.id.status_text);
mCheckLicenseButton = (Button) findViewById(R.id.check_license_button);
mCheckLicenseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
doCheck();
}
});
mHandler = new Handler();
// Try to use more data here. ANDROID_ID is a single point of attack.
String deviceId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
// Library calls this when it's done.
mLicenseCheckerCallback = new MyLicenseCheckerCallback();
// Construct the LicenseChecker with a policy.
mChecker = new LicenseChecker(
this, new ServerManagedPolicy(this,
new AESObfuscator(SALT, getPackageName(), deviceId)),
BASE64_PUBLIC_KEY);
doCheck();
}
protected Dialog onCreateDialog(int id) {
final boolean bRetry = id == 1;
return new AlertDialog.Builder(this)
.setTitle(R.string.unlicensed_dialog_title)
.setMessage(bRetry ? R.string.unlicensed_dialog_retry_body : R.string.unlicensed_dialog_body)
.setPositiveButton(bRetry ? R.string.retry_button : R.string.buy_button, new DialogInterface.OnClickListener() {
boolean mRetry = bRetry;
public void onClick(DialogInterface dialog, int which) {
if ( mRetry ) {
doCheck();
} else {
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(
"http://market.android.com/details?id=" + getPackageName()));
startActivity(marketIntent);
}
}
})
.setNegativeButton(R.string.quit_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).create();
}
private void doCheck() {
mCheckLicenseButton.setEnabled(false);
setProgressBarIndeterminateVisibility(true);
mStatusText.setText(R.string.checking_license);
mChecker.checkAccess(mLicenseCheckerCallback);
}
private void displayResult(final String result) {
mHandler.post(new Runnable() {
public void run() {
mStatusText.setText(result);
setProgressBarIndeterminateVisibility(false);
mCheckLicenseButton.setEnabled(true);
}
});
}
private void displayDialog(final boolean showRetry) {
mHandler.post(new Runnable() {
public void run() {
setProgressBarIndeterminateVisibility(false);
showDialog(showRetry ? 1 : 0);
mCheckLicenseButton.setEnabled(true);
}
});
}
private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
public void allow(int policyReason) {
System.out.println("Allow");
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
// Should allow user access.
displayResult(getString(R.string.allow));
}
public void dontAllow(int policyReason) {
System.out.println("dontAllow");
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
displayResult(getString(R.string.dont_allow));
// Should not allow access. In most cases, the app should assume
// the user has access unless it encounters this. If it does,
// the app should inform the user of their unlicensed ways
// and then either shut down the app or limit the user to a
// restricted set of features.
// In this example, we show a dialog that takes the user to Market.
// If the reason for the lack of license is that the service is
// unavailable or there is another problem, we display a
// retry button on the dialog and a different message.
displayDialog(policyReason == Policy.RETRY);
}
public void applicationError(int errorCode) {
System.out.println("applicationError");
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
// This is a polite way of saying the developer made a mistake
// while setting up or calling the license checker library.
// Please examine the error code and fix the error.
String result = String.format(getString(R.string.application_error), errorCode);
displayResult(result);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mChecker.onDestroy();
}
}
I follow the tutorial for setting up LVL as a library project and those imports seem to be ok.
Why do I get this error? Why can it not find the inner class? If I right click and say show definition it jumps to the inner class.
I had same problem.
Below steps solved the probelm
take standard library example
coppied the library.jar file from the library project into your libs folder
So this SO Answer is what fixed it
I created a folder called libs and coppied the library.jar file from the library project included in the licensing package downloaded with the manager
What I dont understand is per this answer this should have been done for me
As I am using ADT 20.0.3
Basically it comes down to an example that I downloaded directly from android and got stuck for a few hours trying to figure out what was wrong and this seems like this step should have been in the readme/help docs OR Im doing something wrong.
If you know why this is the answer and how to do it better please answer and Ill change the answer to yours.
I had the exact same exception and none of the above recommendations worked for me.
However I got mine working by ensuring that your LVL project is a library project (right click project -> properties -> android and tick the "Is Libary" checkbo).
To include this in your application project remove any other references to this and apply the changes. Then if not already there navigate to (right click application project --> properties --> android) and in the library section click Add and select your LVL project. Apply Changes. Ok and clean project.
Hope this helps someone.
i tried the following on the emulator but the as the app starts it gives a runtime error . could someone please help me on this . Heres' the code i tried
package com.example.TextSpeaker;
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
public class TextSpeaker extends Activity {
/** Called when the activity is first created. */
int MY_DATA_CHECK_CODE = 0;
private TextToSpeech mtts;
String test1="hello world";
String test2="hi i am working fine";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent myintent = new Intent();
myintent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(myintent, MY_DATA_CHECK_CODE);
}
protected void onActivityResult(int requestcode,int resultcode,Intent data)
{
if(requestcode == MY_DATA_CHECK_CODE)
{
if(resultcode==TextToSpeech.Engine.CHECK_VOICE_DATA_PASS)
{
// success so create the TTS engine
mtts = new TextToSpeech(this,(OnInitListener) this);
mtts.setLanguage(Locale.ENGLISH);
mtts.speak(test1, TextToSpeech.QUEUE_FLUSH, null);
mtts.speak(test2, TextToSpeech.QUEUE_FLUSH, null);
}
else
{
//install the Engine
Intent install = new Intent();
install.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(install);
}
}
}
}
I've stumbled upon this question well over a year after it was posted, but I'm going to go ahead and answer anyway, in the sheer hope it'll help anyone else who ends up here in the future.
I'm writing this against 2.1, so apologies if you were working with <2.1 (no tags on question)
There are a few things I can spot immediately that may give you a little grief.
Firstly, the following :
mtts.speak(test1, TextToSpeech.QUEUE_FLUSH, null);
mtts.speak(test2, TextToSpeech.QUEUE_FLUSH, null);
If I understand the TextToSpeech API correctly, using QUEUE_FLUSH will flush out anything thats currently being spoken, so its possible that the second line is executing before the first has actually spoken, and you'd experience what you've stated above, that only the last one is being spoken.
Ideally, you only want one of those lines there, if the user puts in a different String, then just pass that through and let it flush out.
Next, you should invest in an onDestroy override, in here you can shutdown the mtts object, this prevents your app from hogging usage to the TTS engine, its always nice to free up resources when you're done with them, you wouldn't leave a ResultSet open now would you?!
#Override
public void onDestroy
() {
// Don't forget to shutdown!
if (mTts != null) {
mTts.stop();
mTts.shutdown();
}
super.onDestroy();
}
Also, as you state, it'll only speak English, because of the line you're using :
mtts.setLanguage(Locale.ENGLISH);
That's easy to correct, just set a different locale. Perhaps have some buttons and set the locale accordingly. I believe that the Google TTS engine currently only supports English, French, German, Italian and Spanish, but 3rd party TTS engines may offer more.
If all else fails, I wrote a tutorial here that might be of use.
Good luck!