Text-to-Speech Function not working - java

The Android does not talk despite my code being error free and accurate. I have used a toast function to see where the issue occurs. However, both toasts are called.
I have removed all irrelevant code.
The code below is mostly relevant.
package com.example.android.BluetoothChat;
import android.R.string;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Locale;
import java.util.Set;
import android.bluetooth.BluetoothDevice;
import java.io.InputStream;
import java.io.OutputStream;
import android.bluetooth.BluetoothSocket;
import android.widget.EditText;
import java.io.IOException;
import java.util.UUID;
public class MainActivity extends Activity implements LocationListener{
Button start, stop;
TextView tv;
TextView tv2;
TextView sum;
LocationManager lm;
static TextToSpeech Talker;
TextView myLabel;
Handler mhandler = new Handler();
int i;
int sum1 = 0;
static BluetoothDevice mmDevice;
static BluetoothAdapter mBluetoothAdapter;
static BluetoothSocket mmSocket;
String lat;
String lon;
EditText myTextbox;
static OutputStream mmOutputStream;
static InputStream mmInputStream;
static Thread workerThread;
static byte[] readBuffer;
static int readBufferPosition;
static int counter;
static volatile boolean stopWorker;
TextToSpeech talker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
setTitle("Seizure Detection Helmet Application");
myTextbox = (EditText)this.findViewById(R.id.name);
talker = new TextToSpeech(getApplicationContext(),new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR)
{
talker.setLanguage(Locale.US);
}
}
});
Button talk = (Button)this.findViewById(R.id.talk);
talk.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
speakOut();
}
});
public void speakOut()
{
String toSpeak = myTextbox.getText().toString();
Toast.makeText(getApplicationContext(), toSpeak, Toast.LENGTH_SHORT).show();
String full = ("My name is"+toSpeak+ "and I am having a Seizure at 38.901 Latitude and -77.031 Longitude ");
Toast.makeText(getApplicationContext(), toSpeak, Toast.LENGTH_SHORT).show();
talker.speak(full, TextToSpeech.QUEUE_FLUSH, null);
Toast.makeText(getApplicationContext(), full, Toast.LENGTH_SHORT).show();
talker.speak("HELLO",TextToSpeech.QUEUE_FLUSH, null);
}
}

There are several problems with your code. You should check for error returned by setLanguage. You cannot call speakOut until onInit has been called. One way you can insure this is to disable the talk button in the xml layout file and enable it in onInit.

Related

How can I add Continues Speech Recognition in my Android Application?

I want to create application which will write text while listening. I have tried this code but this is not working. and i have followed this link. but it couldn't work for me.
If i speak, it is not displaying spoken words and speech recognition is also not working. if you know the solution Please guide me to solve this problem. Thank you...
package com.kp.notesapp;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.fonts.Font;
import android.graphics.pdf.PdfDocument;
import android.graphics.pdf.PdfRenderer;
import android.os.Bundle;
import android.os.Environment;
import android.print.PageRange;
import android.provider.DocumentsContract;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.text.Html;
import android.text.style.ParagraphStyle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.compose.ui.text.Paragraph;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.android.material.internal.ViewUtils;
import com.kp.notesapp.Models.Notes;
import org.w3c.dom.Document;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
public class NoteView extends AppCompatActivity {
EditText contentEditText;
ImageView micImg;
SpeechRecognizer speechRecognizer;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_view);
getSupportActionBar().hide();
contentEditText = findViewById(R.id.contentNotes);
micImg = findViewById(R.id.micImg);
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
Intent speechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
speechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
speechIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test");
speechIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5);
micImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(count==0){
micImg.setImageResource(R.drawable.micvoice);
speechRecognizer.startListening(speechIntent);
count=1;
}
else{
micImg.setImageResource(R.drawable.mic);
speechRecognizer.stopListening();
count=0;
}
}
});
speechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
/*ArrayList<String> data = bundle.getStringArrayList(speechRecognizer.RESULTS_RECOGNITION);
contentEditText.setText(data.get(0));
Log.e("csData", String.valueOf(data));*/
String str = new String();
Log.e( "csonResults " , String.valueOf(bundle));
ArrayList data = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < data.size(); i++)
{
Log.e("csresult", String.valueOf(data.get(i)));
str += data.get(i);
}
}
#Override
public void onPartialResults(Bundle bundle) {
ArrayList data = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
String word = (String) data.get(data.size() - 1);
contentEditText.setText(word);
Log.e("csWord", word);
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
saveData();
finish();
}
}

Android Studio - The (Very) Basics - startActivty doesn't work

im trying to move the info of a user from one activity to the other, but everytime i run the app it crashes at the "startActivity(i)" Line (i checked everything else, it only crashes at that line).
that's the MainActivity Code
package com.example.hw1511;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.hw1511.Model.User;
import org.w3c.dom.Text;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements Serializable {
private EditText Name;
private EditText Age;
private EditText Birth;
private Button AddUser;
private Button Send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Name = findViewById(R.id.Name);
Age = findViewById(R.id.Age);
Birth = findViewById(R.id.Birth);
AddUser = findViewById(R.id.AddUser);
Send = findViewById(R.id.Send);
Intent i = new Intent(MainActivity.this, SecondActivity.class);
List<User> list1 = new LinkedList<>();
AddUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Name.getText().toString().trim().length() > 0 && Age.getText().toString().trim().length() > 0 && Birth.getText().toString().trim().length() > 0) {
User u = new User(Name.getText().toString(), Integer.parseInt(Age.getText().toString()), Birth.getText().toString());
list1.add(u);
Name.setText("");
Age.setText("");
Birth.setText("");
}
else {
Toast.makeText(MainActivity.this, "Fill All", Toast.LENGTH_SHORT).show();
}
}
});
Send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i.putExtra("Users", (Serializable) list1);
startActivity(i);
}
});
}
}
and that's the SecondActivty Code (it's preety much empty)
package com.example.hw1511;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.hw1511.Model.User;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
import java.util.jar.Attributes;
public class SecondActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
}
please if anyone help me understand what is making my app crash everytime i press the send button! it would really help me a lot.
Your User objects need to implement Serializable as well.
Also, since LinkedLists are Serializable you can use putSerializable(String key, Serializable value) instead of putExtra

String in Database and Drawable Image in drawable folder

How can I get String from my database and combine it with Image from my drawable folder. Help Please.
this is my main activity.
package com.apk.foodanalyzer.healthandnutrifactsanalyzer;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.goactivity.DatabaseHelper;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.goactivity.GoItem;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.goactivity.ListGoAdapter;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.growactivity.GrowDatabaseHelper;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.growactivity.GrowItem;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.growactivity.ListGrowAdapter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
/**
* Created by Pavilion on 11/18/2015.
*/
public class Grow extends AppCompatActivity {
private ListView listviewGrow;
private ListGrowAdapter adapter;
private List<GrowItem> mGrowItemList;
private GrowDatabaseHelper mDBHelper;
private SearchView searchtext;
Integer[] imgid = {R.drawable.carp,R.drawable.catfish, R.drawable.cavalla };
#Override
protected void onCreate(Bundle savedInstanceState) {
searchtext = (SearchView) findViewById(R.id.search_text);
super.onCreate(savedInstanceState);
setContentView(R.layout.grow_layout);
listviewGrow = (ListView)findViewById(R.id.listview_growtable);
mDBHelper = new GrowDatabaseHelper(this);
mGrowItemList = mDBHelper.getListGrow();
adapter = new ListGrowAdapter(imgid, this, mGrowItemList);
listviewGrow.setAdapter(adapter);
listviewGrow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View row, int position, long index) {
Toast.makeText(getApplicationContext(), "Position " + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Grow.this, GrowValueActivityContent.class);
intent.putExtra("RowId", position);
startActivity(intent);
}
});
}
This is my Adapter. I don't know what to revised this. Hope you would help me.
package com.apk.foodanalyzer.healthandnutrifactsanalyzer.growactivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.R;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.goactivity.GoItem;
import java.util.List;
/**
* Created by Pavilion on 12/1/2015.
*/
public class ListGrowAdapter extends BaseAdapter {
private Context mContext;
private List<GrowItem> mGrowItemList;
private final Integer[] imgid;
public ListGrowAdapter(Integer[] imgid, Context mContext, List<GrowItem> mGrowItemList) {
this.imgid = imgid;
this.mContext = mContext;
this.mGrowItemList = mGrowItemList;
}
#Override
public int getCount() {
return mGrowItemList.size();
}
#Override
public GrowItem getItem(int position) {
return mGrowItemList.get(position);
}
#Override
public long getItemId(int position) {
return mGrowItemList.get(position).getRowId();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
GrowItem item = getItem(position);
View vv = View.inflate(mContext, R.layout.go_listview, null);
TextView tvFoodDescription = (TextView)vv.findViewById(R.id.txtvw_fooddescription);
ImageView imgFoodImage = (ImageView)vv.findViewById(R.id.food_image);
tvFoodDescription.setText(item.getFoodDescription());
imgFoodImage.setImageResource(imgid[position]);
return vv;
}
}

onPostExecute gets called too late

First I will describe the process/problem briefly in words. Afterwards, I'll attach all of the code.
I start the android application in debug mode.
Main activity gets called.
It calls Activity2 via "intent".
Then (in onCreate) I start an Async activity in order to get information from a webserver. I do that with this command "new Kontakt(info1, info2, information).execute();"
I've put a break point at the onPostExecute method in "Kontakt" to see what happens. But!! It doesn't stop there. So then I figured, "okey, the doInBackground method didn't get called for some reason"
When I continue to run the code, as a surprise, onPostExecute gets called (somewhere at the end of onClick) and stops at the break point just the way I want it but than it's too late, because I'd like to have the output already in the onCreate method where I called "new Kontakt(info1, info2, information).execute();".
So why does it call onPostExecute too late and what can I do to make the process call it properly already in onCreate at the line "new Kontakt(info1, info2, information).execute();" in Activity2?
The code is below
MainActivity.java
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
Intent intent = new Intent(this, Activity2.class);
startActivity(intent);
break;
}
}
}
Activity2.java
package com.example.myapplication;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
public class Activty2 extends ActionBarActivity implements View.OnClickListener {
Button button;
Context information;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
information=this;
String info1="Yeah";
String info2="Yeah";
new Kontakt(info1, info2, information).execute();
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.button) {
}
}
Kontakt.java
package com.example.myapplication;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;
import java.util.ArrayList;
public class Kontakt extends AsyncTask<Void, Void, Integer> {
public static final int CONNECTION_TIMEOUT = 1000 * 15;
public static final String SERVER_ADDRESS = "http://test.site.net/";
String info1;
String info2;
private final Context information;
public Kontakt(String info1, String info2, Context context) {
this.info1=info1;
this.Info2=info2;
this.information=context;
}
#Override
protected Integer doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("user", info1));
dataToSend.add(new BasicNameValuePair("password", info2));
HttpParams httpRequestParams = getHttpRequestParams();
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS
+ "Register.php");
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
int result=1;
return result;
} catch (Exception e) {
e.printStackTrace();
int result=0;
return result;
}
//return null;
}
private HttpParams getHttpRequestParams() {
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams,
CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams,
CONNECTION_TIMEOUT);
return httpRequestParams;
}
#Override
protected void onPostExecute(Integer result)
{
super.onPostExecute(result);
SharedPreferences.Editor editor = information.getSharedPreferences("INTERNET_KOLL", Context.MODE_PRIVATE).edit();
editor.putString("internet_status", String.valueOf(result));
editor.commit();
}
}
In Activity2, when onCreate() calls new Kontakt(info1, info2, information).execute();:
an asynchronous task (Kontakt) is started in the background
the execution of onCreate() continues
so it's normal that you don't have the response immediately.

Playing a video in android

Im implementing a video playback in android im completely new to android, and this is the bit of code i have gathered so far.
according to the logic it should play a video. don't know where im doing wrong.
package com.themetanoia.readfilefromsdc;
import java.io.File;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import android.widget.AdapterView.OnItemClickListener;
public class ReadFileFromSDCActivity extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get the file path for external storage
String a = Environment.getExternalStorageDirectory().getAbsolutePath();
final String finalPath = a+"/Videos";
//Define new file function
File f=new File(finalPath);
if(f.isDirectory()){
//Define arrayadapter
setListAdapter(new ArrayAdapter<String>(this, R.layout.listview,files));
//Define listview
ListView listview = getListView();
listview.setTextFilterEnabled(true);
//Onclick list item event
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//get selected items
String selectedValue = (String) getListAdapter().getItem(position);
Uri uri = Uri.parse(finalPath);
MediaController mediaController = new MediaController(getBaseContext());
mediaController.setAnchorView(mVideoView);
Uri video = Uri.parse(finalPath+"/"+selectedValue);
mVideoView.setMediaController(mediaController);
mVideoView.setVideoURI(video);
mVideoView.start();
}
});
}
}
}
<VideoView
android:id="#+id/videoView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
VideoView vv = (VideoView) findViewById(R.id.videoView1);
uri = "your video uri";
vv.setVideoURI(Uri.parse(uri));
vv.start();
vv.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
finish();
}
});

Categories