Android Eclipse changing text on a snake game - android

How do i go to the next text when my snake eat a food? (When the snake eat the food, the text will change from testing to success.) I'm using the snake game provided by eclipse. This is the code i have done so far. I am doing this for my project so i appreciate all the help i can get.
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Snake extends Activity {
/**
* Constants for desired direction of moving the snake
*/
public static int MOVE_LEFT = 0;
public static int MOVE_UP = 1;
public static int MOVE_DOWN = 2;
public static int MOVE_RIGHT = 3;
private static String ICICLE_KEY = "snake-view";
private SnakeView mSnakeView;
/**
* Called when Activity is first created. Turns off the title bar, sets up the content views,
* and fires up the SnakeView.
*
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.snake_layout);
init();
mSnakeView = (SnakeView) findViewById(R.id.snake);
mSnakeView.setDependentViews((TextView) findViewById(R.id.text),
findViewById(R.id.arrowContainer), findViewById(R.id.background));
if (savedInstanceState == null) {
// We were just launched -- set up a new game
mSnakeView.setMode(SnakeView.READY);
} else {
// We are being restored
Bundle map = savedInstanceState.getBundle(ICICLE_KEY);
if (map != null) {
mSnakeView.restoreState(map);
}
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
// Store the game state
outState.putBundle(ICICLE_KEY, mSnakeView.saveState());
}
private int currentQuestion;
private String [] questions;
private TextView questionView;
public void init() {
questions = new String[]{"testing","success"};
currentQuestion = -1;
questionView = (TextView) findViewById(R.id.QuestionTextView);
showQuestion();
}
public void showQuestion() {
currentQuestion++;
if(currentQuestion == questions.length)
currentQuestion =0;
questionView.setText(questions[currentQuestion]);
}
}

After checking out the source code (which I did here: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android-apps/4.2_r1/com/example/android/snake/SnakeView.java), I dont think it's possible to add this functionality without altering the source code...
However, if u want to edit the source to make it work, I would suggest the following:
create an interface to use as a listener
public interface AppleEatenListener{
public void appleEaten(int size);
}
Then add a variable of this interface to the SnakeView class
private AppleEatenListener mAppleEatenListener;
Create a setter in the SnakeView class to set the mAppleEatenListener
public void setAppleEatenListener(AppleEatenListener listener){
this.mAppleEatenListener = listener;
}
After that, make your way down to the updateSnake() method in the SnakeView class and find the following piece of code (consider using ctrl+f (search function)):
This snippet comes from the current source code:
// except if we want the snake to grow
if (!growSnake) {
mSnakeTrail.remove(mSnakeTrail.size() - 1);
}
And here we want to add, that if the snake should grow, we call the AppleEatenListener's function appleEaten(), like so:
// except if we want the snake to grow
if (!growSnake) {
mSnakeTrail.remove(mSnakeTrail.size() - 1);
}
else{
if(mAppleEatenListener != null){
mAppleEatenListener.appleEaten(mSnakeTrail.size());
}
}
Now, we should return to your own Snake class and add the following in onCreate():
mSnakeView.setOnAppleEatenListener(new AppleEatenListener() {
#Override
public void appleEaten(int size) {
showQuestion();
//size is the current size of the snake after the apple was eaten
}
});
Note that I've added that the listener requests a "size" parameter, I'm supposing it could be useful to know the size of the snake after it has eaten an apple, since I didn't see a function for requesting the size of the snake in the API either...
I have not tested this code, but I hope this helps u at least a little

Related

I need an efficient way of duplicating an existing activity in Android Studio

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
public int currentQuestion;
public String[] questions;
public String[] answers;
int score = 0;
Button answerButton;
Button questionButton;
Button homeButton;///NEW ****
public TextView questionView;
public TextView answerView;
public EditText answerText;
public TextView scoreText;
public void main() {
questions = new String[]{"Type Yes", "Type No", "Type And", "Type The"}; /*Array of Hard Coded Questions*/
answers = new String[]{"Yes", "No", "And", "The",}; /*Array of Hard Coded Answers to indexed to match the questions*/
currentQuestion = -1; /*This will index the questions to be used*/
answerButton = (Button) findViewById(R.id.AnswerButton);
questionButton = (Button) findViewById(R.id.QuestionButton);
homeButton = (Button) findViewById(R.id.HomeButton);
questionView = (TextView) findViewById(R.id.QuestionTextView);
answerView = (TextView) findViewById(R.id.AnswerTextView);
answerText = (EditText) findViewById(R.id.AnswerText);
scoreText = (TextView) findViewById(R.id.ScoreText);
///Check the user inserted answer string against the correct or incorrect answers.... NEEDS VALIDATION....
answerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer();
}
});
///Skips to the next questions
questionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getNextQuestion();
}
});
/// Returns you to the Home screen
homeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, _MainMenu.class));
}
});
}
public void getNextQuestion() {
//1st question so reset everything
if(currentQuestion == -1)
{
setupQuiz();
}
currentQuestion++;
//Check to see if the end of the questions has been reached
if(currentQuestion == questions.length)
{
endQuiz();
}
else
{
questionView.setText(questions[currentQuestion]);
answerText.setText("");
}
}
public void setupQuiz()
{
score = 0;
answerButton.setVisibility(View.VISIBLE);
questionView.setVisibility(View.VISIBLE);
answerText.setVisibility(View.VISIBLE);
answerView.setText("");
questionButton.setText("Skip Question");
}
public void endQuiz()
{
currentQuestion = -1;
answerButton.setVisibility(View.INVISIBLE);
questionView.setVisibility(View.INVISIBLE);
answerText.setVisibility(View.INVISIBLE);
questionButton.setText("Try Again");
scoreText.setText("Final Score: " + score);
}
public void checkAnswer() ///validaion goes here and not in getnextquestion
{
String answer = answerText.getText().toString();
boolean result = answer.equalsIgnoreCase(answers[currentQuestion]);
//answer is correct
if(result == true) {
score += 10; /* ++ will increment the score by 1, +=10 will increment the score by the value added (10)*/
answerView.setText("Correct!");
}/*answerView, text view set to print the string in the event of the correct answer*/
else //answer was wrong
answerView.setText("Incorrect, The answer was " + answers[currentQuestion]); /*answers[currentQuestion] answers reads the answer to the current question in use */
scoreText.setText("Current Score = "+score);
getNextQuestion();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
main();
getNextQuestion();
}
}
I am building a simple Quiz game in Android that currently has a main Menu Activity that links you directly to a quiz activity that will ask you an "x amount of questions". Ultimately I want three difficulty levels for the Quiz. There will be 3 buttons on the home screen that will direct the user to an Easy, Medium or Hard version of the Quiz.
As each activity will be exactly the same other than the actual questions being asked. I was wondering if there is a more efficient way of duplicating the class a couple of times without having to rebuild the user interface and then copy the code into the separate classes.
I attached an example of my code that works perfectly fine so far. The game is very simple and is a learning exercise for me for than anything.
The best way for something like this is to use a single activity.
Every activity makes the application a lot heavier and this is why you usually try to create the smallest number of different activities as possible.
If your pages are pretty much the same you should consider adding a simple value and doing different stuffs based on the value.
On button click, simply add an int value to the intent opening the questions activity (1 = easy, 2 = medium, 3 = hard, or any value you like) with
intent.putExtra("lvl", lvl);
Now, on activity start, call this number retrieving the value from the intent with
int myLvl = getIntent().getIntExtra("lvl", 0);
now simply call a switch:
switch(myLvl){
case 1: doLvl1Stuffs();
break;
case 2: doLvl2Stuffs();
break;
case 3: doLvl3Stuffs();
break;
default: throw new Exception("no lvl found");
break;
Hope this helps, but generally avoid creating more activities than the needed ones
I think the real answer here is the good old "prefer composition over inheritance" mem.
Example: upon "collection" your UI elements; you could create a helper class like
public class QuizButtonManager {
private final Button answerButton;
private final Button questionButton;
private final Button homeButton;
public QuizButtonManager(Button answerButton ... ) {
this.answerButton = answerButton;
...
And then you simply move your setupQuiz() and endQuiz methods into that class.
Then you look into other responsibilities that you have currently forced into your activities. You "cut" them out and put them into distinct classes; thus enabling much simpler "re-use".
The best way is to Create BaseActivity that contains all the Mutual Components and the other activities extend from it and implement their logic
but as you say it's all the same. the difference is the Questions so you don't need to create multiple activities you can use the same activity and set a flag to know what is the current difficulty and set the questions based on it

get value from SpinnerWheel

I'm trying to get the value from Android SpinnerWheel. There are very few post in SO giving answer for this and not one post shows any true information. I found only one link which was a bit descriptive but still didn't have the result I wanted. So if anyone can show me how exactly we can get the value and set it in a TextView, it will be really great
My Code
public class MainActivity extends Activity {
TextView textvalue;
String value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textvalue = (TextView)findViewById(R.id.textvalue);
final AbstractWheel mins = (AbstractWheel) findViewById(R.id.mins);
NumericWheelAdapter minAdapter = new NumericWheelAdapter(this, 0, 59, "%02d");
minAdapter.setItemResource(R.layout.wheel_text_centered_dark_back);
minAdapter.setItemTextResource(R.id.text);
mins.setViewAdapter(minAdapter);
//OnWheelChangedListener listener = null;
//mins.addChangingListener(listener);
}
private OnWheelChangedListener changedListener = new OnWheelChangedListener() {
public void onChanged(AbstractWheel wheel, int oldValue, int newValue) {
String value = String.valueOf(newValue);
textvalue.setText(value);
}
};
}
.
The only thing I see is, that You havenĀ“t added the listener to Your wheel, because You had commented it out:
//mins.addChangingListener(listener);
It must be:
mins.addChangingListener(changedListener);

Set TextView text to what is returned from function in another class

I'm new to android and I am making an app as part of an assignment, and can't get this function to return a value - the app closes and I get an error message: "Unfortunately, APP has stopped".
I have two classes, one is the MainActivity and one is a class that I am wanting to use to do arithmetic, and they are:
import com.calc.Calculation;
public class MainActivity extends Activity {
private Calculation util;
calculate = (Button) findViewById(R.id.btnCalc);
private TextView tvMultiply;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvMultiply = (TextView) findViewById(R.id.tvMult);
}
btnCalc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tvMiltiply.setText(String.valueOf(util.CalculateMult(4,6)));
}
});
}
and
package com.calc;
public class Calculation{
public int CalculateMult(int numOne, int numTwo)
{
return numOne * numTwo;
}
}
I've tried a few alternatives but to no avail. It's going to be something simple that I am not doing quite right.
Any help appreciated.
Thanks
You need to create instance to the class before acccessing the member.
private Calculation util = new Calculation()
Else make the method in the class as static and access without creating instance.
This would be done by defining the class as:
package com.calc;
public class Calculation{
public static int CalculateMult(int numOne, int numTwo)
{
return numOne * numTwo;
}
}
and calling the method as:
Calculation.CalculateMult(4,6)
You should move the line
calculate = (Button) findViewById(R.id.btnCalc);
to the onCreate() function after you have set the content view. You should also move the assignment of the onClickListener to your button to the onCreate() method.
Finally, you should initialize your Calculation object by using the new operator in onCreate(), i.e:
util = new Calculation();

Non-static variable error in android

So I have a main class and another class that has a variable I need to pull out into the main class. I have tried some of the ways posted on the answered questions like this, but I'm still failing to get it right.
public class Example extends MapActivity
{
public void OnCreate(Bundle savedInstanceState){
final Button bttn = (Button)findViewById(R.id.button1);
bttn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast tulos = Toast.makeText(getBaseContext(),
"Area is: "
+MyItemizedOverlay.alue +""
/*I get the non static variable error here
which I get as it is not yet defined, it will be after the user
inputs values into the program*/
,Toast.LENGTH_LONG);
tulos.show();
}
});
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
int alue;
//irreleveant stuff (I assume)
public void Calc(Geopoint gp, Mapview map){
//there's some stuff before the variable I want to get like other variables
//not relevant for my problem I hope
alue = (int)Math.round(*formula: derived from user input data*)
}
}
So how can I get a value out of my other class, as it doesn't seem to be able to get it now? Or is this maybe an indication of a bigger problem?
There are two way
1 - make alue static but that will show the error that satic variable can't be accesses in non static function Calc so either make function Calcalso static as well or go to point 2
2-try this new MyItemizedOverlay().alue with making alue public as below
public class Example extends MapActivity
{
public void OnCreate(Bundle savedInstanceState){
final Button bttn = (Button)findViewById(R.id.button1);
bttn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast tulos = Toast.makeText(getBaseContext(),
"Area is: "
+new MyItemizedOverlay().alue +"" /<--------------------
/*I get the non static variable error here
which I get as it is not yet defined, it will be after the user has input
values into the program*/
,Toast.LENGTH_LONG);
tulos.show();
}
});
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
public int alue; /<--------------------
//irreleveant stuff (I assume)
public void Calc(Geopoint gp, Mapview map){
//there's some stuff before the variable I want to get like other variables
//not relevant for my problem I hope
alue = (int)Math.round(*formula: derived from user input data*)
}
There is no access modifier for int alue means it is default.
Make it public int alue to be accessible from other classes.
Have a Look At Controlling Access to Members of a Class

onCreate method variables unaccessible?

I'm still struggling to find a clean easy way to load some values in my onCreate method and pass them to another class in order that a game may load and save option settings.
I can successfully retrieve and change values from my other class but the problem is, no matter what I try, variable set in the onCreate method will not carry to the rest of the code.
I take the point that by only showing snipits of the code I may have obscured the problem but my original is far to massive and sprawling to post HOWEVER it was based on a great tutorial by Martin
http://www.droidnova.com/android-3d-game-tutorial-part-i,312.html
So I've returned to first principles and just added the problematic portion to that tutorial code and my problem has been replicated. So here is the complete code:
Vortex.java **
package com.clockworkrobot.vortex;
import android.app.Activity;
import android.os.Bundle;
public class Vortex extends Activity {
private static final String LOG_TAG = Vortex.class.getSimpleName();
private VortexView _vortexView;
private float _red ; // these are the values that actually reach VortexRender class
private float _green = 1f ; // touch the screen, it will turn green.
private float _blue ; // but why don't the variable in my onCreate override these?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_red = 1f; // The test values I want to reach my Vortex Renderer class.
_green = 0f; // to help debug. they should make the screen magenta
_blue = 1f; // Eventually these value will be loaded during onCreate
setRed(_red); // I don't think these are needed
setGreen(_green); // But since the variable within this method
setBlue(_blue); // don't appear to be reaching their target..worth a try
_vortexView = new VortexView(this);
setContentView(_vortexView);
}
public float getRed() {
return _red;
}
public void setRed(float value) {
_red = value;
}
public float getGreen() {
return _green;
}
public void setGreen(float value) {
_green = value;
}
public float getBlue() {
return _blue;
}
public void setBlue(float value) {
_blue = value;
}
}
VortexRender.java**
package com.clockworkrobot.vortex;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
public class VortexRenderer extends Activity implements GLSurfaceView.Renderer {
private static final String LOG_TAG = VortexRenderer.class.getSimpleName();
// Vortex sw = new Vortex();
private Vortex sw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sw = new Vortex();
}
private float _red = 0f;
private float _green = 0f;
private float _blue = 0f;
#Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
// Do nothing special.
}
#Override
public void onSurfaceChanged(GL10 gl, int w, int h) {
gl.glViewport(0, 0, w, h);
}
#Override
public void onDrawFrame(GL10 gl) {
// define the color we want to be displayed as the "clipping wall"
gl.glClearColor(_red, _green, _blue, 1.0f);
// clear the color buffer to show the ClearColor we called above...
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
}
public void setColor(float r, float g, float b) {
_red = sw.getRed(); // Want these to grab the values from my onCreate method
_green = sw.getGreen(); // But instead it's getting the nul values
_blue = sw.getBlue(); // eg values as set above me onCreate.
// _red = r;
// _green = g;
// _blue = b;
}
}
VortexView.java**
package com.clockworkrobot.vortex;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.view.MotionEvent;
public class VortexView extends GLSurfaceView {
private static final String LOG_TAG = VortexView.class.getSimpleName();
private VortexRenderer _renderer;
public VortexView(Context context) {
super(context);
_renderer = new VortexRenderer();
setRenderer(_renderer);
}
public boolean onTouchEvent(final MotionEvent event) {
queueEvent(new Runnable() {
public void run() {
_renderer.setColor(event.getX() / getWidth(), event.getY() / getHeight(), 1.0f);
}
});
return true;
}
}
AndroidManifest.xml**
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.clockworkrobot.vortex"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".Vortex"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
In essence.. What I require is a way to save and recover the current screen colour when the game opens and closes.
Thanks to everyone who has helped so far.
I'm still struggling to find a clean easy way to load some values in my onCreate method and pass them to another class in order that a game may load and save option settings.
Use SharedPreferences -- that is why they are there.
Anyone got any helpful ideas?
Either:
Your other class is not talking to the Activity object you think it is, or
You are not calling the code in the other class that invokes your setter, or
Your activity is being recreated (e.g., configuration change) as part of your testing, or
As #Arnout Engelen notes, you are calling the setter from multiple places and are overwriting what you want, or
Something else, since the code you have above most likely is not really the code from your app, and fake examples like this just cause problems when you go to ask people for help, because you introduce differences between what you're really running and what you're claiming you're running
UPDATE
You are creating a Vortex via new Vortex(). Vortex is an Activity. Never create activities via the constructor. You do not access activities from other activities. Your red/green/blue values need to be in some data model accessible from all your components.
Given your code and comments, I strongly encourage you to first learn Java outside of Android, then learn Android.
I had a similar problem. The solution is easy.
If the setter method is setting an int, initially it must be written as "public int...{} " instead of "public void...{} ".
Then it must return an int variable at the end with the following code line: "return a;" (where a is any int or int variable that has previously been initiated).
Then, whenever you want an int b to get a's number, simply write:
int b = new exampleClassWhereYourMethodIs().setterMethodName();
Hope I helped!

Categories

Resources