Android Java calling method - java

So, I tried to call all the methods from overView but is not working, I tried with "view" in the parentheses and then is constantly crashing when I start the app.... Can someone help, this is the whole code. I tried not to include the first four methods but then is not working the way it's suppose to.
public class MainActivity extends AppCompatActivity {
int health = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void checkQuestionOne(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.question_one_yes:
if(checked)
health += 1;
break;
case R.id.question_one_no:
if(checked)
health -= 1;
break;
}
}
public void checkQuestionTwo(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.question_two_yes:
if(checked)
health += 1;
break;
case R.id.question_two_no:
if(checked)
health -= 1;
break;
}
}
public void checkQuestionThree(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.question_three_yes:
if(checked)
health += 1;
break;
case R.id.question_three_no:
if(checked)
health -= 1;
break;
}
}
public void checkQuestionFour(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.question_four_yes:
if(checked)
health += 1;
break;
case R.id.question_four_no:
if(checked)
health -= 1;
break;
}
}
public void checkQuestionFive() {
EditText gettingQuestionFive = findViewById(R.id.sleep_hours);
int answerQuestionFive = Integer.parseInt(gettingQuestionFive.getText().toString());
if (answerQuestionFive > 7) {
health += 1;
} else if (answerQuestionFive == 7) {
health += 1;
} else {
health -=1;
}
}
private void displayMessage(String message) {
TextView orderSummaryTextView = (TextView) findViewById(R.id.summary);
orderSummaryTextView.setText(message);
}
public void overView(View view){
checkQuestionOne();
checkQuestionTwo();
checkQuestionThree();
checkQuestionFour();
checkQuestionFive();
String Message = health + " is your score. If is 3 or above, you have a healthy life";
displayMessage(Message);
}
}

I think you have forgot to call the overView() method in the onCreate() method of activity. You can call it like this.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Pass your view in argument
overView(View view)
}

Related

Send a value from Mainactivity and display the value in another activity

I am trying to make a simple quiz app and I want to display the score value in another activity(another screen) i.e. when I press the submit button the score activity should open and display the total score.
I have tried using intents but it hasn't worked. I am new at android programming and there could be some silly mistakes.
This is the MainActivity.java file.
package com.example.android.conanquiz;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//Question 1 Methods
public void question1_click(View view) {
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.haibara:
if (checked) {
String correct = "Right Answer";
display_answer1(correct);
score++;
}
break;
default: {
String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q1_o1);
display_answer1(wrong);
}
break;
}
}
private void display_answer1(String answer) {
TextView quantityTextView = (TextView) findViewById(R.id.answer_1);
quantityTextView.setText(answer);
}
//Question 2 Methods
public void question2_click(View view) {
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.true_op:
if (checked) {
String correct = "Right Answer";
display_answer2(correct);
score++;
}
break;
default: {
String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q2_o1);
display_answer2(wrong);
}
break;
}
}
private void display_answer2(String answer) {
TextView quantityTextView = (TextView) findViewById(R.id.answer_2);
quantityTextView.setText(answer);
}
//Question 3 Methods
public void question3_click(View view) {
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.q3_op3:
if (checked) {
String correct = "Right Answer";
display_answer3(correct);
score++;
}
break;
default: {
String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q3_o3);
display_answer3(wrong);
}
break;
}
}
private void display_answer3(String answer) {
TextView quantityTextView = (TextView) findViewById(R.id.answer_3);
quantityTextView.setText(answer);
}
//Question 4 Methods
public void question4_click(View view) {
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.q4_op1:
if (checked) {
String correct = "Right Answer";
display_answer4(correct);
score++;
}
break;
default: {
String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q4_o1);
display_answer4(wrong);
}
break;
}
}
private void display_answer4(String answer) {
TextView quantityTextView = (TextView) findViewById(R.id.answer_4);
quantityTextView.setText(answer);
}
//Question 5 Methods
public void question5_click(View view) {
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.q5_op3:
if (checked) {
String correct = "Right Answer";
display_answer5(correct);
score++;
}
break;
default: {
String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q5_o3);
display_answer5(wrong);
}
break;
}
}
private void display_answer5(String answer) {
TextView quantityTextView = (TextView) findViewById(R.id.answer_5);
quantityTextView.setText(answer);
}
//Submit Button
public void onClickSubmit(View view){
Intent scoreActivity = new Intent(MainActivity.this,Score.class);
scoreActivity.putExtra("sendScore", score);
startActivity(scoreActivity);
}
}
This is the other activity java(Score.java) file
package com.example.android.conanquiz;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class Score extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
Intent scoreActivity = getIntent();
int totalScore = scoreActivity.getIntExtra("sendScore", 0);
displayScore(totalScore);
}
public void displayScore(int score) {
TextView scoreTextView = (TextView) findViewById(R.id.score);
scoreTextView.setText(score);
}
}
Try to print score on button click using log. if score is not null than write below code.
From Activity
Intent intent = new Intent(getBaseContext(), Score.class);
intent.putExtra("EXTRA_SCORE", score);
startActivity(intent);
To Activity
Intent intent = getIntent();
int intValue = intent.getIntExtra("EXTRA_SCORE", 0);

android - repeat a switch statement

In my app I want to randomly pick an image and put it in the center of the screen. After that, animations can be performed, the image will be moved and reset to its origin position afterwards. Then I want to choose a new image of the switch case, but the image always stays the same. How can I fix it?
public class MainActivity extends Activity implements OnGestureListener
{
private ImageView imageView;
float x1,x2;
float y1, y2;
public int sco = 0;
TextView score;
final Random rand = new Random();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageview1);
imageView.setImageResource(getMyRandomResId());
score = (TextView)findViewById(R.id.textView2);
}
int imag = rand.nextInt(4);
int getMyRandomResId() {
switch (imag) {
case 0:
return R.drawable.a;
case 1:
return R.drawable.b;
case 2:
return R.drawable.c;
default:
return R.drawable.d;
}
}
private boolean animationRunning = false;
public boolean onTouchEvent(MotionEvent touchevent)
{
final ViewPropertyAnimator animator = imageView.animate();
switch (touchevent.getAction())
{
case MotionEvent.ACTION_DOWN:
{
x1 = touchevent.getX();
y1 = touchevent.getY();
break;
}
case MotionEvent.ACTION_UP:
{
x2 = touchevent.getX();
y2 = touchevent.getY();
if (!animationRunning) {
//left to right sweep event on screen
if (x1 < x2 && (x2-x1)>=(y1-y2) && (x2-x1)>=(y2-y1)) {
animationRunning = true;
animator.translationX(imageView.getWidth() * 2)
.setDuration(180)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
if(getMyRandomResId() == R.drawable.ballgrue) {
sco++;
}
imageView.setTranslationX(0);
imageView.setImageResource(getMyRandomResId());
animationRunning = false;
}
})
.start();
}
}
}
}
}
}
int getMyRandomResId() {
int imag = rand.nextInt(4);
switch (imag) {
case 0:
return R.drawable.a;
case 1:
return R.drawable.b;
case 2:
return R.drawable.c;
default:
return R.drawable.d;
}
}
the reason you got a same image bcoz of this only
Hope it helps

Out of Memory error - possibly due to memory leak?

So I'm having an issue with my code when using the android emulator. I get the same error: Throwing OutOfMemoryError "Failed to allocate a 4776816 byte allocation with 2473998 free bytes and 2MB until OOM"
I have a feeling this is due to memory leak as I create objects for each class within each other class and I imagine it's causing some kind of loop error. Is this disallowed in Java? Any help would be much appreciated..
Here is the code:
public class BoardActivity extends AppCompatActivity {
Move move = new Move();
Button buttons[] = new Button[16];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_board);
move.newGame();
buttons[0] = (Button)findViewById(R.id.button1);buttons[0].setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
move.makeMove(move.cups.get(0));
updateButtons();
}});
buttons[1] = (Button)findViewById(R.id.button2);buttons[1].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(1));
updateButtons();
}
});
buttons[2] = (Button)findViewById(R.id.button3);buttons[2].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(2));
updateButtons();
}
});
buttons[3] = (Button)findViewById(R.id.button4);buttons[3].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(3));
updateButtons();
}
});
buttons[4] = (Button)findViewById(R.id.button5);buttons[4].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(4));
updateButtons();
}
});
buttons[5] = (Button)findViewById(R.id.button6);buttons[5].setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
move.makeMove(move.cups.get(5));
updateButtons();
}
});
buttons[6] = (Button)findViewById(R.id.button7);buttons[6].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(6));
updateButtons();
}
});
buttons[7] = (Button)findViewById(R.id.button8);buttons[7].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
updateButtons();
}
});
buttons[8] = (Button)findViewById(R.id.button9);buttons[8].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(8));
updateButtons();
}
});
buttons[9] = (Button)findViewById(R.id.button10);buttons[9].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(9));
updateButtons();
}
});
buttons[10] = (Button)findViewById(R.id.button11);buttons[10].setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
move.makeMove(move.cups.get(10));
updateButtons();
}
});
buttons[11] = (Button)findViewById(R.id.button12);buttons[11].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(11));
updateButtons();
}
});
buttons[12] = (Button)findViewById(R.id.button13);buttons[12].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(12));
updateButtons();
}
});
buttons[13] = (Button)findViewById(R.id.button14);buttons[13].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(13));
updateButtons();
}
});
buttons[14] = (Button)findViewById(R.id.button15);buttons[14].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(14));
updateButtons();
}
});
// Still have bug with this button - needs to be sorted
buttons[15] = (Button)findViewById(R.id.button16);buttons[15].setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
updateButtons();
}
});
updateButtons();
}
public void updateButtons(){
for(int i=0; i<buttons.length; i++){
buttons[i].setText(move.cups.get(i).toString());
}
}
}
Player class:
public class Player extends Move{
Random rand = new Random();
BoardActivity board = new BoardActivity();
/**public void setScoreCups(){
if(returnCurrentPlayer()==1){
oppositionScoreCup = cups.get(16);
scoreCup = cups.get(8);
}else{
oppositionScoreCup = cups.get(8);
scoreCup = cups.get(16);
}
}**/
public void setNextPlayer(){
if(returnCurrentPlayer()==1) {
setTurnPlayer(2);
}else if(returnCurrentPlayer()==2){
setTurnPlayer(1);
}
}
public int returnCurrentPlayer(){
if(board.buttons[5].isEnabled()){
return 1;
}else{
return 2;
}
}
public void setRandomPlayer(){
boolean b = rand.nextBoolean();
if(b){
setTurnPlayer(1);
}else{
setTurnPlayer(2);
}
}
public void setTurnPlayer(int n){
if(n==1) {
for (int i = 1; i < 8; i++) {
board.buttons[i].setEnabled(true);
}
for (int i = 9; i < 16; i++) {
board.buttons[i].setEnabled(false);
}
}else if(n==2){
for(int i=1; i<8; i++){
board.buttons[i].setEnabled(false);
}
for(int i=9; i<16; i++){
board.buttons[i].setEnabled(true);
}
}
}
public void setPlayer() {
if ((move.currentCup.pebbleCount == 0) && (move.currentCup != move.scoreCup)) {
Log.d("makeMove.java", "print cup index" + move.cups.indexOf(move.currentCup));
//emptyCupSwitch(currentCup);
move.currentCup.increasePebbleCount();
}
if (move.currentCup == move.scoreCup) {
move.currentCup.increasePebbleCount();
setTurnPlayer(move.currentPlayer);
} else if (move.currentCup != move.scoreCup) {
move.currentCup.increasePebbleCount();
setNextPlayer();
}
}
//needs to be changed
public static int score=0;
public void setScore(int n){
score = n;
}
}
And Move class:
public class Move extends Game{
Player player = new Player();
public Cup oppositionScoreCup; public Cup scoreCup;
int i; int currentPlayer; int cupValue;
int currentIndex; int lastCupIndex = currentIndex + cupValue - 1;
Cup currentCup;
public List<Cup> cups;
public void newGame() {
cups = new ArrayList<>();
//Reset all cups
for (int i = 0; i < 16; i++) {
Cup cup = new Cup(7);
cups.add(i, cup);
}
}
//Returns the cup following the one entered in the parameters
public Cup getNextCup(Cup cup) {
if (cups.indexOf(cup) == 15) {
return cups.get(0);
} else {
return cups.get(cups.indexOf(cup) + 1);
}
}
//Emptys current cup and switches pebbles to opposite side
public void emptyCupSwitch(Cup cup) {
Cup oppCup;
int index = cups.indexOf(cup);
switch(index) {
case 1:
oppCup = cups.get(15);
cups.get(1).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
break;
case 2:
oppCup = cups.get(14);
cups.get(2).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
break;
case 3:
oppCup = cups.get(13);
cups.get(3).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
break;
case 4:
oppCup = cups.get(12);
cups.get(4).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 5:
oppCup = cups.get(11);
cups.get(5).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 6:
oppCup = cups.get(10);
cups.get(6).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 7:
oppCup = cups.get(9);
cups.get(7).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 9:
oppCup = cups.get(7);
cups.get(9).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 10:
oppCup = cups.get(6);
cups.get(10).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 11:
oppCup = cups.get(5);
cups.get(11).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 12:
oppCup = cups.get(4);
cups.get(12).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 13:
oppCup = cups.get(3);
cups.get(13).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 14:
oppCup = cups.get(2);
cups.get(7).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 15:
oppCup = cups.get(1);
cups.get(7).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
}
}
//Method for Clicking Cup - Basic move - Skips oppositonScoreCup
public void makeMove(Cup cup) {
cupValue = cup.returnPebbleCount();
currentIndex = cups.indexOf(cup);
currentCup = getNextCup(cup);
cup.emptyCup();
for (i = currentIndex; i < currentIndex + cupValue; i++) {
if (i == lastCupIndex) {
player.setPlayer();
} else if (currentCup == oppositionScoreCup) {
currentCup = getNextCup(currentCup);
} else if (currentCup != oppositionScoreCup) {
currentCup.increasePebbleCount();
currentCup = getNextCup(currentCup);
}
}
if(checkGameOver()){
gameOver();
}
}
}
You are running out of memory because your code will run recursively and create an infinite number of objects of BoardActivity, Move and Player.
How? Well, when the BoardActivity class is initialized, the line
Move move = new Move();
will create new Move object. This, in turn will result in the execution of the line
Player player = new Player();
from inside the Move class. This will spawn a new Player object which contains the line
BoardActivity board = new BoardActivity();
Now this will create another BoardActivity object and this takes us back to the beginning creating an endless cycle of object spawning.
Simply put, BoardActivity->Move->Player->BoardActivity->Move->Player....
I'm guessing the AppCompatActivity is an android activity. Android activities are pretty heavy and allocates some good amount of heap memory when initialized. This is basically why you are running out of memory so quickly.
You shouldn't be creating an activity this way. Either create one and start from the main activity or load it as the default activity using the AndroidManifest
Also instead of creating a separate OnClickListener for each button, it would be better to create a single OnClickListener and check button ids using if statements to determine which button was clicked.

Switch statement just returning the last case

Switch statment fix:
The switch statement is only returning the last case i.e case 4, "#0R0dfdf0FF". how can i fix this so the text view shows the the one clicked in the dialogue box?
I'm a total newbie so yes help would really be appreciated.
public class NoteEdit extends Activity {
public EditText mTitleText;
public EditText mBodyText;
public EditText mColor;
private NotesDbAdapter mDbHelper;
private static final int DIALOG_ALERT = 10;
Long mRowId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.note_edit);
setTitle(R.string.done);
mTitleText = (EditText) findViewById(R.id.editTitle);
mBodyText = (EditText) findViewById(R.id.editNote);
mColor = (EditText) findViewById(R.id.editColor);
mRowId = (savedInstanceState == null) ? null :
(Long) savedInstanceState.getSerializable(NotesDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID)
: null;
}
populateFields();
setupActionBar();
}
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
setResult(RESULT_OK);
finish();
}
return super.onOptionsItemSelected(item);
}
private void populateFields() {
if (mRowId != null) {
Cursor note = mDbHelper.fetchNote(mRowId);
startManagingCursor(note);
mTitleText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
mBodyText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
mColor.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_COLOR)));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(NotesDbAdapter.KEY_ROWID, mRowId);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
#Override
protected void onResume() {
super.onResume();
populateFields();
}
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
String color = mColor.getText().toString();
if (mRowId == null) {
long id = mDbHelper.createNote(title, body, color);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateNote(mRowId, title, body, color);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case R.id.add:
showDialog(DIALOG_ALERT);
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ALERT:
// Create out AlterDialog
android.app.AlertDialog.Builder builder = new AlertDialog.Builder(this);
final String[] colors = {"Blue", "Green", "Yellow", "Red", "Purple"};
builder.setTitle(R.string.body);
builder.setItems(colors, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which){
case 0:
mColor.setText("#000000");
case 1:
mColor.setText("#0000FF");
case 2:
mColor.setText("#0R00FF");
case 3:
mColor.setText("#0R00dsdFF");
case 4:
mColor.setText("#0R0dfdf0FF");
default:
break;
}
} });
AlertDialog dialog = builder.create();
dialog.show();
}
return super.onCreateDialog(id);
}
}
You are missing break; at the end of the switch branches.
Fall Through.
You have to add the break.
case 0:
mColor.setText("#000000");
break;
You can find that in docs
The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
You need a break when you don't have a return otherwise it causes fall through
You need the break; after all cases except for the last one or else it'll fall through case by case
switch (which){
case 0:
mColor.setText("#000000");
break;
case 1:
mColor.setText("#0000FF");
break;
case 2:
mColor.setText("#0R00FF");
break;
case 3:
mColor.setText("#0R00dsdFF");
break;
case 4:
mColor.setText("#0R0dfdf0FF");
default:
break;
}

Why not change color when pressed?

when you click the color should change to another
but it doesnt work!
My code:
#
public class CreateActivity extends Activity {
TableLayout table;
Integer i;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
table = (TableLayout)findViewById(R.id.myTable);
Button left = (Button) findViewById(R.id.buttonLeft);
Button right = (Button) findViewById(R.id.buttonRight);
TextView color = (TextView) findViewById(R.id.text);
i=0;
right.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
i++; //+1
}
});
//COLOR
switch(i){
case 1: table.setBackgroundColor(Color.RED); break;
case 2: table.setBackgroundColor(Color.rgb (255, 127, 0) ); break;
case 3: table.setBackgroundColor(Color.YELLOW); break;
case 4: table.setBackgroundColor(Color.GREEN) ; break;
case 5: table.setBackgroundColor(Color.rgb (0,191,255) ); break;
case 6: table.setBackgroundColor(Color.BLUE ); break;
case 7: table.setBackgroundColor(Color.rgb (160,32,240) ); break;
}
}
}
When the button is clicked, you're incrementing i - but you won't be running the switch/case statement again. If you look in the debugger you'll find that the variable value is changing, but you haven't instructed any part of the display to change.
You should put that common logic in a separate method which is called both from the onCreate method and the OnClickListener. For example:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
table = (TableLayout)findViewById(R.id.myTable);
Button left = (Button) findViewById(R.id.buttonLeft);
Button right = (Button) findViewById(R.id.buttonRight);
TextView color = (TextView) findViewById(R.id.text);
i=0;
right.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
i++;
// Cycle round
if (i == 8) {
i = 1;
}
applyBackgroundColor();
}
});
applyBackgroundColor();
}
private void applyBackgroundColor() {
switch(i) {
// TODO: Consider what you want to do when i is 0...
case 1: table.setBackgroundColor(Color.RED); break;
case 2: table.setBackgroundColor(Color.rgb(255, 127, 0)); break;
case 3: table.setBackgroundColor(Color.YELLOW); break;
case 4: table.setBackgroundColor(Color.GREEN); break;
case 5: table.setBackgroundColor(Color.rgb(0,191,255)); break;
case 6: table.setBackgroundColor(Color.BLUE); break;
case 7: table.setBackgroundColor(Color.rgb(160,32,240)); break;
}
}
There are various other things I'd change about this code, but that should at least get you over this hump.

Categories