I am trying to run the Android SpellChecker With The EditText but it is not running displaying some errors as follows:
My Activity is As Follows:
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.textservice.SentenceSuggestionsInfo;
import android.view.textservice.SpellCheckerSession;
import android.view.textservice.SpellCheckerSession.SpellCheckerSessionListener;
import android.view.textservice.SuggestionsInfo;
import android.view.textservice.TextInfo;
import android.view.textservice.TextServicesManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class HelloSpellCheckerActivity extends Activity implements SpellCheckerSessionListener {
private static final int NOT_A_LENGTH = -1;
private TextView mMainView;
private SpellCheckerSession mScs;
private EditText editText1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mMainView = (TextView)findViewById(R.id.main);
editText1 = (EditText)findViewById(R.id.editText1);
}
#Override
public void onResume() {
super.onResume();
final TextServicesManager tsm = (TextServicesManager) getSystemService(
Context.TEXT_SERVICES_MANAGER_SERVICE);
mScs = tsm.newSpellCheckerSession(null, null, this, true);
}
#Override
public void onPause() {
super.onPause();
if (mScs != null) {
mScs.close();
}
}
public void go(View view){
Toast.makeText(getApplicationContext(), editText1.getText().toString(),
Toast.LENGTH_SHORT).show();
mScs.getSuggestions(new TextInfo(editText1.getText().toString()), 3);
}
#Override
public void onGetSuggestions(final SuggestionsInfo[] arg0) {
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < arg0.length; ++i) {
// Returned suggestions are contained in SuggestionsInfo
final int len = arg0[i].getSuggestionsCount();
sb.append('\n');
for (int j = 0; j < len; ++j) {
sb.append("," + arg0[i].getSuggestionAt(j));
}
sb.append(" (" + len + ")");
}
runOnUiThread(new Runnable() {
public void run() {
mMainView.append(sb.toString());
}
});
}
#Override
public void onGetSentenceSuggestions(SentenceSuggestionsInfo[] arg0) {
// TODO Auto-generated method stub
}
}
I am uploading an image of the error. Please have a look and let me know why this error is occuring:
Your manifest has minSdkVersion as 8, which won't work.
You will have to change your minSdkVersion to 14 in manifest file.
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="18" />
As SpellCheckerSessionListener was added in API level 14, your project is showing errors.
Hope this helps.
Related
this is the view that crashes when i click start but i dont know why
i think it has something to do with the threding in the bruteForce function
package com.my.app;
import android.app.*;
import android.os.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;
import android.content.*;
import android.graphics.*;
import android.media.*;
import android.net.*;
import android.text.*;
import android.util.*;
import java.util.*;
import java.text.*;
import android.test.*;
import android.view.animation.*;
import android.widget.Button;
public class TestActivity extends Activity {
private LinearLayout linear1;
private TextView original;
private TextView match;
private TextView text;
private Button bstart;
String attempt = new String();
boolean running;
int counter;
private String hash = "";
public String username = new String();
public static String password = "ZZZZZ";
public static char[] charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
private static char[] currentGuess = new char[1];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
initialize();
initializeLogic();
}
private void initialize() {
linear1 = (LinearLayout) findViewById(R.id.linear1);
original = (TextView) findViewById(R.id.original);
match = (TextView) findViewById(R.id.match);
text = (TextView) findViewById(R.id.text);
bstart = (Button) findViewById(R.id.bstart);
bstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View _v) {
bruteForce();
}
});
}
private void initializeLogic() {
Intent test = getIntent();
hash = test.getStringExtra("hash");
original.setText(password);
}
public void increment()
{
int index = currentGuess.length - 1;
while (index >= 0)
{
if (currentGuess[index] == charset[charset.length - 1])
{
if (index == 0)
{
currentGuess = new char[currentGuess.length + 1];
Arrays.fill(currentGuess, charset[0]);
break;
}
else
{
currentGuess[index] = charset[0];
index--;
}
}
else
{
currentGuess[index] = charset[Arrays.binarySearch(charset, currentGuess[index]) + 1];
break;
}
}
}
public String toString()
{
return String.valueOf(currentGuess);
}
public void bruteForce()
{
Animation animation = new Animation(){
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
text.setText(attempt);
}
};
animation.setRepeatCount(Animation.INFINITE);
text.startAnimation(animation);
new Thread(){
#Override
public void run() {
running = true;
while(running)
if (attempt.equals(password))
{
text.setText(attempt);
this.stop();
}
attempt = toString();
text.setText(attempt);
increment();
}
}.start();
}
#Override
protected void onStop() {
super.onStop();
running = false;
}
public void BruteForceTest()
{
Arrays.fill(currentGuess, charset[0]);
}
// created automatically
private void ShowMessage(String _s) {
Toast.makeText(getApplicationContext(), _s, Toast.LENGTH_SHORT).show();
}
private int GetRandom(int _minValue ,int _maxValue){
Random random = new Random();
return random.nextInt(_maxValue - _minValue + 1) + _minValue;
}
public ArrayList<Integer> getCheckedItemPositionsToArray(ListView _list) {
ArrayList<Integer> _result = new ArrayList<Integer>();
SparseBooleanArray _arr = _list.getCheckedItemPositions();
for (int _iIdx = 0; _iIdx < _arr.size(); _iIdx++) {
if (_arr.valueAt(_iIdx))
_result.add(_arr.keyAt(_iIdx));
}
return _result;
}
}
Your problem lies here
new Thread(){
#Override
public void run() {
running = true;
while(running)
if (attempt.equals(password))
{
text.setText(attempt);
this.stop();
}
attempt = toString();
text.setText(attempt);
increment();
}
}.start();
You can only update an UI element from the main thread. If you want to do it likes this you need to wrap text.setText(attempt) with a handler that posts it to the main thread. e.g.
new Handler(Looper.getMainLooper()).post(new Runnable(){
void run() {
text.setText(attempt);
}
});
Looper.getMainLooper() (docs) will get the main application thread which the handler then posts the Runnable to .
if (attempt.equals(password))
{
getActivity().runOnUiThread(new Runnable()
{
#Override
public void run()
{
text.setText(attempt);
}
});
this.stop();
}
Similarly wherever you are changing ui elements like setting text or changin colors do it in runOnUithread as I did above.
I'm tring to build an simple android game.
Users answer the questions, when the answer is correct, it is continue..
I want to add time control for each answer.
I tried to add handler function, but I didn't.
My Code;
import java.util.Collections;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class EasyGameActivity extends Activity {
public int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_easygame);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
finishScreen();
}
}, 5000);
startGame();
}
private void startGame() {
// TODO Auto-generated method stub
Button b1 = (Button)findViewById(R.id.answer_one);
Button b2 = (Button)findViewById(R.id.answer_two);
Button b3 = (Button)findViewById(R.id.answer_three);
Button b4 = (Button)findViewById(R.id.answer_four);
Random number = new Random();
int first = number.nextInt(100)+1;
int second = number.nextInt(100)+1;
int answer = first + second;
int rnd1 = answer + 1;
int rnd2 = answer + 2;
int rnd3 = answer - 1;
final String a = Integer.toString(answer);
String b = Integer.toString(rnd1);
String c = Integer.toString(rnd2);
String d = Integer.toString(rnd3);
((TextView) findViewById(R.id.display)).setText(Integer.toString(first) + '+' + Integer.toString(second));
List<Button> buttons = Arrays.asList(b1, b2, b3, b4);
List<String> texts = Arrays.asList(a, b, c, d);
Collections.shuffle(texts);
int i = 0;
OnClickListener onClick = new OnClickListener() {
public void onClick(View view) {
Button button = (Button) view;
String value = (String) button.getText();
if(value == a) {
checkTrue();
} else {
finishScreen();
}
}
};
for(Button button : buttons) {
button.setText(texts.get(i++));
button.setOnClickListener(onClick);
}
}
private void checkTrue() {
score++;
((TextView) findViewById(R.id.score)).setText(Integer.toString(score));
startGame();
}
private void finishScreen() {
score = 0;
startActivity (new Intent("com.bsinternet.mathfast.RESTARTGAMESCREEN"));
finish();
}
}
How can I add time control. Thanks.
This bit of code doesn't look right
if(value == a) {
checkTrue();
} else {
finishScreen();
}
You should be using equals() to check for String equality. At the moment you are checking only object equality, which will evaluate to False, and the code will never call checkTrue().
Do this instead:
if(value.equals(a) {
checkTrue();
} else {
finishScreen();
}
I'm trying to start another activity in my main activity using this method:
public void switchToRead(){// Switches to the reading view which displays the text that the tts engine reads off.
Intent intent = new Intent(getApplicationContext(),ReadOut.class);
intent.putExtra("response", res);
startActivity(intent);
}
This starts the following class:
package com.example.webview;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
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;
TextToSpeech tts;
protected void onPreExecute()
{
System.out.println("Pre-execute");
}
#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));
System.out.println("START");
tts = new TextToSpeech(this, this);
}
#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);
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 = "";
int k = 0;
if(i != 0){
k = i-1;
}
leftToRead = null;
for(int j = k; j < sentences.length; j++){
leftToRead += sentences[j];
}
return leftToRead;
}else{
i--;
System.out.println("Sleeping");
System.out.println("Speaking : " + tts.isSpeaking());
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
if(i == sentences.length - 1){
return "Message 001: Complete";
}
}
return null;
}
#Override
public void onInit(int arg0) {
System.out.println("speakFull");
leftToRead = speakFull(res);
}
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
}
}
After the ReadOut class is started one of a couple things can happen,
either the screen turns black, the text to speech begins reading, and the app is telling me it's not responding, OR it shows me the view for ReadOut, reads in text to speech, and then tells me it's not responding.
I'm really confused as to why this is happening, and any insight would be appreciated.
I don't know anything about using TTS but I can tell you that this line is probably causing a problem
Thread.sleep(1000);
It appears you are calling it on the UI Thread which isn't a good idea. You need to use a background Thread and update it with something like runOnUiThread() or AsyncTask or you could use a Handler.
Hey guys I know there are many java programs for the factorial of a number...but I am facing problem with android. Following is my code....Thanks
package com.droidacid.apticalc.aptitudes;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.droidacid.apticalc.R;
public class AptiFactorial extends Activity implements android.view.View.OnClickListener{
EditText number;
TextView answer;
Button calculate;
long factorial = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.apti_factorial);
initialize();
calcFactorial();
}
private void initialize() {
number = (EditText) findViewById(R.id.et_apti_number);
answer = (TextView) findViewById(R.id.tv_apti_answer);
calculate = (Button) findViewById(R.id.b_apti_calc);
calculate.setOnClickListener(this);
}
private void calcFactorial() {
if (number.getText().toString().equals("")) number.setText("0");
int num = Integer.parseInt(number.getText().toString());
for(int i = 1; i<=num; i++){
factorial = i * factorial;
}
}
#Override
public void onClick(View v) {
calcFactorial();
answer.setText("Factorial of " + number.getText().toString() + " is : " + factorial);
}
}
This is my code and I need to know a way around for setting the hint instead of 0, but if I remove if (number.getText().toString().equals("")) number.setText("0");
then getting NullPointerException...
Also on the first go its calculating correctly but If I calculate again then getting wrong answer. I think some loop issue because I am directly using the value of factorial.
Please help thanks
Forget all that equal stuff, cover all basis and do it like this:
package com.droidacid.apticalc.aptitudes;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.droidacid.apticalc.R;
public class AptiFactorial extends Activity implements android.view.View.OnClickListener{
EditText number;
TextView answer;
Button calculate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.apti_factorial);
initialize();
}
private void initialize() {
number = (EditText) findViewById(R.id.et_apti_number);
number.setHint("Enter number to be factorialized :P")
answer = (TextView) findViewById(R.id.tv_apti_answer);
calculate = (Button) findViewById(R.id.b_apti_calc);
calculate.setOnClickListener(this);
}
private long calcFactorial() {
long factorial = 1;
try {
factorial = Long.parseLong(number.getText().toString());
for(int i=factorial-1; i>0; i--){
factorial = i * factorial;
}
} catch (NumberFormatException e) {
Toast.makeText(this, "Incorrect Input", Toast.LENGTH_LONG).show();
} finally {}
return factorial;
}
#Override
public void onClick(View v) {
answer.setText("Factorial of " + number.getText().toString() + " is : " + calcFactorial());
}
Do something like.
private void calcFactorial() {
int num = 0;
if (!number.getText().toString().equals(""))
num = Integer.parseInt(number.getText().toString());
for(int i = 1; i<=num; i++){
factorial = i * factorial;
}
}
Rather than using
(number.getText().toString().equals("")) number.setText("0");
Use
(number.getText().length==0) number.setText("0");
** first go its calculating correctly but If I calculate again then getting wrong answer**
try like this
private void calcFactorial() {
factorial = 1;///Check out the line..
int num = 0;
if (!number.getText().toString().equals(""))
num = Integer.parseInt(number.getText().toString());
for(int i = 1; i<=num; i++){
factorial = i * factorial;
}
}
You need to make sure variable factorial is reinitialise to 1 .. for getting factorial for next number..
private void fact_isClicked(View view) {
if(textField.length()>0){
int ifac = Integer.parseInt(textField.getText().toString());
int fact = factorial(ifac);
tvsec.setText(String.valueOf(fact));
textField.setText(ifac+"!");
}}
I'm working on a simple game. The idea of the first round is that, there are 26 buttons (images) on the first activity - english alphabet and I want to make it pronounce on button click. For example, when I press "a" button, it must say "a". How can I get the ID of each button, then string of it and give it to speak() method as a parameter? THANKS IN ADVANCE !
Code is here:
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Vibrator;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import java.util.Locale;
import java.util.Random;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
public class FirstActivity extends Activity {
/** Called when the activity is first created. */
TextToSpeech ttx;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firstact);
ttx = new TextToSpeech(
FirstActivity.this,
new TextToSpeech.OnInitListener() {
public void onInit(int status) {
// TODO Auto-generated method stub
if(status !=TextToSpeech.ERROR){
ttx.setLanguage(Locale.US);
}
}
});
TableLayout table = (TableLayout) findViewById(R.id.table);
String alphabet = "abcdefghijqlmnopqrstuvwxyz";
int pos = 0;
for (int i = 0; i < 7; i++) {
TableRow row = new TableRow(this);
for (int j = 0; j < 4; j++) {
if (pos == 26) {
break;
}
Button but = new Button(this);
/*but.setOnClickListener(btnListener);*/
but.setText(Character.toString(alphabet.charAt(pos++)));
but.setHeight(80);
but.setWidth(70);
but.setBackgroundResource(R.drawable.burti);
row.addView(but);
but.setId(pos);
but.setOnClickListener((OnClickListener) this);
table.addView(row);
}}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
if(ttx != null){
ttx.stop();
ttx.shutdown();
}
super.onPause();
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
String pressed = but.getText().toString(); //error here....
ttx.speak(pressed, TextToSpeech.QUEUE_FLUSH, null);
}
}
I made a working example: http://frank.anemaet.nl/android/TalkingButtons.zip
Here is a snippet of the working code:
for (int i = 0; i < alphabet.length(); i++)
{
TableRow row = new TableRow(this);
Button but;
but = new Button(this);
but.setText(Character.toString(alphabet.charAt(i)));
but.setHeight(button_width);
but.setWidth(button_height);
but.setId(i);
but.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
performClick(v);
}
});
row.addView(but);
table.addView(row);
}
...
public void performClick(View arg0){
Button tv = (Button)findViewById(arg0.getId());
String pressed = tv.getText().toString();
ttx.speak(pressed, TextToSpeech.QUEUE_FLUSH, null);
}
Your onInit() method has to do more, like handle when the user does not have the language data installed.
See this code for a helper class.