i already set google tts language to hindi.And in my code i am setting that hindi as a default language by tts.setLanguage(Locale.getDefault()),my code working fine.But when i am using Locale.getDefault().getDisplayLanguage() to get default language,logcat shows English.
I want to set language according to user.
package com.example.texttospeech;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.ActionBarActivity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
#SuppressWarnings("unused")
public class MainActivity extends Activity implements TextToSpeech.OnInitListener{
private TextToSpeech tts;
EditText ed1,ed2;
Button b1,b2;
AudioManager audioManager;
static final int READ_BLOCK_SIZE = 100;
protected static final int PICKFILE_RESULT_CODE = 1;
protected static final int ACTIVITY_TTS_PASS=1;
#SuppressWarnings("static-access")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText1);
b1=(Button)findViewById(R.id.button1);
ed2=(EditText)findViewById(R.id.editText2);
b2=(Button)findViewById(R.id.button2);
tts = new TextToSpeech(this, this);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int amStreamMusicMaxVol = audioManager.getStreamMaxVolume(audioManager.STREAM_MUSIC);
audioManager.setStreamVolume(audioManager.STREAM_MUSIC, amStreamMusicMaxVol, 0);
audioManager.setSpeakerphoneOn(true);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "clicked",Toast.LENGTH_SHORT).show();
try {
if(ed1.getText().toString()==null || ed1.getText().toString().matches(""))
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file.txt/*");
startActivityForResult(intent,PICKFILE_RESULT_CODE);
}else
{
savefile();
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// openfile();
}
});
}
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onInit(int status) {
Locale.getDefault().getDisplayLanguage();
Log.e("--f----f-----f-- ",""+Locale.getDefault().getDisplayLanguage());
if (status == TextToSpeech.SUCCESS)
{
int result = tts.setLanguage(Locale.getDefault());
Log.e("--g----g-----g--",""+result);
tts.setLanguage(new Locale("hi_IN"));
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED)
{
Log.e("TTS", "This Language is not supported");
}
else {
b1.setEnabled(true);
try {
savefile();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
private void savefile() throws IOException {
String text = ed1.getText().toString();
FileOutputStream fos = null;
final File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
"/MynewText/" );
if (!dir.exists())
{
dir.mkdirs();
}
final File myFile = new File(dir, "newtest" + ".txt");
if (!myFile.exists())
{
myFile.createNewFile();
}
fos = new FileOutputStream(myFile);
fos.write(text.getBytes());
fos.close();
Toast.makeText(getBaseContext(), "File saved successfully!",Toast.LENGTH_SHORT).show();
tts.setSpeechRate(0);
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
try {
// Read text from file
File sdcard = Environment.getExternalStorageDirectory();
File file1 = new File(sdcard,"MynewText/newtest.txt");
//Read text from file
StringBuilder text1 = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file1));
String line;
while ((line = br.readLine()) != null)
{
text1.append(line);
text1.append('\n');
}
ed2.setText(text1);
br.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode)
{
case ACTIVITY_TTS_PASS:
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS)
{
tts = new TextToSpeech(getApplicationContext(), this);
int availability = tts.isLanguageAvailable(new Locale("hin-IND"));
switch(availability)
{
case TextToSpeech.LANG_AVAILABLE:
Log.d("TTS", "Language available");
break;
case TextToSpeech.LANG_NOT_SUPPORTED:
Log.d("TTS", "Language not supported");
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
ArrayList<String> languages = new ArrayList<String>();
languages.add("hin-IND"); // hin - hindi, IND - INDIA
installTTSIntent.putStringArrayListExtra(
TextToSpeech.Engine.EXTRA_CHECK_VOICE_DATA_FOR, languages);
startActivity(installTTSIntent);
break;
case TextToSpeech.LANG_MISSING_DATA:
Log.d("TTS", "Language missing data");
break;
case TextToSpeech.LANG_COUNTRY_AVAILABLE:
Log.d("TTS", "Contry available");
break;
default:
Log.d("TTS", "default");
}
}
else {
Log.d("TTS", "fail");
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
ArrayList<String> languages = new ArrayList<String>();
languages.add("hin-IND"); // hin - hindi, IND - INDIA
installTTSIntent.putStringArrayListExtra(
TextToSpeech.Engine.EXTRA_CHECK_VOICE_DATA_FOR, languages);
startActivity(installTTSIntent);
}
break;
default:
Log.d("TTS", "case default");
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
For getting Default language set in setting > Language and Input > Google-Text-To-Speech default language set , i used :
tts.getLanguage();
Related
I have an android app that lets me scan barcodes and it saves to csv upon pressing a save button.
Would it be possible for me to auto-save data upon the scan result of a certain column?
So in short save after scan initiated in a certain edit text location.
**EDIT !:
packages and imports used.:
package kinjal.com.barcodescanner;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;**
//btn_save = (Button) findViewById(R.id.button4);
btn_scanecode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
scanBar(view);
}
});
btn_savedata.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
final String binlocation = edt_binlocation.getText().toString().trim();
final String islenumber = edt_islenumber.getText().toString().trim();
final String shelfnumber = edt_shelf_number.getText().toString().trim();
final String sku_barcode = edt_skubarcode.getText().toString().trim();
final String quantity = edt_quantity.getText().toString().trim();
if (binlocation.length() == 0)
{
edt_binlocation.setError("Enter BIN Location");
} else if (islenumber.length() == 0) {
edt_islenumber.setError("Enter ISLE Number");
} else if (shelfnumber.length() == 0) {
edt_shelf_number.setError("Enter Shelf Number");
} else if (sku_barcode.length() == 0) {
edt_skubarcode.setError("Scan the Item");
} else if (quantity.length() == 0) {
edt_quantity.setError("Enter Quantity");
} else {
try {
File folder = new File(Environment.getExternalStorageDirectory()
+ "/Download/ScannedData");
boolean var = false;
if (!folder.exists())
var = folder.mkdir();
final String filename = folder.toString() + "/" + "ScannedDataFile.csv";
// show waiting screen
// CharSequence contentTitle = getString(R.string.app_name);
//FileWriter(filename, boolean append);
// output = new BufferedWriter(new FileWriter(filename, true));
try {
//BufferedWriter fw = new BufferedWriter(new FileWriter(filename, true));
FileWriter fw = new FileWriter(filename, true);
{
BufferedReader br = new BufferedReader(new FileReader(filename));
String line = br.readLine();
if (line == null) {
fw.append("BIN Number");
fw.write(",");
fw.append("ISIE Number");
fw.write(",");
fw.append("Shelf Number");
fw.write(",");
fw.append("SKU");
fw.write(",");
fw.append("Quantity");
fw.write(",");
fw.write("\n");
}
fw.append(binlocation);
fw.append(',');
fw.append(islenumber);
fw.append(',');
fw.append(shelfnumber);
fw.append(',');
fw.append(sku_barcode);
fw.append(',');
fw.append(quantity);
fw.append(',');
fw.append('\n');
Toast.makeText(Main2Activity.this, "Row Inserted..", Toast.LENGTH_SHORT).show();
fw.flush();
edt_skubarcode.setText("");
edt_quantity.setText("1");
edt_skubarcode.requestFocus();
}
} catch (Exception e) {
}
} catch (Exception e) {
}
}
}
});
}
From the below code I can convert a image file to byte array in my mobile app.But I cannot Convert a video file since OutOfMemoryError exception comes. I want to send a video file to a arduino board. Since I can send a string from android app to arduino, I am trying to send a video file like that. But it fails. I there any other solution to solve my problem?please help.
Code for converting image to byte array
package com.example.krishan.detectusbplugin;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File file = new File(Environment.getExternalStorageDirectory() + "/Output/" +"My.mp4");
// convertFileToByteArray(file);
System.out.println(Arrays.toString(convertFileToByteArray(file)));
try {
System.out.write(convertFileToByteArray(file));
} catch (IOException e) {
e.printStackTrace();
}
}
public static byte[] convertFileToByteArray(File f) {
byte[] byteArray = null;
try {
InputStream inputStream = new FileInputStream(f);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024 * 8];
int bytesRead = 0;
while ((bytesRead = inputStream.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byteArray = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return byteArray;
}
}
Code for sending a string to arduino through usb cable
package com.hariharan.arduinousb;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.felhr.usbserial.UsbSerialDevice;
import com.felhr.usbserial.UsbSerialInterface;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends Activity {
public final String ACTION_USB_PERMISSION = "com.hariharan.arduinousb.USB_PERMISSION";
Button startButton, sendButton, clearButton, stopButton;
TextView textView;
EditText editText;
UsbManager usbManager;
UsbDevice device;
UsbSerialDevice serialPort;
UsbDeviceConnection connection;
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { //Defining a Callback which triggers whenever data is read.
#Override
public void onReceivedData(byte[] arg0) {
String data = null;
try {
data = new String(arg0, "UTF-8");
data.concat("/n");
tvAppend(textView, data);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { //Broadcast Receiver to automatically start and stop the Serial connection.
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_USB_PERMISSION)) {
boolean granted = intent.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
if (granted) {
connection = usbManager.openDevice(device);
serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
if (serialPort != null) {
if (serialPort.open()) { //Set Serial Connection Parameters.
setUiEnabled(true);
serialPort.setBaudRate(9600);
serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
serialPort.setParity(UsbSerialInterface.PARITY_NONE);
serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
serialPort.read(mCallback);
tvAppend(textView, "Serial Connection Opened!\n");
} else {
Log.d("SERIAL", "PORT NOT OPEN");
Toast.makeText(getApplicationContext(), "SERIAL , PORT NOT OPEN", Toast.LENGTH_LONG).show();
}
} else {
Log.d("SERIAL", "PORT IS NULLPORT IS NULL");
Toast.makeText(getApplicationContext(), "SERIAL , PORT IS NULL", Toast.LENGTH_LONG).show();
}
} else {
Log.d("SERIAL", "PERM NOT GRANTED");
Toast.makeText(getApplicationContext(), "SERIAL , PERM NOT GRANTED", Toast.LENGTH_LONG).show();
}
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
onClickStart(startButton);
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
onClickStop(stopButton);
}
}
;
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usbManager = (UsbManager) getSystemService(this.USB_SERVICE);
startButton = (Button) findViewById(R.id.buttonStart);
sendButton = (Button) findViewById(R.id.buttonSend);
clearButton = (Button) findViewById(R.id.buttonClear);
stopButton = (Button) findViewById(R.id.buttonStop);
editText = (EditText) findViewById(R.id.editText);
textView = (TextView) findViewById(R.id.textView);
setUiEnabled(false);
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(broadcastReceiver, filter);
}
public void setUiEnabled(boolean bool) {
startButton.setEnabled(!bool);
sendButton.setEnabled(bool);
stopButton.setEnabled(bool);
textView.setEnabled(bool);
}
public void onClickStart(View view) {
HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
if (!usbDevices.isEmpty()) {
boolean keep = true;
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int devicePID = device.getProductId();
if (devicePID == 0x0043)//Arduino Product ID in Hexa
{
PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
usbManager.requestPermission(device, pi);
keep = false;
} else {
Toast.makeText(getApplicationContext(), "PID does not match", Toast.LENGTH_LONG).show();
connection = null;
device = null;
}
if (!keep)
break;
}
}
}
public void onClickSend(View view) {
String string = editText.getText().toString();
serialPort.write(string.getBytes());
tvAppend(textView, "\nData Sent : " + string + "\n");
}
public void onClickStop(View view) {
setUiEnabled(false);
serialPort.close();
tvAppend(textView, "\nSerial Connection Closed! \n");
}
public void onClickClear(View view) {
textView.setText(" ");
}
private void tvAppend(TextView tv, CharSequence text) {
final TextView ftv = tv;
final CharSequence ftext = text;
runOnUiThread(new Runnable() {
#Override
public void run() {
ftv.append(ftext);
}
});
}
}
I'm learning how to create app with android studio,
this is my code source:
package com.example.droide;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class DroideSphereRuhlmannActivity extends Activity implements OnClickListener {
private TextView logview;
private Button connect, deconnect;
private ImageView forwardArrow, backArrow, rightArrow, leftArrow, stop, topleftArrow, toprightArrow, backleftArrow, backrightArrow;
private BluetoothAdapter mBluetoothAdapter = null;
private String[] logArray = null;
private BtInterface bt = null;
static final String TAG = "Droid";
static final int REQUEST_ENABLE_BT = 3;
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
String data = msg.getData().getString("receivedData");
addToLog(data);
}
};
final Handler handlerStatus = new Handler() {
public void handleMessage(Message msg) {
int status = msg.arg1;
if(status == BtInterface.CONNECTED) {
addToLog("Connected");
} else if(status == BtInterface.DISCONNECTED) {
addToLog("Disconnected");
}
}
};
private void addToLog(String message){
for (int i = 1; i < logArray.length; i++){
logArray[i-1] = logArray[i];
}
logArray[logArray.length - 1] = message;
logview.setText("");
for (int i = 0; i < logArray.length; i++){
if (logArray[i] != null){
logview.append(logArray[i] + "\n");
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_remote);
logview = (TextView)findViewById(R.id.logview);
logArray = new String[3];
connect = (Button)findViewById(R.id.connect);
connect.setOnClickListener(this);
deconnect = (Button)findViewById(R.id.deconnect);
deconnect.setOnClickListener(this);
forwardArrow = (ImageView)findViewById(R.id.forward_arrow);
forwardArrow.setOnClickListener(this);
backArrow = (ImageView)findViewById(R.id.back_arrow);
backArrow.setOnClickListener(this);
rightArrow = (ImageView)findViewById(R.id.right_arrow);
rightArrow.setOnClickListener(this);
leftArrow = (ImageView)findViewById(R.id.left_arrow);
leftArrow.setOnClickListener(this);
stop = (ImageView)findViewById(R.id.stop);
stop.setOnClickListener(this);
topleftArrow = (ImageView)findViewById(R.id.topleft_arrow);
topleftArrow.setOnClickListener(this);
toprightArrow = (ImageView)findViewById(R.id.topright_arrow);
toprightArrow.setOnClickListener(this);
backrightArrow = (ImageView)findViewById(R.id.backright_arrow);
backrightArrow.setOnClickListener(this);
backleftArrow = (ImageView)findViewById(R.id.backleft_arrow);
backrightArrow.setOnClickListener(this);
}
#Override
public void onResume() {
super.onResume();
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Log.v(TAG, "Device does not support Bluetooth");
}
else{
if (!mBluetoothAdapter.isEnabled()){
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
else{
bt = new BtInterface(handlerStatus, handler);
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent moreData){
if (requestCode == REQUEST_ENABLE_BT){
if (resultCode == Activity.RESULT_OK){
bt = new BtInterface(handlerStatus, handler);
}
else if (resultCode == Activity.RESULT_CANCELED)
Log.v(TAG, "BT pas active");
else
Log.v(TAG, "code n'est pas valide");
}
else{
Log.v(TAG, "code n'est pas reconnu");
}
}
#Override
public void onClick(View v) {
if(v == connect) {
addToLog("Appareillage en cours");
bt.connect();
}
else if(v == deconnect) {
addToLog("connexion en cours");
bt.close();
}
else if(v == forwardArrow) {
bt.sendData("F");
}
else if(v == backArrow) {
bt.sendData("B");
}
else if(v == rightArrow) {
bt.sendData("R");
}
else if(v == leftArrow) {
bt.sendData("L");
}
else if( v == topleftArrow){
bt.sendData("I");
}
else if(v == toprightArrow){``
bt.sendData("J");
}
else if(v == backleftArrow){
bt.sendData("G");
}
else if(v ==backrightArrow){
bt.sendData("H");
}
else if(v == stop) {
bt.sendData("S");
}
Error Log:
After that, I got some error like :
"Error:(156, 10) error: reached end of file while parsing"
or
"Error:Execution failed for task ':app:compileDebugJavaWithJavac'."
So now I don't now how to solve that.
If this is your full code then your onClick method has not ending curly bracket and also your main class is not ended with curly bracket.
so add two ending curly braces at end of your code
I have device bluetooth with button, I want connect to this device after click button on this device, it's there any example to do this?
May this help you.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements Runnable {
protected static final String TAG = "TAG";
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
Button mScan, mPrint;
static OutputStream outStream;
BluetoothAdapter mBluetoothAdapter;
private UUID applicationUUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private ProgressDialog mBluetoothConnectProgressDialog;
static BluetoothSocket mBluetoothSocket;
BluetoothDevice mBluetoothDevice;
#Override
public void onCreate(Bundle mSavedInstanceState) {
super.onCreate(mSavedInstanceState);
setContentView(R.layout.activity_main);
mScan = (Button) findViewById(R.id.Scan);
mScan.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(MainActivity.this, "Message1", 2000).show();
} else {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,
REQUEST_ENABLE_BT);
} else {
ListPairedDevices();
Intent connectIntent = new Intent(MainActivity.this,
DeviceListActivity.class);
startActivityForResult(connectIntent,
REQUEST_CONNECT_DEVICE);
}
}
}
});
mPrint = (Button) findViewById(R.id.mPrint);
mPrint.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
Thread t = new Thread() {
public void run() {
try {
if (mBluetoothSocket != null) {
//code for send data on printer to print
sendDataToDevice("Hello");
}
// printer specific code you can comment ==== > End
} catch (Exception e) {
Log.e("Main", "Exe ", e);
}
}
};
t.start();
}
});
/* mDisc = (Button) findViewById(R.id.dis); */
/*
* mDisc.setOnClickListener(new View.OnClickListener() { public void
* onClick(View mView) { if (mBluetoothAdapter != null)
* mBluetoothAdapter.disable(); } });
*/
}// onCreate
public void onActivityResult(int mRequestCode, int mResultCode,
Intent mDataIntent) {
super.onActivityResult(mRequestCode, mResultCode, mDataIntent);
switch (mRequestCode) {
case REQUEST_CONNECT_DEVICE:
if (mResultCode == Activity.RESULT_OK) {
Bundle mExtra = mDataIntent.getExtras();
String mDeviceAddress = mExtra.getString("DeviceAddress");
Log.v(TAG, "Coming incoming address " + mDeviceAddress);
mBluetoothDevice = mBluetoothAdapter
.getRemoteDevice(mDeviceAddress);
mBluetoothConnectProgressDialog = ProgressDialog.show(this,
"Connecting...", mBluetoothDevice.getName() + " : "
+ mBluetoothDevice.getAddress(), true, false);
Thread mBlutoothConnectThread = new Thread(this);
mBlutoothConnectThread.start();
// pairToDevice(mBluetoothDevice); This method is replaced by
// progress dialog with thread
}
break;
case REQUEST_ENABLE_BT:
if (mResultCode == Activity.RESULT_OK) {
ListPairedDevices();
Intent connectIntent = new Intent(MainActivity.this,
DeviceListActivity.class);
startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
} else {
Toast.makeText(MainActivity.this, "Message", 2000).show();
}
break;
}
}
private void ListPairedDevices() {
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter
.getBondedDevices();
if (mPairedDevices.size() > 0) {
for (BluetoothDevice mDevice : mPairedDevices) {
Log.v(TAG, "PairedDevices: " + mDevice.getName() + " "
+ mDevice.getAddress());
}
}
}
public void run() {
try {
mBluetoothSocket = mBluetoothDevice
.createRfcommSocketToServiceRecord(applicationUUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
mHandler.sendEmptyMessage(0);
} catch (IOException eConnectException) {
Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
closeSocket(mBluetoothSocket);
return;
}
}
private void sendDataToDevice(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Send data: " + message + "...");
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: "
+ e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg
+ ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
msg = msg
+ ".\n\nTry Connecting the device one more time from the options menu.\n\n";
errorExit("Fatal Error", msg);
}
}
private void closeSocket(BluetoothSocket nOpenSocket) {
try {
nOpenSocket.close();
Log.d(TAG, "SocketClosed");
} catch (IOException ex) {
Log.d(TAG, "CouldNotCloseSocket");
}
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
mBluetoothConnectProgressDialog.dismiss();
Toast.makeText(MainActivity.this, "DeviceConnected", 5000).show();
}
};
}
and DeviceListActivty.java is like this
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class DeviceListActivity extends Activity {
protected static final String TAG = "TAG";
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
#Override
protected void onCreate(Bundle mSavedInstanceState) {
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list);
setResult(Activity.RESULT_CANCELED);
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this,
R.layout.device_name);
ListView mPairedListView = (ListView) findViewById(R.id.paired_devices);
mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
mPairedListView.setOnItemClickListener(mDeviceClickListener);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter
.getBondedDevices();
if (mPairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice mDevice : mPairedDevices) {
mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n"
+ mDevice.getAddress());
}
} else {
String mNoDevices = "None Paired";// getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(mNoDevices);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery();
}
}
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> mAdapterView, View mView,
int mPosition, long mLong) {
mBluetoothAdapter.cancelDiscovery();
String mDeviceInfo = ((TextView) mView).getText().toString();
String mDeviceAddress = mDeviceInfo
.substring(mDeviceInfo.length() - 17);
Log.v(TAG, "Device_Address " + mDeviceAddress);
Bundle mBundle = new Bundle();
mBundle.putString("DeviceAddress", mDeviceAddress);
Intent mBackIntent = new Intent();
mBackIntent.putExtras(mBundle);
setResult(Activity.RESULT_OK, mBackIntent);
finish();
}
};
}
I'm trying to make speaking dictionary.
LogCat shows "Successfully bound to com.android.tts" but when the Speak button clicked, it shows "failed speak : not bound to tts engine".
But on AVD it runs smoothly, why?
This Is my goTranslator class:
package sk.team;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.speech.tts.TextToSpeech;
import android.widget.Toast;
import android.content.Intent;
import android.content.res.Configuration;
import java.util.Locale;
public class goTranslator extends Activity implements TextToSpeech.OnInitListener{
private int MY_DATA_CHECK_CODE = 0;
private TextToSpeech tts;
private SQLiteDatabase db = null;
private Cursor translatorCursor = null;
private EditText txtSearch;
private EditText txtResult;
private AppDatabase dbtranslator = null;
private RadioButton Eng,Ind;
private Button Translate,Speak;
public static final String ENGLISH = "english";
public static final String INDONESIA = "indonesia";
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Toast.makeText(goTranslator.this,
"Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
} else if (status == TextToSpeech.ERROR) {
Toast.makeText(goTranslator.this,
"Error occurred while initializing Text-To-Speech engine",
Toast.LENGTH_LONG).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
tts = new TextToSpeech(this, this);
} else {
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbtranslator = new AppDatabase(this);
db = dbtranslator.getWritableDatabase();
setContentView(R.layout.main);
dbtranslator.createTable(db);
dbtranslator.generateData(db);
Eng = (RadioButton) findViewById(R.id.Eng);
Ind = (RadioButton) findViewById(R.id.Ind);
Translate = (Button) findViewById(R.id.Translate);
Speak = (Button) findViewById(R.id.Speak);
txtSearch = (EditText) findViewById(R.id.txtSearch);
txtResult = (EditText) findViewById(R.id.txtResult);
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
Speak.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String text = txtResult.getText().toString();
if (text!=null && text.length()>0) {
Toast.makeText(goTranslator.this, "Saying: " + text,
Toast.LENGTH_LONG).show();
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
}
}
});
}
public void Translate (View view) {
if (view == Translate) {
if (Eng.isChecked()) {
txtSearch.setHint("Masukkan Kata");
Locale loc = new Locale ("es_ES");
tts.setLanguage(loc);
String result = "";
String englishword = txtSearch.getText().toString().trim().toLowerCase();
translatorCursor = db.rawQuery("SELECT ID, ENGLISH, INDONESIA "
+ "FROM translator where ENGLISH='" + englishword
+ "' ORDER BY ENGLISH", null);
if (translatorCursor.moveToFirst()) {
result = translatorCursor.getString(2);
for (; !translatorCursor.isAfterLast(); translatorCursor.moveToNext()) {
result = translatorCursor.getString(2);
}
}
if (result.equals("")) {
result = "Kata Tidak Tersedia";
}
txtResult.setText(result);
}
if (Ind.isChecked()) {
txtSearch.setHint("Enter Word");
Locale loc = new Locale ("en_US");
tts.setLanguage(loc);
String result = "";
String indonesiaword = txtSearch.getText().toString().trim().toLowerCase();
translatorCursor = db.rawQuery("SELECT ID, ENGLISH, INDONESIA "
+ "FROM translator where INDONESIA='" + indonesiaword
+ "' ORDER BY INDONESIA", null);
if (translatorCursor.moveToFirst()) {
result = translatorCursor.getString(1);
for (; !translatorCursor.isAfterLast(); translatorCursor.moveToNext()) {
result = translatorCursor.getString(1);
}
}
if (result.equals("")) {
result = "Result Not Found";
}
txtResult.setText(result);
}
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.main);
}
#Override
public void onDestroy() {
super.onDestroy();
if (tts != null) {
tts.stop();
tts.shutdown();
}
if (translatorCursor != null) {
translatorCursor.close();
db.close();
}
}
}
Log.w(TAG, method + " failed: not bound to TTS engine");
I caused by
mServiceConnection;
Being null
Does your testing device lack an internet connection?