Open keyboard on button click - java

I do open Keyboard on Button click and i store all keypress value in String but i am facing some problem like this
1. when i press CAPITAL keys then i will got 2 times char
2. when i press search and Menu button then also enter the key
3. some char i can't get like PIE
So please check this code and give me proper answer.
My Code is :
package com.indianic.phykeyboard;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class KeyboardActivity extends Activity {
EditText mEdit;
Boolean key = false;
Button mKey, mMon;
String getvalue;
InputMethodManager imm;
StringBuilder stringBuilder;
TextView value;
String ch = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mKey = (Button) findViewById(R.id.openkey);
value = (TextView) findViewById(R.id.value);
mKey.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, 0);
stringBuilder = new StringBuilder();
}
});
}
public boolean onKey(View v, int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
return true;
}
return false;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.v("log_tag", "char : " + event.getUnicodeChar());
if (event.getUnicodeChar() != 0) {
int i = event.getUnicodeChar();
ch = new Character((char) i).toString();
}
if (ch.length() > 0) {
if (keyCode == KeyEvent.KEYCODE_DEL && stringBuilder.length() >= 1) {
stringBuilder.delete(stringBuilder.length() - 1, stringBuilder
.length());
} else if (keyCode != KeyEvent.KEYCODE_DEL
&& keyCode != KeyEvent.KEYCODE_ENTER) {
stringBuilder.append(ch);
} else if (keyCode == KeyEvent.KEYCODE_SEARCH
|| keyCode == KeyEvent.KEYCODE_MENU) {
}
}
if (keyCode == KeyEvent.KEYCODE_BACK) {
stringBuilder.delete(0, stringBuilder.length());
finish();
}
String str = stringBuilder.toString().trim();
value.setText(str);
return false;
}
}

you can try this code :
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.v("log_tag", "char : " + event.getUnicodeChar());
if (event.getUnicodeChar() != 0) {
int i = event.getUnicodeChar();
ch += new Character((char) i).toString();
}
if (keyCode == KeyEvent.KEYCODE_DEL && ch.length() > 0) {
ch = ch.substring(0, ch.length() - 1);
}
value.setText(ch);
return super.onKeyDown(keyCode, event);
}

if (event.getUnicodeChar() != 0) {
int i = event.getUnicodeChar();
ch = new Character((char) i).toString();
}
This portion of your routine is losing data. A char can't possible contain all available Unicode codepoints. I don't know if this is related to what is giving you trouble, but it is a sign that you're not doing things correctly and trying to patch over your bugs is probably a mistake -- fixing this will require a more fundamental reworking of your event handler, at least.

Related

Android Speech recognition: negative numbers

I'm having some problems with my app.
It's an app that asks user to enter 2 numbers by speech recognition, one by one.
If i say six and seven it will multiply 6 and 7 and tell me the result.
Even decimals will work (6.2, 7.5).
But when i say minus eight or negative eight, my app immediately crashes, and isn't even asking for another number, just crashes.
In logcat it says "java.lang.NumberFormatException: Invalid double: "minus 8""
so i guess it enters 'minus 8' instead of '-8'.
My question is, what can i do to solve this?
Here is the whole activity:
package cannon.gaming.physicsdroidvoice;
import android.content.Intent;
import android.content.SharedPreferences;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.Toast;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends ActionBarActivity {
private SpeechRecognizer mSpeechRecognizer;
private Intent mSpeechRecognizerIntent;
private boolean mIslistening;
int forza, m, a;
double mass, acc, mares;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
forza = 0;
m = 0;
mass = 0;
a = 0;
acc = 0;
mares = 0;
final String abc = "Welcome to PhysicsDroid!";
final String abcc = "What do you need?";
final String abccc = "Force, Velocity, Mass, Acceleration, Distance, Time, Temperature, Work, Density, Info, or Exit?";
final String abcccc = "Just tap the screen and speak. When you are done, tap the screen again.";
final String abccccc = "Can you repeat please?";
final String force = "Which force equation would you like to use?";
final String exit = "Thank you for using PhysicsDroid, see ya!";
final String one = "First one: F=m times A. Second one: F=p times A. Or third one: Fg=G times m1m2 over r squared?";
final String ma = "What is the mass of object in kilograms?";
final String am = "What is the acceleration of object in meters per second squared?";
final String mnum = "What the fuck!";
final TextToSpeech home = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
//DO NOTHING
}
}
});
new Timer().schedule(
new TimerTask() {
#Override
public void run()
{
home.speak(abc, TextToSpeech.QUEUE_ADD, null);
home.speak(abcc, TextToSpeech.QUEUE_ADD, null);
home.speak(abccc, TextToSpeech.QUEUE_ADD, null);
home.speak(abcccc, TextToSpeech.QUEUE_ADD, null);
}
},
1000
);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
class SpeechRecognitionListener implements RecognitionListener
{
#Override
public void onBeginningOfSpeech()
{
//Log.d(TAG, "onBeginingOfSpeech");
}
#Override
public void onBufferReceived(byte[] buffer)
{
}
#Override
public void onEndOfSpeech()
{
//Log.d(TAG, "onEndOfSpeech");
}
#Override
public void onError(int error)
{
//Log.d(TAG, "error = " + error);
}
#Override
public void onEvent(int eventType, Bundle params)
{
}
#Override
public void onPartialResults(Bundle partialResults)
{
}
#Override
public void onReadyForSpeech(Bundle params)
{
//Log.d(TAG, "onReadyForSpeech"); //$NON-NLS-1$
}
#Override
public void onResults(Bundle results) {
//Log.d(TAG, "onResults"); //$NON-NLS-1$
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
CharSequence cs1 = "Force";
CharSequence cs2 = "force";
CharSequence cs3 = "Exit";
CharSequence cs4 = "exit";
CharSequence cs5 = "First";
CharSequence cs6 = "first";
CharSequence cs7 = "times";
CharSequence cs8 = "equals";
if(forza == 1 && m == 0 && a == 0)
{
if(String.valueOf(matches).contains(cs5) || String.valueOf(matches).contains(cs6) || String.valueOf(matches).contains(cs7) || String.valueOf(matches).contains(cs8))
{
home.speak(ma,TextToSpeech.QUEUE_FLUSH, null);
forza = 0;
m = 1;
}
}
else if(m == 1 && forza == 0 && a == 0)
{
if(String.valueOf(matches).matches(".*\\d.*"))
{
home.speak(am,TextToSpeech.QUEUE_FLUSH, null);
mass = Double.parseDouble(matches.get(0));
m = 0;
a = 1;
}
else
{
home.speak(mnum,TextToSpeech.QUEUE_FLUSH, null);
}
}
else if(a == 1 && m == 0 && forza == 0)
{
if(String.valueOf(matches).matches(".*\\d.*"))
{
acc = Double.parseDouble(matches.get(0));
mares = -mass * acc;
String mare = String.format("The force is %.2f", mares);
home.speak(mare,TextToSpeech.QUEUE_FLUSH, null);
a = 0;
}
else
{
home.speak(mnum,TextToSpeech.QUEUE_FLUSH, null);
}
}
else if(String.valueOf(matches).contains(cs1) || String.valueOf(matches).contains(cs2) && forza == 0 && m == 0 && a == 0)
{
home.speak(force,TextToSpeech.QUEUE_FLUSH, null);
home.speak(one,TextToSpeech.QUEUE_ADD, null);
forza = 1;
}
else if(String.valueOf(matches).contains(cs3) || String.valueOf(matches).contains(cs4) && forza == 0 && m == 0 && a == 0)
{
home.speak(exit,TextToSpeech.QUEUE_FLUSH, null);
new Timer().schedule(
new TimerTask() {
#Override
public void run() {
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
},
4000
);
}
else
{
home.speak(abccccc,TextToSpeech.QUEUE_FLUSH, null);
}
// matches are the return values of speech recognition engine
// Use these values for whatever you wish to do
}
#Override
public void onRmsChanged(float rmsdB)
{
}
}
SpeechRecognitionListener listener = new SpeechRecognitionListener();
mSpeechRecognizer.setRecognitionListener(listener);
RelativeLayout rlayout = (RelativeLayout) findViewById(R.id.MainActivity);
rlayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
boolean mIsListening = false;
if (!mIsListening)
{
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
}
else
{
mSpeechRecognizer.cancel();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the part where it's crashing after 'minus 8'
else if(m == 1 && forza == 0 && a == 0)
{
if(String.valueOf(matches).matches(".*\\d.*"))
{
home.speak(am,TextToSpeech.QUEUE_FLUSH, null);
mass = Double.parseDouble(matches.get(0));
m = 0;
a = 1;
}
else
{
home.speak(mnum,TextToSpeech.QUEUE_FLUSH, null);
}
}
as you can see from the code above, matches is what user spoke.
Please help.
Thanks in advance!
Your problem is that STT (speech to text) is translating what you say to text, and it doesn't understand signs. This kind of operation is call NLP ( Natural Language Processing ) where depending on the strategies you use you can understand, classify and translate what was said to what you need.
To solve your problem you should relly on some simple strategies like Regexes to see if on the returned matches it has the negative or minus word and then convert your number.
Using your piece of code would be something like:
String extractedNumber = matches.get(0).replaceAll("[^0-9.]*","");
mass = Double.parseDouble(extractedNumber);
if ( matches.get(0).matches(".*((minus)|(negative)).*") ){
mass *= -1;
}
What I'm doing is replacing everything that isn't a number, then I verify if in the text exists the words minus or negative and if so I just multiply the number by -1 making it negative.

Converting string from speech to double

I want to make an app that will ask user for 2 numbers one by one.
then multiply them and tell user the result.
but my app crashes when i try to convert user's speech string to double.
this is my code:
num1 = Double.parseDouble(String.valueOf(matches));
(num1 is double, matches is the string form user's speech)
if you need more code just tell me.
thanks in advance!
EDIT: here's the whole activity_
package cannon.gaming.physicsdroidvoice;
import android.content.Intent;
import android.content.SharedPreferences;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import java.io.File;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends ActionBarActivity {
private SpeechRecognizer mSpeechRecognizer;
private Intent mSpeechRecognizerIntent;
private boolean mIslistening;
int forza, m, a;
double mass, acc, mares;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
forza = 0;
m = 0;
mass = 0;
a = 0;
acc = 0;
mares = 0;
final String abc = "Welcome to PhysicsDroid!";
final String abcc = "What do you need?";
final String abccc = "Force, Velocity, Mass, Acceleration, Distance, Time, Temperature, Work, Density, Info, or Exit?";
final String abcccc = "Just tap the screen and speak. When you are done, tap the screen again.";
final String abccccc = "Can you repeat please?";
final String force = "Which force equation would you like to use?";
final String exit = "Thank you for using PhysicsDroid, see ya!";
final String one = "First one: F=m times A. Second one: F=p times A. Or third one: Fg=G times m1m2 over r squared?";
final String ma = "What is the mass of object in kilograms?";
final String am = "What is the acceleration of object in meters per second squared?";
final String mnum = "What the...!";
final TextToSpeech home = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
//DO NOTHING
}
}
});
new Timer().schedule(
new TimerTask() {
#Override
public void run()
{
home.speak(abc, TextToSpeech.QUEUE_ADD, null);
home.speak(abcc, TextToSpeech.QUEUE_ADD, null);
home.speak(abccc, TextToSpeech.QUEUE_ADD, null);
home.speak(abcccc, TextToSpeech.QUEUE_ADD, null);
}
},
1000
);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
class SpeechRecognitionListener implements RecognitionListener
{
#Override
public void onBeginningOfSpeech()
{
//Log.d(TAG, "onBeginingOfSpeech");
}
#Override
public void onBufferReceived(byte[] buffer)
{
}
#Override
public void onEndOfSpeech()
{
//Log.d(TAG, "onEndOfSpeech");
}
#Override
public void onError(int error)
{
//Log.d(TAG, "error = " + error);
}
#Override
public void onEvent(int eventType, Bundle params)
{
}
#Override
public void onPartialResults(Bundle partialResults)
{
}
#Override
public void onReadyForSpeech(Bundle params)
{
//Log.d(TAG, "onReadyForSpeech"); //$NON-NLS-1$
}
#Override
public void onResults(Bundle results)
{
//Log.d(TAG, "onResults"); //$NON-NLS-1$
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
CharSequence cs1 = "Force";
CharSequence cs2 = "force";
CharSequence cs3 = "Exit";
CharSequence cs4 = "exit";
CharSequence cs5 = "First";
CharSequence cs6 = "first";
CharSequence cs7 = "times";
CharSequence cs8 = "equals";
Pattern p = Pattern.compile("[a-zA-Z]");
Matcher mat = p.matcher("3453443534534");
if(forza == 1 && m == 0 && a == 0)
{
if(String.valueOf(matches).contains(cs5) || String.valueOf(matches).contains(cs6) || String.valueOf(matches).contains(cs7) || String.valueOf(matches).contains(cs8))
{
home.speak(ma,TextToSpeech.QUEUE_FLUSH, null);
forza = 0;
m = 1;
}
}
else if(m == 1 && forza == 0 && a == 0)
{
if(String.valueOf(matches).matches(".*\\d.*"))
{
mass = Double.parseDouble(String.valueOf(matches));
home.speak(am,TextToSpeech.QUEUE_FLUSH, null);
m = 0;
a = 1;
home.speak(mnum,TextToSpeech.QUEUE_FLUSH, null);
}
else
{
home.speak(mnum,TextToSpeech.QUEUE_FLUSH, null);
}
}
else if(a == 1 && m == 0 && forza == 0)
{
if(String.valueOf(matches).contains("[a-zA-Z]+") || String.valueOf(matches).equals("") || String.valueOf(matches).equals(".") || String.valueOf(matches).equals("-.") || String.valueOf(matches).equals("-"))
{
home.speak(mnum,TextToSpeech.QUEUE_FLUSH, null);
}
else
{
acc = Double.parseDouble(String.valueOf(matches));
a = 0;
mares = mass * acc;
String mare = String.format("The force is %d", mares);
home.speak(mare,TextToSpeech.QUEUE_FLUSH, null);
}
}
else if(String.valueOf(matches).contains(cs1) || String.valueOf(matches).contains(cs2) && forza == 0 && m == 0 && a == 0)
{
home.speak(force,TextToSpeech.QUEUE_FLUSH, null);
home.speak(one,TextToSpeech.QUEUE_ADD, null);
forza = 1;
}
else if(String.valueOf(matches).contains(cs3) || String.valueOf(matches).contains(cs4) && forza == 0 && m == 0 && a == 0)
{
home.speak(exit,TextToSpeech.QUEUE_FLUSH, null);
new Timer().schedule(
new TimerTask() {
#Override
public void run() {
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
},
4000
);
}
else
{
home.speak(abccccc,TextToSpeech.QUEUE_FLUSH, null);
}
// matches are the return values of speech recognition engine
// Use these values for whatever you wish to do
}
#Override
public void onRmsChanged(float rmsdB)
{
}
}
SpeechRecognitionListener listener = new SpeechRecognitionListener();
mSpeechRecognizer.setRecognitionListener(listener);
RelativeLayout rlayout = (RelativeLayout) findViewById(R.id.MainActivity);
rlayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
boolean mIsListening = false;
if (!mIsListening)
{
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
}
else
{
mSpeechRecognizer.cancel();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Ensure that matches is not null or that it is a double.
You could use try catches to check if matches is a number at runtime. You also should not need String.valueOf if matches is a string.
try {
num1 = Double.parseDouble(matches);
} catch (NumberFormatException e) {
e.pritStackTrace();
}
Also make sure num1 is initialised.

Android Memory Game how to switch between random button that gets highlighted and then user input

Currently, I am making an android app that is going to be a very simple memory game where 1 random button is going to be highlighted, then the user must click the button that was highlighted after the button goes back to normal. If the user gets the button correct the original button that was highlighted the first time will light up, then another random button will light up after just like the first time and they have to click them in order. For further clarification if your unsure its kind of like Simon (The game) http://en.wikipedia.org/wiki/Simon_(game) but for Android.
I currently have this code that gets a random button and displays it but i'm lost on how to do the user input for the game and compare it to what buttons were clicked in the specific order then restarting until they get something wrong.
Any help would be greatly appreciated!
package com.MakeItMobile.fixmymemory;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import android.R.drawable;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainScreen extends Activity implements OnClickListener {
Button buttonRed, buttonYellow, buttonOrange, buttonBlack, buttonGreen,
buttonPurple, buttonPink, buttonLime, buttonDarkBlue;
Random randNumber;
int whichButtonToRepeat[] = {};
int userInput[] = {};
int counter = 0;
int compareCounter = 0;
int n = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mainscreen);
buttonRed = (Button) findViewById(R.id.buttonRed);
buttonYellow = (Button) findViewById(R.id.buttonYellow);
buttonOrange = (Button) findViewById(R.id.buttonOrange);
buttonBlack = (Button) findViewById(R.id.buttonBlack);
buttonGreen = (Button) findViewById(R.id.buttonGreen);
buttonPurple = (Button) findViewById(R.id.buttonPurple);
buttonPink = (Button) findViewById(R.id.buttonPink);
buttonLime = (Button) findViewById(R.id.buttonLime);
buttonDarkBlue = (Button) findViewById(R.id.buttonDarkBlue);
buttonRed.setOnClickListener(this);
buttonYellow.setOnClickListener(this);
buttonOrange.setOnClickListener(this);
buttonBlack.setOnClickListener(this);
buttonGreen.setOnClickListener(this);
buttonPurple.setOnClickListener(this);
buttonPink.setOnClickListener(this);
buttonLime.setOnClickListener(this);
buttonDarkBlue.setOnClickListener(this);
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
switch (which) {
case (DialogInterface.BUTTON_POSITIVE):
whenStarted();
break;
case (DialogInterface.BUTTON_NEGATIVE):
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Would you like to begin?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
public void whenStarted() {
boolean yourTurn = false;
boolean aiTurn = true;
if (aiTurn) {
randomNumber();
n = randomNumber();
for (int i = 0; i < 100; i++) {
System.out.println(n);
Log.i(null, " " + n);
}
if (n == 1) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 2) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 3) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 4) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 5) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 6) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 7) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 8) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 9) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
}
System.out.println(n);
// whichButtonToRepeat[counter] += n;
Log.i(null, "The number is : " + n);
// buttonGreen.setText(whichButtonToRepeat[0]);
counter++;
yourTurn = true;
} else if (yourTurn) {
}
}
// creating a blinking color button for each specific random number
public void delay(final int newStartID, final int endID) {
final int time = 1000;
new CountDownTimer(time, 1000) {
#Override
public void onFinish() {
// TODO Auto-generated method stub
if (n == 1) {
buttonRed.setBackgroundResource(endID);
} else if (n == 2) {
buttonYellow.setBackgroundResource(endID);
} else if (n == 3) {
buttonOrange.setBackgroundResource(endID);
} else if (n == 4) {
buttonBlack.setBackgroundResource(endID);
} else if (n == 5) {
buttonGreen.setBackgroundResource(endID);
} else if (n == 6) {
buttonPurple.setBackgroundResource(endID);
} else if (n == 7) {
buttonPink.setBackgroundResource(endID);
} else if (n == 8) {
buttonLime.setBackgroundResource(endID);
} else if (n == 9) {
buttonDarkBlue.setBackgroundResource(endID);
}
new CountDownTimer(time, 1000) {
#Override
public void onFinish() {
// TODO Auto-generated method stub
if (n == 1) {
buttonRed.setBackgroundResource(newStartID);
} else if (n == 2) {
buttonYellow.setBackgroundResource(newStartID);
} else if (n == 3) {
buttonOrange.setBackgroundResource(newStartID);
} else if (n == 4) {
buttonBlack.setBackgroundResource(newStartID);
} else if (n == 5) {
buttonGreen.setBackgroundResource(newStartID);
} else if (n == 6) {
buttonPurple.setBackgroundResource(newStartID);
} else if (n == 7) {
buttonPink.setBackgroundResource(newStartID);
} else if (n == 8) {
buttonLime.setBackgroundResource(newStartID);
} else if (n == 9) {
buttonDarkBlue.setBackgroundResource(newStartID);
}
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
}.start();
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
}.start();
}
public int randomNumber() {
randNumber = new Random();
int n = randNumber.nextInt(9) + 1;
return n;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case (R.id.buttonRed):
Log.i(null, "testing");
System.out.println("testing");
break;
case (R.id.buttonYellow):
break;
case (R.id.buttonOrange):
break;
case (R.id.buttonBlack):
break;
case (R.id.buttonGreen):
break;
case (R.id.buttonPurple):
break;
case (R.id.buttonPink):
break;
case (R.id.buttonLime):
break;
case (R.id.buttonDarkBlue):
break;
}
}
}
You could, when setting which buttons you want to light up and in what order, do something like:
store the order of random numbers in an array.
each time you assign that random number to a button
buttonRed.setTag(randomNumber()); // button, not just this one
and then, when your user clicks a button, inside your click listener,
#Override
public void onClick(View v) {
Object tag = v.getTag();
if (tag == storedRandomNumber) { // proper compare syntax needed here
found = true;
}
}

Speak Failed Not Bound to TTS Engine

So I had an original activity with basically the same exact code for speaking, but I had to move that code into another activity. The only difference I can tell is that the text to speech is not called in an asynchronous method. The speaking occurs in the speakFull method.
I get these errors:
speak failed: not bound to TTS engine
isSpeaking failed: not bound to TTS engine
I'm new to android development, I've searched through other solutions to this problem, and I can't really seem to find a solution to make mine work. Any advice, or help is appreciated.
Code:
package com.example.webview;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class ReadOut extends Activity implements TextToSpeech.OnInitListener, OnClickListener {
boolean paused = false;
String leftToRead = null;
String res = null;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.read_out);
Intent intent = getIntent();
res = intent.getExtras().getString("response");
TextView textv = (TextView) findViewById(R.id.textView1);
textv.setText(res);
textv.setMovementMethod(new ScrollingMovementMethod());
android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
textv.setHeight((int)(display.getHeight()*0.76));
leftToRead = speakFull(res);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
public String speakFull(String text){
System.out.println("Speaking: " + text);
TextToSpeech tts = new TextToSpeech(this, this);
System.out.println("Speaking");
String[] sentences = text.split("\n|\\.(?!\\d)|(?<!\\d)\\."); // Regex that splits the body of text into the sentences of that body which are stored in a String array.
for(int i = 0; i < sentences.length; i++){
if(!tts.isSpeaking() && !paused){
System.out.println("Speaking: " + i);
tts.speak(sentences[i], TextToSpeech.QUEUE_FLUSH, null);
}else if(paused){
System.out.println("Paused");
String paused = "";
for(int j = i - 1; j < sentences.length; j++){
paused += sentences[j];
}
return paused;
}else{
i--;
}
if(i == sentences.length - 1){
return "Message 001: Complete";
}
}
return null;
}
#Override
public void onInit(int arg0) {
// TODO Auto-generated method stub
}
public void clickPause(View v){
if(paused){
paused = false;
Button b = (Button) findViewById(R.id.button1);
b.setText("Play");
}else{
paused = true;
Button b = (Button) findViewById(R.id.button1);
b.setText("Pause");
if(leftToRead == null){
leftToRead = speakFull(res);
}else{
leftToRead = speakFull(leftToRead);
}
}
}
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}
You can only call speak() after onInit() was called. So move your tts speak code in onCreate to onInit()
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
leftToRead = speakFull(res);
}
and initialize pause to true boolean paused = true;
I have this problem but after some minutes. For now I fixed in this way
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
if(!myTTS.isSpeaking()) {
myTTS = new TextToSpeech(this, this);
System.out.println("tts restarted");
}
It is not a good solution, I know, but for now it works.
Only 1 problem: at the first fault, the tts doesn't speak.

Android: Probleme use keyboard enter button say “Search” and handle its click?

I want to add a search button on the keyboard input and the EditText and searches I proceeded as follows and I have them the following errors
recherche=(EditText)findViewById(R.id.recherche);
recherche.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
new DownloadTask().execute();
return true;
}
return false;
}
});
ERROR : The type new TextView.OnEditorActionListener(){} must implement the inherited abstract method
TextView.OnEditorActionListener.onEditorAction(TextView, int, KeyEvent)
ERROR : KeyEvent cannot be resolved to a type
Here is a sample of my code:
TextView.OnEditorActionListener enterListener = new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if ((keyEvent != null && (keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (i == EditorInfo.IME_ACTION_DONE)) {
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
bQServer.performClick();
}
return false;
}
};
//etUserName.setOnEditorActionListener(enterListener);
etPassword.setOnEditorActionListener(enterListener);
You should be able to just change KeyEvent.KEYCODE_ENTER for KeyEvent.KEYCODE_SEARCH
i.e
TextView.OnEditorActionListener enterListener = new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if ((keyEvent != null && (keyEvent.getKeyCode() == KeyEvent.KEYCODE_SEARCH)) {
new DownloadTask().execute();
return true;
}
return false;
}
};
recherche.setOnEditorActionListener(enterListener);
--Edit--
Make sure you have imported KeyEvent and onEditorActionListener
import android.view.KeyEvent;
import android.widget.TextView.OnEditorActionListener;

Categories