How to implement speech to text in my app - java

I am building an app that utilities speech to text, in my code everything seems fine till it gets to protected void onActivityResult method to handle the results, it generates an error saying onActivityResult is a variable and then if I delete the access modifier, it sees it as a method then it generates another error in the parameters saying identifier expected and token is missing
Any help would be greatly appreciated.
My code
private static final int SPEECH_REQUEST_CODE = 100;
// Create an intent that can start the Speech Recognizer activity
private void displaySpeechRecognizer() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
// Start the activity, the intent will be populated with the speech text
startActivityForResult(intent, SPEECH_REQUEST_CODE);
}
// This callback is invoked when the Speech Recognizer returns.
// This is where you process the intent and extract the speech text from the intent.
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SPEECH_REQUEST_CODE && resultCode == RESULT_OK) {
List<String> results = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
Output.setText(results.get(0));
}
}

DO it like this:
private void displaySpeechRecognizer() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
And in onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtSpeechInput.setText(result.get(0));
}
break;
}
}
}
And in onCreate:
//Button you craete to start speech recognition
Button btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
// hide the action bar
//getActionBar().hide();
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displaySpeechRecognizer();
}
});

Related

How do I pass ArrayLists to another activity, modify it, and return it back to use?

I'm trying to create a login/register part of a project, and I'm having trouble with passing the sign-up information back to the login activity. I initialized username_info, password_info, and name_info in MainActivity, and I want to send it to SignUpActivity through Intent.
Intent i = new Intent(this, SignUpActivity.class);
i.putExtra("username_info", username_info);
i.putExtra("password_info", password_info);
i.putExtra("name_info", name_info);
startActivityForResult(i, 101);
After values are added in the other activity, it's sent back like this (the arraylists have the same name in both activities):
Intent r = new Intent();
r.putExtra("username_info", username_info);
r.putExtra("password_info", password_info);
r.putExtra("name_info", name_info);
setResult(Activity.RESULT_OK, r);
finish();
}
and it's received here:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 101) {
if (resultCode == Activity.RESULT_OK) {
Bundle e = getIntent().getExtras();
username_info = e.getStringArrayList("username_info");
password_info = e.getStringArrayList("password_info");
name_info = e.getStringArrayList("name_info");
}
}
}
But the array lists are unchanged when I get back to the MainActivity. I'm new to Android Studio, so I might just be making a simple mistake.
EDIT:
I'm crashing when the username and password don't match, but it should be returning a toast instead:
#Override
public void onClick(View v) {
username = username_input.getText().toString();
password = password_input.getText().toString();
int index = username_info.indexOf(username);
if (username_info.size() < 1) {
Toast.makeText(MainActivity.this, "You must sign up first", Toast.LENGTH_SHORT).show();
}
else if (password_info.get(index).equals(password)) {
Toast.makeText(MainActivity.this, "make an activity", Toast.LENGTH_SHORT).show();
// open activity
}
else {
Toast.makeText(MainActivity.this, "Incorrect username/password", Toast.LENGTH_SHORT).show();
}
}
});
Don't use getIntent() in onActivityResult, instead use the Intent data:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 101) {
if (resultCode == Activity.RESULT_OK) {
Bundle e = data.getExtras();
username_info = e.getStringArrayList("username_info");
password_info = e.getStringArrayList("password_info");
name_info = e.getStringArrayList("name_info");
}
}
}

How to check from which onResume the user is coming

I have a problem. The following Picture visualises my issue. We start in App 1 and press the button. Now we either get to see the screen of app2 or the setting screen. Now when i press the back button (marked as the red circle in app2 and settings) and we get back to the app1 screen. But what i wanna know is from what screen we get back to the app1 screen.
#Override
protected void onResume() {
super.onResume();
// if(from setting) {
// do this
}
NfcManager manager = (NfcManager) this.getSystemService(Context.NFC_SERVICE);
NfcAdapter adapter = manager.getDefaultAdapter();
if (adapter != null && adapter.isEnabled()) {
Intent userHomeScreen = new Intent(getApplicationContext(), UserHomeActivity.class);
startActivity(userHomeScreen);
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nfc_setting);
NfcManager manager = (NfcManager) this.getSystemService(Context.NFC_SERVICE);
NfcAdapter adapter = manager.getDefaultAdapter();
if (adapter != null && adapter.isEnabled()) {
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
if (currentUser != null){
Intent userHomeScreen = new Intent(getApplicationContext(), UserHomeActivity.class);
startActivity(userHomeScreen);
}else{
Intent loginScreen = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(loginScreen);
}
}
else {
btn_nfc_navigate_setting = findViewById(R.id.btn_nfc_navigate_setting);
btn_nfc_navigate_setting.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
}
});
}
Look now that I understand whats going on, you have to startActivityForResult() not startActivity():
Now in the activity that you use to open other activities:
When you open Log in screen:
Intent loginScreen = new Intent(getApplicationContext(), LoginActivity.class);
int requestCode = 10;
startActivityForResult(loginScreen , requestCode);
When you open settings
btn_nfc_navigate_setting.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int requestCode = 11;
startActivityForResult(new Intent(Settings.ACTION_NFC_SETTINGS) , requestCode);
}
});
Override this method to listen to from where you came instead of onResume()
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//this is triggered when you come back to this activity
if(requestCode == 10){
//we came from login
}else if(requestCode == 11){
//we came from settings
}
}
Use startActivityForResult()
From App1 to App2 or Setting:
int FLAG_APP2 = 1
Intent i = new Intent(this, App2.class);
startActivityForResult(i, FLAG_APP2);
Then in App2 button back tapped:
finish();
Then in App1 override onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FLAG_APP2) {
//here you know this is from App2 Screen
}
}
If you want to know the result of an Intent (in this case settings or app2), you can use
startActivityForResult(intent, requestCode)
instead of
startActivity(intent).
Where request code should be unique for different intents (in this case settings and app2).
To handle the result you have to override the onActivityResult() in the actvity.
So your required code will be
#Override
protected void onResume() {
super.onResume();
// if(from setting) {
// do this
// }
NfcManager manager = (NfcManager) this.getSystemService(Context.NFC_SERVICE);
NfcAdapter adapter = manager.getDefaultAdapter();
if (adapter != null && adapter.isEnabled()) {
Intent userHomeScreen = new Intent(getApplicationContext(), UserHomeActivity.class);
startActivityForResult(userHomeScreen,1);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
// Activity returned from userHomeScreen
}
else if (requestCode ==2) {
// Activity returned from Settings
}
}
UPDATE:
To add to that above if you want to access any Settings FEATURE you can use SETTINGS Constants as intent parameters.
Settings Documentation
For example, if you want to access NFC settings:
// Look into the constants in the documentation to know which constants to use in intent
Intent intent = new Intent(Settings.ACTION_NFC_SETTINGS);
startActivityForResult(intent, 2);

Integrate git project on an existing project startActivityForResult and onActivityResult android

I implemented this git on my current project without cloning
implementation 'com.github.adityaarora1:LiveEdgeDetection:master-SNAPSHOT'
But I'm unable to call it on my method. The document says
Start startActivityForResult from your activity
startActivityForResult(new Intent(this, ScanActivity.class), REQUEST_CODE);
Get a file path for cropped image on onActivityResult
String filePath = data.getExtras().getString(ScanConstants.SCANNED_RESULT);
Bitmap baseBitmap = ScanUtils.decodeBitmapFromFile(filePath, ScanConstants.IMAGE_NAME);
So I tried calling like this onClick button from a new Class
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this,
ScanActivity.class);
startActivity(myIntent);
}
and put the rest inside my onActivityResult
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String filePath = data.getExtras().getString(ScanConstants.SCANNED_RESULT);
Bitmap baseBitmap = ScanUtils.decodeBitmapFromFile(filePath, ScanConstants.IMAGE_NAME);
}
Edit: here is the MainActivity the author used on git I tried using it I get this error:
scannedImageView = findViewById(com.adityaarora.liveedgedetection.R.id.scanned_image);
MainActivity (imported)
private static final int REQUEST_CODE = 101;
private ImageView scannedImageView;
Button scan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
scannedImageView = findViewById(com.adityaarora.liveedgedetection.R.id.scanned_image);
startScan();
scan = findViewById(R.id.open_scan);
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(ScanActivity2.this,
ScanActivity.class);
startActivityForResult(myIntent ,111);
}
});
}
private void startScan() {
Intent intent = new Intent(this, ScanActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE) {
if(resultCode == Activity.RESULT_OK) {
if(null != data && null != data.getExtras()) {
String filePath = data.getExtras().getString(ScanConstants.SCANNED_RESULT);
Bitmap baseBitmap = ScanUtils.decodeBitmapFromFile(filePath, ScanConstants.IMAGE_NAME);
scannedImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
scannedImageView.setImageBitmap(baseBitmap);
}
} else if(resultCode == Activity.RESULT_CANCELED) {
finish();
}
}
}
Update :
After some research I found that the imported project was on read file only and cannot be changed (ScanActivity.java) and my current project was updated sdk 28 which is different from the one Imported so there is some errors in ScanActivity which Is why the button (technically) wasn't working
You should use startActivityForResult instead of startActivity like below.
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this,
ScanActivity.class);
startActivityForResult(myIntent ,111);
}
});
and modify your onActivityResult like
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK && requestCode == 111){
String filePath = data.getExtras().getString(ScanConstants.SCANNED_RESULT);
Bitmap baseBitmap = ScanUtils.decodeBitmapFromFile(filePath, ScanConstants.IMAGE_NAME);
Log.d("YourTAG","File Path "+filePath);
// here you can set bitmap to your image view
yourImageView.setImageBitmap(baseBitmap);
}
}
UPDATE
You Main Activity should be like
private static final int REQUEST_CODE = 111;
private ImageView scannedImageView;
Button scan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
scannedImageView = findViewById(R.id.scanned_image); // this ImageView should be in your activity_scan.xml file with same id(scanned_image)
startScan();
scan = findViewById(R.id.open_scan);
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startScan();
}
});
}
private void startScan() {
Intent intent = new Intent(ScanActivity2.this, ScanActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE) {
if(resultCode == Activity.RESULT_OK) {
if(null != data && null != data.getExtras()) {
String filePath = data.getExtras().getString(ScanConstants.SCANNED_RESULT);
Bitmap baseBitmap = ScanUtils.decodeBitmapFromFile(filePath, ScanConstants.IMAGE_NAME);
scannedImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
scannedImageView.setImageBitmap(baseBitmap);
}
} else if(resultCode == Activity.RESULT_CANCELED) {
finish();
}
}
}
Demo project
I have uploaded a demo project on Github which is integrated LiveEdgeDetection library and working as expected.
To check it go here

How to use in-built voice recognition in my Android app?

I want to use offline voice recognition in my app.
Setting -> “Language and Input” -> "Google Voice Typing" -> "Offline speech recognition" :- I would like to use this built-in feature.
In the below code, I tried to implement it using Recognizer Intent, but it uses the Google voice search (works online). Please help.
public class MainActivity extends AppCompatActivity {
private TextView txtSpeechInput;
private ImageButton btnSpeak;
private final int REQ_CODE_SPEECH_INPUT = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
promptSpeechInput();
//onCreateOptionsMenu();
}
private void promptSpeechInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
//txtSpeechInput.setText(result.get(0));
{
String a="camera";
if(a.compareTo(result.get(0))==0){
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (i.resolveActivity(getPackageManager()) != null) {
startActivityForResult(i, 1);
}
}
}
}
break;
}
}
}
Well, here I am sending intent to camera via voice. So, I have a limited vocabulary requirement here.
Try this:
intent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE,true);
Note: This will work only on API level 23 and above.

I cannot use the result from Zxing to do my activity

I am new to Android, i want to use the data from QR code to set my textview.
and i want to test the data's result as well.
the QR code format is just plain Text.
the problem is after I scanned my text wasn't change.
please help me check the code
btnSendJob.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.setPackage("com.google.zxing.client.android");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
//result from Zxing
#SuppressWarnings("unused")
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
// Handle successful scan
TextView text1 = (TextView) findViewById(R.id.resultQR);
TextView text2 = (TextView) findViewById(R.id.textToSelectGroup);
text1.setText(contents.toString());
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
btnSendJob.setText("failed");
}
}
}
});
I think something like this works:
import zxing.IntentIntegrator;
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
String barcode = result.getContents();
//yadda, yadda..
}
}

Categories