Speech to text app replaces old text with new - java

The app overwrites the old text with the new one but that's not the purpose. I want the new text to retain old text in addition to new, like turning old and new into strings and then combining them?
final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onResults(Bundle bundle) {
//getting all the matches
ArrayList<String> matches = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
//displaying the first match
if (matches != null)
resultText.setText(matches.get(0));
}
});

So you want to append the results to the TextView ?
That's easy:
resultText.append(matches.get(0));
With space:
resultText.append(" " + matches.get(0));
Another way:
resultText.setText(resultText.getText() + " " + matches.get(0));

Related

onPostExecute is called twice and showing double result

I am trying to download some files in background, for that I used download manager and I made this method:
/*** media download ***/
public long mediaDownload(ArrayList<DownloadedFile> arrayList, String foldPathName) {
long downloadReference = 0;
// Create request for android download manager
downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
for (int i = 0; i < arrayList.size();i++){
DownloadManager.Request request = new DownloadManager.Request(arrayList.get(i).getUri());
request.setTitle("Data Download");
request.setDescription("New media");
//Set the local destination for the downloaded file to a path
//within the application's external files directory
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS + "/" + folder_main + "/" + foldPathName, arrayList.get(i).getName());
File f = new File(Environment.DIRECTORY_DOWNLOADS + "/" + folder_main + "/" + foldPathName + "/" + arrayList.get(i).getName());
Log.e("File:",f.toString());
//Enqueue download and save into referenceId
downloadReference = downloadManager.enqueue(request);
}
return downloadReference;
}
I have a picture and a Video to download for test, and when checking downloaded file in Explorer I find 2 videos and 2 picture, debug that I found that onPostExecute method is called twice and I can't figure out why.
Here is my onPostExecute method:
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray region = null;
region = jsonObject.getJSONArray("regions");
Log.e("Regions:", String.valueOf(region.length()));
for (int i = 0; i < region.length(); i++) {
try {
JSONObject json_data = region.getJSONObject(i);
int height_view = Integer.parseInt(json_data.getString("height"));
int width_view = Integer.parseInt(json_data.getString("width"));
int left_view = Integer.parseInt(json_data.getString("left"));
int top_view = Integer.parseInt(json_data.getString("top"));
int right_view = Integer.parseInt(json_data.getString("right"));
int bottom_view = Integer.parseInt(json_data.getString("bottom"));
/**** Media in region ***/
JSONObject media = json_data.getJSONObject("media");
String type_media = media.getString("type");
url = media.getString("url");
name = media.getString("name");
uri = Uri.parse(url);
} catch (JSONException e) {
e.printStackTrace();
}
downloadedFiles.add(new DownloadedFile(name, uri));
}
Toast.makeText(MainActivity.this, "Layout Created with" + height + "x" + width, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("Downloaded Files:",downloadedFiles.toString());
mediaDownload(downloadedFiles, folderName); // region media's download
}
On my logcat I see that my arrayList has 2 elements, but displayed twice, which means files are downloaded twice so the onPostExecute method called 2 times, thanks for help.
I figured out after passing my time debugging all the code, when the activity is created it changes the screen orientation and so it creates a second instance, so my AsyncTask is called twice and thats why i thought onPosteExecute is called twice, thanks for everyone who tried to help.

How to pass an arrayList between two intent in Android

I am new in Android and I have a question regarding intent. I want to pass an String ArrayList between two activities by using intent. I have tried this:
`
ArrayList<String> playerName = new ArrayList<>();
Intent intent = new Intent(this,Game.class);
intent.putStringArrayListExtra("Player",playerName);
startActivity(intent);`
Then I tried to receive my intent like that:
`
ArrayList<String> playerNameList= new ArrayList<>();
playerNameList = getIntent().getStringArrayListExtra("Player");
int listSize = playerNameList.size();
StringBuilder str = new StringBuilder(" ");
str.append(listSize);
textView.setText(str);
StringBuilder str1 = new StringBuilder(" ");
str1.append(playerNameList.get(2));
textView2.setText(str1);`
I can get the correct listSize; however I am not able to get any element of my arrayList. I always get the "index(0)" element. I would be really appreciated to any advice and help
you can easily to by using Gson
Intent intent = new Intent(this,Game.class);
intent.putExtra("Player",new Gson().toJson(playerName));
startActivity(intent);
at Game.class
ArrayList<String> playerNameList = playerNameList = new ArrayList<>();
String str = getIntent().getStringExtra("Player");
playerNameList = new Gson().fromJson(str,new TypeToken<ArrayList< String >>(){}.getType());
Check your code to add data to ArrayList playerName. The code to putStringArrayListExtra to Intent and getStringArrayListExtra from Intent is correct.

Get only digits from input and call that number Android

Okay, I am creating an android app, I do like to get the number from an input here mostLikelyThingHeard unfortenately my code doesn't work for some reason.
For example when the user says: bel 0612345678
The dialer has to call 0612345678
String one = "bel";
if (mostLikelyThingHeard.contains(one)) {
String numbers = mostLikelyThingHeard.replaceAll("[^0-9]", "");
Intent call = new Intent(Intent.ACTION_DIAL);
call.setData(Uri.parse("tel:" + numbers));
tts.speak(numbers + " wordt gebeld.",
TextToSpeech.QUEUE_FLUSH, null);
found = true;
}
I also added the right permissions in AndroidManifest.xml, I guess the code is wrong.
You need to get numbers from String like this:
String numbers = mostLikelyThingHeard.replaceAll("[^\\d]", "");
To call that number, you can use ACTION_CALL. ACTION_DIAL will just open a dialer screen with that number. Also, you have initialized intent, but you are missing call to startActivity(intent)
Intent call = new Intent(Intent.ACTION_DIAL);
call.setData(Uri.parse("tel:" + numbers));
startActivity(call);
Hope this helps.
Can you try this
Intent.ACTION_CALL
and make sure that you are using this before application tag in manifest file
<uses-permission android:name="android.permission.CALL_PHONE" />
You can use regex and delete non-digits.
str = str.replaceAll("\\D+","");
Try this one..
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + yours_numbers_values));
startActivity(intent);
String one = "bel";
String mostLikelyThingHeard="bel 0612345678";
if (mostLikelyThingHeard.contains(one)) {
String numbers = mostLikelyThingHeard.replaceAll("[^0-9]", "");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+Uri.encode(numbers.trim())));
startActivity(callIntent);
tts.speak(numbers + " wordt gebeld.",
TextToSpeech.QUEUE_FLUSH, null);
found = true;
}
And in Manifest add permission
<uses-permission android:name="android.permission.CALL_PHONE" ></uses-permission>

Android - Send email with image attachment returning 0KB size

I created an app with action click to send email with image attachment file, I was think the code is working right, after I found the image size of attachment is 0kb, and when I clicked it, it said "Unable find the item", here is the code I use for
public void SendEmailWithAttachment(final String imageUrl){
String path = "file:///android_asset".concat(File.separator).concat(getString(R.string.sa_books_directory)).concat(File.separator); // Get the path file from my asset folder
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("image/jpeg");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, "");
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "This is subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "This is email body");
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(path + "IndividualVillas/pages/" + imageUrl + ".jpg"));
startActivity(emailIntent);
}
I don't know where is the problem, I had tried to change the setType but it doesn't help me also. Any kind help will much appreciate :)
Sorry for my bad English
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("image/jpeg");
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
//emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,body);
emailIntent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(new StringBuilder()
.append("I think you'll like this ")
.append(wineName).append(".")
.append("<br /><br />Scanned it with the ")
.append(bottleRating+tastingNote)
emailIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse("file://"+winePic));
final PackageManager pm = ShareWineActivity.this.getPackageManager();
final List<ResolveInfo> matches = pm.queryIntentActivities(emailIntent, 0);
ResolveInfo best = null;
for (final ResolveInfo info : matches)
if (info.activityInfo.packageName.endsWith(".gm")|| info.activityInfo.name.toLowerCase().contains("gmail"))
best = info;
if (best != null)
emailIntent.setClassName(best.activityInfo.packageName,best.activityInfo.name);
startActivityForResult(emailIntent, 2015);
Is the path correct? If you have double checked that then:
The problem here are privileges. If you want to make some private file accessible for other application then probably you want to use this simple, nice and clean solution: https://developer.android.com/reference/android/support/v4/content/FileProvider.html

Reporting progress of parser

I have a large file that I am trying to parse with Antlr in Java, and I would like to show the progress.
It looked like could do the following:
CommonTokenStream tokens = new CommonTokenStream(lexer);
int maxTokenIndex = tokens.size();
and then use maxTokenIndex in a ParseTreeListener as such:
public void exitMyRule(MyRuleContext context) {
int tokenIndex = context.start.getTokenIndex();
myReportProgress(tokenIndex, maxTokenIndex);
}
The second half of that appears to work. I get ever increasing values for tokenIndex. However, tokens.size() is returning 0. This makes it impossible to gauge how much progress I have made.
Is there a good way to get an estimate of how far along I am?
The following appears to work.
File file = getFile();
ANTLRInputStream input = new ANTLRInputStream(new FileReader(file));
ProgressMonitor progress = new ProgressMonitor(null,
"Loading " + file.getName(),
null,
0,
input.size());
Then extend MyGrammarBaseListener with
#Override
public void exitMyRule(MyRuleContext context) {
progress.setProgress(context.stop.getStopIndex());
}

Categories

Resources