Why Android Text To Speech initialization Is slow? - android

I am implementing TTS (Text to Speech) support in my Android app. I am showing my code :
TextSpeech textSpeech = new TextSpeech();
textToSpeech = new TextToSpeech(this, textSpeech);
private class TextSpeech implements TextToSpeech.OnInitListener {
#Override
public void onInit(final int status) {
if (status != TextToSpeech.ERROR) {
if (TextToSpeech.LANG_AVAILABLE == textToSpeech.isLanguageAvailable(Locale.ENGLISH)) {
Thread thread = new Thread() {
#Override
public void run() {
super.run();
textToSpeech.setLanguage(Locale.ENGLISH);
try {
for (int i = 0; i < 10; i++) {
if (Util.isGreaterThanApi21()) {
textToSpeech.speak("" + i, TextToSpeech.QUEUE_FLUSH, null, null);
} else {
textToSpeech.speak("" + i, TextToSpeech.QUEUE_FLUSH, null);
}
Thread.sleep(1000);
}
} catch (Exception exception) {
}
}
};
thread.start();
} else {
Toast.makeText(ViewWorkplanActivity.this, "Language Not Supported", Toast.LENGTH_SHORT).show();
}
}
}
}
When I run this code, some devices missing 3-4 number or taking 3-4 seconds for initialization. Can any body tell me how can I remove this error?

Related

Thread dosen't interrupted

I'm work on crate server and android client
but thread doesn't interrupted by android client
My android Client has request for the RoomList from server
and Server receive, Client Accept
and fill in my ListView used the Adapter
here's problem if Click backButton,
than RoomListAcitivity was close and thread was stop
but thread dosen't stop just alive in my app
first Enter has work on sucessfully
but Press BackButton on and re-Enter this Activity
MyApp just White, No Action
how can i stop this thread?
(and sorry for my English skill...)
i tried .interrupt() method , and handler.removeMessages(0)
but failed thread keep alive
upload this full java code just in case...
ListView roomList;
RoomAdapter roomAdapter;
Socketservice ss;
String msg,rtitle;
String msgs[];
String list[];
Thread listthread,EnterRoomThread,removeV;
boolean staterun = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_room);
roomList = findViewById(R.id.roomList);
roomAdapter = new RoomAdapter();
listthread = new Thread() {
public void run(){
ss.out.println("163|");
ss.out.println("100|");
try {
while (staterun == true) {
msg = ss.in.readLine();
handler.post(new Runnable() {
public void run() {
msgs = msg.split("\\|");
String protocol = msgs[0];
switch (protocol) {
case "163":
list = msgs[1].split(",");
for (int i = 0; i < list.length; i++) {
String list1[] = list[i].split("-");
String listT = list1[0];
int listC = Integer.parseInt(list1[1]);
int listI = Integer.parseInt(list1[2]);
roomAdapter.CreateRoom(listI, listT, listC);
}
roomList.setAdapter(roomAdapter);
msg = "";
msgs = null;
break;
case "200":
Intent i = new Intent(getApplicationContext(), GameWaitingActivity.class);
i.putExtra("tname", rtitle);
staterun = !staterun;
Toast.makeText(getApplicationContext(),""+listthread.isAlive(),Toast.LENGTH_SHORT).show();
startActivity(i);
finish();
break;
case "201":
Toast.makeText(getApplicationContext(), "방이 꽉 찼습니다.", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
} catch (IOException e) {
}
}
};
listthread.start();
roomList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Room item = (Room) roomList.getItemAtPosition(position);
rtitle=item.getTitle();
EnterRoomThread = new Thread() {
public void run() {
ss.out.println("200|" + rtitle);
EnterRoomThread.interrupt();
}
};
EnterRoomThread.start();
}
});
}
Handler handler = new Handler();
#Override
public void onBackPressed() {
removeV = new Thread() {
public void run(){
ss.out.println("101|");
removeV.interrupt();
}
};
removeV.start();
handler.removeMessages(0);
staterun = false;
listthread.interrupt();
Toast.makeText(getApplicationContext(),""+listthread.isAlive(),Toast.LENGTH_SHORT).show();
finish();
}
}
Go ahead with this, write this inside run() method
//use this boolean value to keep track.
boolean shouldRunFlag = true;
while (shouldRunFlag) {
try {
Thread.sleep(10);
//Do your work............
} catch (Exception e) {
e.printStackTrace();
Log.v(TAG, "Interrupted Exception caught");
// change the flag, so that while loop can be broken.
shouldRunFlag = false;
Log.v(TAG, "run: breaking the loop");
break;
}
}
and this is how you interrupt and clean the thread
private void interrupt(Thread currentThread) {
Log.i(TAG, "interrupt");
if (currentThread != null) {
Thread dummyThread = currentThread;
dummyThread.interrupt();
currentThread = null;
}
}

"list" the counter is greater than the number of elements within the

Problem with "list" the counter is greater than the number of elements within the
This is filled by the response of a server.
public class ListQuestions extends Activity{
private ListQuestionsAdapter adapter;
ListView listquestion;
List<ResponseQuestionDto> questions = new ArrayList<>();
List<ResponseQuestionDto> questionsSelected;
int positionQuestion;
final Handler mHandler = new Handler();
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listquestions);
dialog = ProgressDialog.show(this, "",
getString(R.string.progress), true);
Thread thread = new Thread() {
#Override
public void run() {
try {
questions = BusinessLogic.getQuestions(LiveCookie.getInstance().getToken());
mHandler.post(mUpdate);
} catch (Exception e) {
Util.alert(ListQuestions.this, getString(R.string.Error));
}
}
};
thread.start();
}catch (Exception e)
{
Toast.makeText(ListQuestions.this, getString(R.string.Error), Toast.LENGTH_LONG).show();
}
}
final Runnable mUpdate = new Runnable() {
#Override
public void run() {
try {
dialog.dismiss();
questionsSelected = LiveCookie.getInstance().getQuestionsSelected();
positionQuestion = LiveCookie.getInstance().getPositionQuestion();
try {
if(questionsSelected != null)
{
for (int i=0;i<questionsSelected.size();i++) {
if (questionsSelected != null) {
if (questionsSelected.get(i).pregunta != null) {
if (positionQuestion != i) {
for (int e = 0; e < questions.size(); e++) {
if (questions.get(e) != null) {
if (questions.get(e).pregunta.equals(questionsSelected.get(i).pregunta)) {
questions.remove(questions.get(e));
}
}
}
}
}
}
}
}
}catch (Exception e)
{
//Not Used
}
listquestion = (ListView) findViewById(R.id.listquestion);
adapter = new ListQuestionsAdapter(ListQuestions.this,questions);
listquestion.setAdapter(adapter);
listquestion.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter2, View v, int position, long id) {
questionsSelected = LiveCookie.getInstance().getQuestionsSelected();
ResponseQuestionDto selected = questions.get(position);
positionQuestion = LiveCookie.getInstance().getPositionQuestion();
questionsSelected.set(positionQuestion,selected);
LiveCookie.getInstance().setQuestionsSelected(questionsSelected);
ListQuestions.this.finish();
}});
}catch (Exception e)
{
dialog.dismiss();
Toast.makeText(ListQuestions.this, getString(R.string.Error), Toast.LENGTH_LONG).show();
ListQuestions.this.finish();
}
}
};
}
At first the list is 14 but when I check it in the "setOnItemClickListener" this is 18.
enter image description here
you have to put all code, and where is the code affect the problem?
as well you check before getting data from the list to avoid this problem
if(counter<=list.size-1){
//put your code
}

How to display a single value in android Threads

In android , i create a application based on RFID Card Reader on mobile. While i tapping Card on RFID Reader it generates same value at many times until the card untapped from the reader.
I want to show only one value per tapping card on RFID reader. Here i place my code and Sample snapshot of my application.
Guide me and tell solution for my problem.
public static MediaPlayer mp;
FT_Device ftDev = null;
int DevCount = -1;
int currentIndex = -1;
int openIndex = 0;
/*graphical objects*/
EditText readText;
Button readEnButton;
static int iEnableReadFlag = 1;
/*local variables*/
int baudRate; /*baud rate*/
byte stopBit; /*1:1stop bits, 2:2 stop bits*/
byte dataBit; /*8:8bit, 7: 7bit*/
byte parity; /* 0: none, 1: odd, 2: even, 3: mark, 4: space*/
byte flowControl; /*0:none, 1: flow control(CTS,RTS)*/
int portNumber; /*port number*/
long wait_sec=3000;
byte[] readData; //similar to data.
public static final int readLength = 1024; // changed length from 512
public int iavailable = 0;
char[] readDataToText;
//char readDataToTextSudha;
public boolean bReadThreadGoing = false;
public readThread read_thread;
public static D2xxManager ftD2xx = null;
boolean uart_configured = false;
// Empty Constructor
public MainActivity() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
readData = new byte[readLength];
readDataToText = new char[readLength];
//readDataToTextSudha = new char;
readText = (EditText) findViewById(R.id.ReadValues);
readText.setInputType(0);
readEnButton = (Button) findViewById(R.id.readEnButton);
baudRate = 9600;
/* default is stop bit 1 */
stopBit = 1;
/* default data bit is 8 bit */
dataBit = 8;
/* default is none */
parity = 0;
/* default flow control is is none */
flowControl = 0;
portNumber = 1;
try {
ftD2xx = D2xxManager.getInstance(this);
} catch (D2xxManager.D2xxException ex) {
ex.printStackTrace();
}
//Opening Coding
if (DevCount <= 0) {
createDeviceList();
} else {
connectFunction();
}
//Configuration coding
if (DevCount <= 0 || ftDev == null) {
Toast.makeText(getApplicationContext(), "Device not open yet...", Toast.LENGTH_SHORT).show();
} else {
SetConfig(baudRate, dataBit, stopBit, parity, flowControl);
}
readEnButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (DevCount <= 0 || ftDev == null) {
Toast.makeText(getApplicationContext(), "Device not open yet...", Toast.LENGTH_SHORT).show();
} else if (uart_configured == false) {
Toast.makeText(getApplicationContext(), "UART not configure yet...", Toast.LENGTH_SHORT).show();
return;
} else {
EnableRead();
}
}
});
}
public void EnableRead() {
iEnableReadFlag = (iEnableReadFlag + 1) % 2;
if (iEnableReadFlag == 1) {
ftDev.purge((byte) (D2xxManager.FT_PURGE_TX));
ftDev.restartInTask();
readEnButton.setText("Read Enabled");
Toast.makeText(getApplicationContext(),"Read Enabled",Toast.LENGTH_LONG).show();
} else {
ftDev.stopInTask();
readEnButton.setText("Read Disabled");
Toast.makeText(getApplicationContext(),"Read Disabled",Toast.LENGTH_LONG).show();
}
}
public void createDeviceList() {
int tempDevCount = ftD2xx.createDeviceInfoList(getApplicationContext());
if (tempDevCount > 0) {
if (DevCount != tempDevCount) {
DevCount = tempDevCount;
updatePortNumberSelector();
}
} else {
DevCount = -1;
currentIndex = -1;
}
};
public void disconnectFunction() {
DevCount = -1;
currentIndex = -1;
bReadThreadGoing = false;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ftDev != null) {
synchronized (ftDev) {
if (true == ftDev.isOpen()) {
ftDev.close();
}
}
}
}
public void connectFunction() {
int tmpProtNumber = openIndex + 1;
if (currentIndex != openIndex) {
if (null == ftDev) {
ftDev = ftD2xx.openByIndex(getApplicationContext(), openIndex);
} else {
synchronized (ftDev) {
ftDev = ftD2xx.openByIndex(getApplicationContext(), openIndex);
}
}
uart_configured = false;
} else {
Toast.makeText(getApplicationContext(), "Device port " + tmpProtNumber + " is already opened", Toast.LENGTH_LONG).show();
return;
}
if (ftDev == null) {
Toast.makeText(getApplicationContext(), "open device port(" + tmpProtNumber + ") NG, ftDev == null", Toast.LENGTH_LONG).show();
return;
}
if (true == ftDev.isOpen()) {
currentIndex = openIndex;
Toast.makeText(getApplicationContext(), "open device port(" + tmpProtNumber + ") OK", Toast.LENGTH_SHORT).show();
if (false == bReadThreadGoing) {
read_thread = new readThread(handler);
read_thread.start();
bReadThreadGoing = true;
}
} else {
Toast.makeText(getApplicationContext(), "open device port(" + tmpProtNumber + ") NG", Toast.LENGTH_LONG).show();
}
}
public void updatePortNumberSelector() {
if (DevCount == 2) {
Toast.makeText(getApplicationContext(), "2 port device attached", Toast.LENGTH_SHORT).show();
} else if (DevCount == 4) {
Toast.makeText(getApplicationContext(), "4 port device attached", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "1 port device attached", Toast.LENGTH_SHORT).show();
}
}
public void SetConfig(int baud, byte dataBits, byte stopBits, byte parity, byte flowControl) {
if (ftDev.isOpen() == false) {
Log.e("j2xx", "SetConfig: device not open");
return;
}
ftDev.setBitMode((byte) 0, D2xxManager.FT_BITMODE_RESET);
ftDev.setBaudRate(baud);
ftDev.setDataCharacteristics(dataBits, stopBits, parity);
uart_configured = true;
Toast.makeText(getApplicationContext(), "Config done", Toast.LENGTH_SHORT).show();
}
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (iavailable > 0) {
mp = MediaPlayer.create(MainActivity.this, R.raw.beep);
mp.start();
readText.append(String.copyValueOf(readDataToText, 0, iavailable));
}
}
};
private class readThread extends Thread {
Handler mHandler;
readThread(Handler h) {
mHandler = h;
this.setPriority(Thread.MIN_PRIORITY);
}
#Override
public void run() {
int i;
while (true == bReadThreadGoing) {
try {
Thread.sleep(1000); //changed
} catch (InterruptedException e) {
}
synchronized (ftDev) {
iavailable = ftDev.getQueueStatus();
if (iavailable > 0) {
if (iavailable > readLength) {
iavailable = readLength;
}
ftDev.read(readData, iavailable,wait_sec);
for (i = 0; i < iavailable; i++) {
readDataToText[i] = (char) readData[i];
}
Message msg = mHandler.obtainMessage();
mHandler.sendMessage(msg);
}
}
}
}
}
#Override
public void onResume() {
super.onResume();
DevCount = 0;
createDeviceList();
if (DevCount > 0) {
connectFunction();
SetConfig(baudRate, dataBit, stopBit, parity, flowControl);
}
}
}
My problem would snapped here
Getting Value continuously from Reader
I want this type of value when i tap the card
If i tap some other cards, old card value replaces from the new one.
Guide me.
Thanks in Advance
I got the answer by using of Threads. When the card tapping it get some values after sleep of one or two seconds only the next value have to get from the reader.
public void run() {
int i;
while (true == bReadThreadGoing) { // Means Make sure , getting value from Reader
try {
Thread.sleep(1000); // Wait for a second to get another value.
clearText(); //clear the old value and get new value.
} catch (InterruptedException e) {
}
And clearing the edittext by using this command.
public void clearText() {
runOnUiThread(new Runnable() {
public void run() {
readText.setText("");
}
});
}

Implementing a progress bar in android with specific values doesn't work

I tried to implement a layout that works like a progress bar. I want to it to be able to be set to any level I want in special cases. For example to be set to 20.
#Override
public void handleMessage(Message msg) {
if (msg.what == 0x123) {
mCDrawable.setLevel(mProgress);
}
}
Runnable a= new Runnable() {
#Override
public void run() {
running = true;
handler.sendEmptyMessage(0x123);
mProgress = 20;
try {
Thread.sleep(18);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
public void add(int num){
Thread s = new Thread(a);
s.start();
}
I do it by calling the "add" function.
The problem is that in a "while" where the progress changes continueslly it works:
Runnable r = new Runnable() {
#Override
public void run() {
running = true;
while (running) {
handler.sendEmptyMessage(0x123);
if (mProgress > MAX_PROGRESS) {
mProgress = 0;
}
mProgress += 100;
try {
Thread.sleep(18);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
What is the difference? How can I set it to a specific value otherwise?
---edit----:
I tried this code and it still doesnt work:
public void add(int num){
int lvl = mClipDrawable.getLevel();
Log.d("______________", "the first was "+lvl);
lvl += 100;
if (lvl > 10000) {
lvl = 1000;
}
Log.d("______________", "set to "+lvl);
mClipDrawable.setLevel(lvl);
}
the first level was 0 and it set 100..

Android, Handler's error

This is a bit weird, but I have no idea where the problem is.
In my onCreate() I have this code:
GameRunningNotesTimer().start();
and then out of onCreate I have this code:
Thread GameRunningNotesTimer = new Thread(new Runnable() {
public void run() {
int sleepingTime;
try {
if (r_settings.getGameOver() == 0) {
sleepingTime = 1000 - (r_settings.getInternalLevel() * 100);
if (r_settings.getInternalLevel() == 0) {
Thread.sleep(1000);
} else {
if (sleepingTime <= 399)
{
sleepingTime = 350;
}
Thread.sleep(sleepingTime);
}
if (r_settings.getGameOver() == 1){ gameOver(); }
myHandler2.sendEmptyMessage(0);
} // End of if (r_settings.getGameOver()
} catch (Exception e) { Log.e("MUSIC!!!!!", "Error in activity", e); }
}// End of run
}); // End of GameRunningNotesTimer()
final Handler myHandler2 = new Handler() {
#Override
public void handleMessage(Message msg) {
//text2.setText(""+item[0]);
int z = 1;
if (r_settings.getGameStarted() == true)
{
changeNoteFromTimer();
} else {
startingCountdown(z);
}
} // end of handleMessage()
};
but this GameRunningNotesTimer().start(); is underlined in red (in Eclipse) and when I mouseover it it says: The method GameRunningNotesTimer() is undefined for the type GameScr
What am I doing wrong? another thread/handler in the same class is not giving me this problem.
Thanks!
It should be GameRunningNotesTimer.start(); not GameRunningNotesTimer().start();

Categories

Resources