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)){
Related
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 want to make a button appear in the MenuActivity layout but the deciding if statement is in the CapitalReceiver class. I've tried adding 'static' to various variables but it didn't work. Please help!
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.text.format.DateFormat;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
public class MenuActivity extends Activity {
String status;
Boolean verified = false;
String textColour = "#000000";
TextView mTvCapital;
ArrayAdapter<String> mAdapter;
Intent mServiceIntent;
CapitalReceiver mReceiver;
IntentFilter mFilter;
String country = "7ec47294ff3d8b74";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_layout);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Button IDButton = (Button) findViewById(R.id.getIt);
Button RefreshButton = (Button) findViewById(R.id.refresh);
long updateTimeMillis = System.currentTimeMillis();
String updateTime = (String) DateFormat.format("hh:mm", updateTimeMillis);
//If application has been submitted//
if(preferences.contains("first_middle_store") & !(verified)) {
status = "Status: Application pending. Last updated: " + updateTime;
IDButton.setVisibility(View.GONE);
RefreshButton.setVisibility(View.VISIBLE);
textColour = "#000000";
}
//If application has not been submitted
else {
status = "Status: Application not yet submitted";
IDButton.setVisibility(View.GONE);
RefreshButton.setVisibility(View.GONE);
textColour = "#000000";
}
TextView text=(TextView)findViewById(R.id.application_status);
text.setTextColor(Color.parseColor(textColour));
text.setText(status);
Button btnNextScreen = (Button) findViewById(R.id.verify);
//Listening to verify event
btnNextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen = new Intent(getApplicationContext(), VerifyActivity.class);
startActivity(nextScreen);
}
});
Button btnNextScreen2 = (Button) findViewById(R.id.how);
//Listening to HowItWorks event
btnNextScreen2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen2 = new Intent(getApplicationContext(), HowItWorksActivity.class);
startActivity(nextScreen2);
}
});
//Listening to IDbutton event
IDButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen3 = new Intent(getApplicationContext(), IDActivity.class);
startActivity(nextScreen3);
}
});
}
#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, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.menu_layout, container, false);
return rootView;
}
}
public void refresh(View view) {
// Getting reference to TextView
mTvCapital = (TextView) findViewById(R.id.tv_capital);
mTvCapital.setText("hello");
// Creating an intent service
mServiceIntent = new Intent(getApplicationContext(), CapitalService.class);
mServiceIntent.putExtra(Constants.EXTRA_ANDROID_ID, country);
// Starting the CapitalService to fetch the capital of the country
startService(mServiceIntent);
// Instantiating BroadcastReceiver
mReceiver = new CapitalReceiver();
// Creating an IntentFilter with action
mFilter = new IntentFilter(Constants.BROADCAST_ACTION);
// Registering BroadcastReceiver with this activity for the intent filter
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(mReceiver, mFilter);
}
// Defining a BroadcastReceiver
private static class CapitalReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String capital = intent.getStringExtra(Constants.EXTRA_APPROVAL);
if(capital == "YES") {
//status = "Status: Application Approved";//
//IDButton.setVisibility(View.VISIBLE);//
}
else if(capital == "NO"){
//status = "Status: Application Denied";//
}
}
}
}
Just glancing over your code, a possible solution (and perhaps not the best) would be to make the ID Button variable global. You would then instantiate it in the onCreate whilst still allowing it to be manipulated in other classes in this MenuActivity.
I hope this helps.
Consider:
package com.example.practicealpha;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity implements OnClickListener {
Button next,previous;
ImageView image;
Integer[] id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
id[0] = R.drawable.aa;
id[1] = R.drawable.bb;
id[2] = R.drawable.cc;
id[3] = R.drawable.dd;
next=(Button)findViewById(R.id.buttonNext);
previous=(Button)findViewById(R.id.buttonPrevious);
image=(ImageView)findViewById(R.id.imageView1);
// image.setImageDrawable(id[0]);
// image.setImageResource(id[i]);
/*
next.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v)
{
if (i<=3)
{
i++;
image.setImageResource(id[i]);
if(i==4)
next.setEnabled(false);
}
}
});
previous.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v)
{
if(i>=1)
{
i--;
image.setImageResource(id[i]);
if(i==0)
next.setEnabled(false);
}
}
});
*/
}
#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;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
id[0] = R.drawable.aa;
This line is causing my app to stop forcefully. How can I fix this problem?
I am trying to intialise an integer array with images id and then trying to go through the image listed in drawable folder.
Change
Integer[] id;
to
int[] id;
You have to initialize the ids for the size:
int[] id = new int[size];
You cannot use the id array directly. Initialise it first:
id[0] = R.drawable.aa;
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.
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