Android Switching Activities Black Screen - android

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.

Related

Closing Android Game After 5 Seconds

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();
}

Android: How to wait for an input from an editText

I am having a problem with a hangman game that I made for android. I have made a version for the computer and used the code on the android version. I made all the necessary changes to print etc. The program on android just loops through everything until you lose. How can I make it wait for an input from an editText before continuing? Note:More code can be given if needed.
package com.aimobile.hangman;
import java.util.Arrays;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity{
protected static char in;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//gui
final EditText input = (EditText) findViewById(R.id.input);
EditText hang = (EditText) findViewById(R.id.hang);
hang.setEnabled(false);
Button guess = (Button) findViewById(R.id.guess);
//Begin Hangman
int nchar = 5;
char[] word;
word = new char[nchar];
word[0] = 'h';
word[1] = 'e';
word[2] = 'l';
word[3] = 'l';
word[4] = 'o';
char[] arinput;
arinput = new char[nchar];
arinput[0] = '*';
arinput[1] = '*';
arinput[2] = '*';
arinput[3] = '*';
arinput[4] = '*';
int lives = 5;
while (lives>0){
hang.append("Enter leter:");
guess.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity.in = input.getText().charAt(0);
}
});
boolean wrong=true;
for(int k=0; k<= nchar-1; k++){
if(arinput[k]==in){
hang.append("You already have this");
wrong=false;
}
else if(word[k]==in){
arinput[k]=in;
wrong=false;
}
}
hang.append(Arrays.toString(arinput));
boolean finish=true;
for(int k=0; k<= nchar-1; k++){
if(word[k]!=arinput[k]){
finish=false;
}
}
if(finish){
hang.append("You win");
System.exit(0);
}
if(wrong){
lives--;
hang.append("You have "+ lives +" lives left");
}
}
hang.append("You lose");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Why not set an addTextChangedListener on your EditText object?
Set addTextChangedListener in a function Android
what about this:
if(textview != null || !textview.getText().equals(""))
{
MainActivity.in = input.getText().charAt(0);
}
You could put a toast message up if it was clicked and it is empty if you wanted. in an if/else statement.
Checkout ontextchangelistener.
You can add this listener to edittext and then on call back add your code.

What is the correct way implement switch case statement in Android?

It didn't showing up any error. however when I run my application, there is no result appear from my listView. I think,the mistake is because of i didn't use the correct way doing switch case statement. here is my code.
QuickSearch.java
package com.example.awesome;
import java.io.IOException;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.SQLException;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class QuickSearch extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
//-------------------------------------------------------------------------
// Initiate database data
initiateDb();
//---------------------------------------------------------------------------
// Declaration of view
final Button qsfaculty, qscollege;
super.onCreate(savedInstanceState);
setContentView(R.layout.quick_search);
//---------------------------------------------------------------------------
// Get reference
qsfaculty = (Button) this.findViewById(R.id.button1);
qsfaculty.setOnClickListener(this);
qscollege = (Button) this.findViewById(R.id.button2);
qscollege.setOnClickListener(this);
}
public void onClick(View v) {
char ch = 0;
View qsfaculty = null;
View qscollege = null;
if(v == qsfaculty){
ch = 'a';
}
else if (v == qscollege)
{ch = 'b';}
Intent i = new Intent(this,SearchLocation.class);
i.putExtra("value",ch);
startActivity(i);
}
//---------------------------------------------------------------------------
// Initiate database data
public void initiateDb() {
DatabaseHandler myDbHandler = new DatabaseHandler(this);
try {
myDbHandler.createDataBase();
}
catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHandler.openDataBase();
}
catch(SQLException sqle) {
throw sqle;
}
Log.d("Initiate", "UKM Location Count: " + myDbHandler.getUkmLocationCount());
myDbHandler.close();
}
//------------------------------------------------------------------------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quick_search, menu);
return true;
}
}
SearchLocation.java
package com.example.awesome;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class SearchLocation extends ListActivity {
//------------------------------------------------------------------
// Declaration
public static UkmLocation selectedPOI = null;
final DatabaseHandler db = new DatabaseHandler(this);
private EditText filterText = null;
ArrayAdapter<String> adapter = null;
final ArrayList<String> results = new ArrayList<String>();
final ArrayList<String> results_id = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_location);
final Intent c = new Intent(SearchLocation.this, LocationDetail.class);
//------------------------------------------------------------------
// Link editText to layout item
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
//------------------------------------------------------------------
// Reading Poi
Log.d("Reading", "Reading all Kategori ..");
int value = 0;
switch(value) {
case 'a' :
List<UkmLocation> faculty = db.getCategoryFaculty();
for(UkmLocation k : faculty) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
case 'b' :
List<UkmLocation> college = db.getCategoryCollege();
for(UkmLocation k : college) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
}
//------------------------------------------------------------------
// Set list arrayAdapter to adapter
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textView1,results);
setListAdapter(adapter);
//------------------------------------------------------------------
// Set ListView from ListActivity
ListView lv = getListView();
lv.setTextFilterEnabled(true);
//------------------------------------------------------------------
// Set click event from listView
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
Log.d("test", "position:" + position);
Log.d("test", "actualname:" + db.getUkmLocationByName(adapter.getItem(position)).getName());
// String poiID = results_id.get(position);
String poiID = db.getUkmLocationByName(adapter.getItem(position)).getID();
setSelectedPoi(poiID);
startActivity(c);
}
});
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
public UkmLocation getSelectedPoi() {
return selectedPOI;
}
public void setSelectedPoi(String poiID) {
selectedPOI = db.getUkmLocation(poiID);
Log.d("test2", "_id:" + db.getUkmLocation(poiID).getID());
Log.d("test2", "Name:" + db.getUkmLocation(poiID).getName());
// Closing db
db.close();
}
}
i think,the if else statement inside QuickSearch.java is already correct. the problem at the switch case statement at SearchLocation.java
please help me solve this.
int value = 0;
switch(value) {
You are setting the value over which you switch to 0 so it is equivalent to doing switch(0) {...
Find out what that value is supposed to be and initialise it properly.
Also, value is of type int but your switch uses chars ('a', 'b'), so you need to either have value be a char and initialise it properly or have it be an int, initialise it properly and change your switch cases to use ints.
First you do int value = 0; so value is 0. So it is not 'a' nor 'b'.
You have to get the value from the intent as you put it in extras. i.putExtra("value",ch);
something like
char value;
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getIntgetChar("value");
}
here, i already solve my problem..
QuickSearch.java
public void onClick(View v) {
int ch = 0;
/*View qsfaculty = null;
View qscollege = null;*/
if(v == qsfaculty){
ch = '1';
}
else if (v == qscollege)
{ch = '2';}
Intent i = new Intent(this,SearchLocation.class);
i.putExtra("value",ch);
startActivity(i);
}
SearchLocation.java
Bundle extras = getIntent().getExtras();
int value = extras.getInt("value");
switch(value) {
case '1' :
List<UkmLocation> faculty = db.getCategoryFaculty();
for(UkmLocation k : faculty) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
case '2' :
List<UkmLocation> college = db.getCategoryCollege();
for(UkmLocation k : college) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
}

Eclipse Android App using JSoup, always ending within the Catch

I have some code that uses JSoup and connects to a website successfully in JAVA.
I am trying to duplicate the exact same thing (as a learning experience) on the Android.
I am using Eclipse.
Within my activity_main.xml I have 3 buttons and a text field.
I do not have any errors within my JAVA code and have confirmed it still works within JAVA (running in Netbeans)
I have my JSoup jar within the libs folder ~ that was an issue that took a little while to find.
I have placed some editText.setText(“Here”); to see where the code gets.
I have a message immediately below my doc = JSoup.connect(“http://www.Google.com”).get();
I never get that message.
Likewise I have the same message within my catch routine – I am always getting into the catch routine, meaning I have a problem.
I have tried this two ways – with the android emulator and with my phone attached through the USB cable. I get the same result – the “app” runs fine but displays the message found within the catch{}.
I am at a loss since the exact code works fine within Netbeans / regular JAVA.
Here is my code:
package com.example.duckriver;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.jsoup.helper.Validate;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
int counter;
Button Button1;
Button SummaryStats;
TextView display;
TextView editText;
String dataread = null;
String high = "High:";
String low = "Low:";
String filename = null;
int index = 0;
int startindex = 0;
int lastindex = 0;
int length = 0;
char[] CharArray = new char[1000];
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
counter = 0;
Button1 = (Button) findViewById(R.id.button1);
SummaryStats = (Button) findViewById(R.id.buttonSummaryStats);
display = (TextView) findViewById(R.id.tvMainDisplay);
editText = (TextView) findViewById(R.id.editText);
Button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
//counter++;
Document doc;
try{
doc=Jsoup.connect("http://www.Google.com").get();
editText.setText("Here");
//get Title
//String title = doc.title();
//System.out.println("Title: "+title);
//dataread = doc.body().text(); // "An example link"
Element link = null;
}//end try
catch(Exception ex){
ex.printStackTrace();
editText.setText("Error");
//((TextView)findViewById(R.id.tv)).setText("Error");
}// end catch
}
});
SummaryStats.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
counter = counter*counter;
}
});
return true;
}
}
I am at a loss. Help?
Thanks.
You need download document with Asyncronous task or Android will throw exception. Try this:
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
counter = 0;
Button1 = (Button) findViewById(R.id.button1);
SummaryStats = (Button) findViewById(R.id.buttonSummaryStats);
display = (TextView) findViewById(R.id.tvMainDisplay);
editText = (TextView) findViewById(R.id.editText);
Button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
downloadDocTask task = new downloadDocTask();
task.execute("www.google.com");
}
});
SummaryStats.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
counter = counter*counter;
}
});
return true;
}
private class downloadDocTask extends AsyncTask<String, Void, Document>{
String urldisplay;
#Override
protected Document doInBackground(String... urls) {
urldisplay = urls[0];
Document doc = null;
try {
doc = Jsoup.connect(urldisplay).timeout(10*1000).get();
} catch (IOException e) {
e.printStackTrace();
}
return doc;
}
#Override
protected void onPostExecute(Document result) {
if(result != null){
Log.i(TAG, "downloadDocTask.onPostExcecute Document Download complete");
buildHtml(result);
}
else{
Log.i(TAG, "downloadDocTask.onPostExcecute Document == null");
}
}
}
public void buildHtml(Document doc){
// Parse document here
String title = doc.title();
}

TextToSpeech - Android

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.

Categories

Resources