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.
Related
I'm trying to write code so that when the hints option is checked in settings it should display hints, but when I do s it says there is no getContext() method defined. What will this method do and where will i have to define this ?
Here is my code for the logic of my maths app:
package com.gamesup.braingame;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Easy extends Activity implements OnClickListener{
EditText display;
// This Array says , I am an array that holds arrays
String [][] multiArray = {{"4 + 5 = ", "9"},
{"20 * 3 - 1 = ","59"},
{"99 - 9 = ","90"},
{"50 / 2 + 18 = ","43"},
{"9 * 8 = ","72"},
{"4 + 20 - 20 = ","4"},
{"75 / 5 = ","15"},
{"99 - 1 * 3 = ","96"},
{"75 + 25 = ","100"}};
TextView displayExpression;
TextView displayAnswer;
TextView setAnswer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.easy);
display = (EditText)findViewById(R.id.displayText);
display.setText("?");
displayExpression = (TextView) findViewById(R.id.expression);
displayAnswer = (TextView) findViewById(R.id.answer_status);
setAnswer = (TextView) findViewById(R.id.answer);
Button generate = (Button) findViewById(R.id.random_gen);
generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random ranGenerate = new Random ();
int random = ranGenerate.nextInt(multiArray.length) ;
// Fetch your random question
String Rquestion = multiArray[random][0];
displayExpression.setText(Rquestion);
displayAnswer.setText("");
setAnswer.setText("?");
}
});
}
static boolean isEmpty = true;
public void num_Clicked(View v){
Button btn = (Button) findViewById(v.getId());
//getting the button object and using a view to get the id of the buttons
if (v.getId()== R.id.del_button){
String s = display.getText().toString();
s = s.substring(0, s.length() - 1);
display.setText(s);
return;
}
if(isEmpty){
display.setText(btn.getText());
isEmpty = false;
}
else{
display.append(btn.getText().toString());
}
}
//xml attribute to views called android:onclick, that can be used to handle
//clicks directly in the view's activity without need to implement any interface.
public void hash_Clicked(View v){
// Get the Answer from your EditText
String answer = display.getText().toString();
setAnswer.setText(answer);
// Using a for loop iterate on the base index
for(int i = 0; i < multiArray.length ; i++)
{
// if the answer is in position 1 of Array [i]
if(answer.equals(multiArray[i][1]))
{
// We have found the answer, Congratulate the User
displayAnswer.setTextColor(getResources().getColor(R.color.green));
displayAnswer.setText("CORRECT");
break;
}else{
// Tell them how bad they are since they can't solve simple equations!
displayAnswer.setTextColor(getResources().getColor(R.color.red));
displayAnswer.setText("INCORRECT");
//this is where i am getting the error
if(Prefs.getHints(getContext())){
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.brain_game, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.settings:
startActivity(new Intent(this,Prefs.class));
return true;
// more items go here if any
}
return false;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
And the Prefs class:
package com.gamesup.braingame;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.os.Bundle;
import android.content.Context;
public class Prefs extends PreferenceActivity {
//option names and default values
private static final String OPT_HINTS = "hints";
private static final boolean OPT_HINTS_DEF = true;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
/**Get the current value of the hints option*/
public static boolean getHints (Context context){
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(OPT_HINTS, OPT_HINTS_DEF);
}
}
Just use this, you already are in an Activity, which is a Context:
if(Prefs.getHints(this)){
Don't need to use other context because if you are calling that function in your Activity then you just need to pass this or yourActivityName.this which are also Context.
So change
if(Prefs.getHints(this)){
or
if(Prefs.getHints(YourActivityName.this)){
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.
The code works fine it takes the contant split when there is a space and replace
what ever word the user enter to the word in V2
the problem is when i put the IF statment to check the
word the user entered it does not work whats wrong with the if ?
package com.example.split;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText te1 = (EditText)findViewById(R.id.t1);
final EditText te2 = (EditText)findViewById(R.id.t2);
final Button b = (Button)findViewById(R.id.b1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//imva.setImageResource(R.id.b1);
String t=te1.getText().toString();
String[] t1= t.split(" ");
if (t1[0] == "hello")
{
String v1= t1[0];
String v2 = " true ";
String a = v1.replaceAll(v1, v2);
te2.setText(a);
}
}
});
}
#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;
}
}
Change
if (t1[0] == "hello"){...}
to
if (t1[0].equals("hello")){...}
1)
if (t1[0] == "hello")
don't ever compare Strings and Objects like that. That way you can compare only object references, not the contents
Java String.equals versus ==
2)
v1.replaceAll(v1, v2);
Takes first argument as a regular expression. And I doubt that is what you want.
I bet you want
v1.replace(v1, v2);
http://developer.android.com/reference/java/lang/String.html#replace%28java.lang.CharSequence,%20java.lang.CharSequence%29
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();
}
I designed a custom keyboard using ImageButtons for Android (using Eclipse). I want to click on a button to write on the text, but every time I click a button, it resets the text, erasing what I previously wrote.
How can I get it to continue writing from the previous text?
This is a basic bit of my code, using two buttons and a text field.
package com.example.nonachan;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends Activity {
char g;
char h;
int i = 0;
//char buf[] = new char[10];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText t =(EditText)findViewById(R.id.t1);
ImageButton n = (ImageButton)findViewById(R.id.b1);
n.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
g = 'd';
// buf[i] = 'd';
t.setText( "" + g);
i++;
}
});
ImageButton a = (ImageButton)findViewById(R.id.b2);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// buf[i] = 'h';
h = 'h' ;
t.setText( "" +h);
i++;
}
});
Button l = (Button)findViewById(R.id.b3);
l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
}
#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;
}
}
t.setText( "" + g);
The above line in your code says to set t's text to "" + g which is equal to "d". It will never append the text since you don't tell it to.
Try adding the existing text in the text field:
t.setText(t.getText().toString() + g);
And you'll have to do the same with t.setText( "" +h); as well.