Why not change color when pressed? - java

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.

Related

OnClick only image2 changes

In this, I want to change the images in the order. i.e on 1st click of dice1 itself, dice1 should change then dice2, dice3, dice4, and then again dice1 and soo on till the end of the loop. but whenever I click any image only the image in dice2 changes. The image I click only that should change that too in the predefined order. Can someone please help fix the code.
JAVA FILE
public class MainActivity extends AppCompatActivity{
private ImageView dice1,dice2,dice3,dice4;
private ImageView[] dice = { dice1, dice2, dice3, dice4 };
private Random rng = new Random();
public int i=0,j=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dice[0] = findViewById(R.id.imageView3);
dice[1]= findViewById(R.id.imageView7);
dice[2] = findViewById(R.id.imageView9);
dice[3] = findViewById(R.id.imageView5);
while(j<5){
if(i==4){
i=0;}
dice[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
rollDice();
}
});
j++;
i++;
}
}
private void rollDice(){
int randomNo = rng.nextInt(6)+1;
switch (randomNo){
case 1:
dice[i].setImageResource(R.drawable.one);
break;
case 2:
dice[i].setImageResource(R.drawable.two);
break;
case 3:
dice[i].setImageResource(R.drawable.three);
break;
case 4:
dice[i].setImageResource(R.drawable.four);
break;
case 5:
dice[i].setImageResource(R.drawable.five);
break;
case 6:
dice[i].setImageResource(R.drawable.six);
break;
}
}

Android Java calling method

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

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

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

Android Calculating values to pass to onClick method

I think I'm getting confused about the activity lifecycle here, I'm trying to perform a simple weights conversion, nothing spectacular.
the user enters a value, selects whether they want it converted to lbs or kgs and when they press 'Convert' it should spit out the converted values, lookng at the stack trace it seems to have a problem with the parseInt im using.
public class WeightConverter extends Activity implements OnClickListener, OnCheckedChangeListener {
Button convertWeight;
TextView conversionResults;
EditText enterWeight;
RadioGroup weightPicker;
RadioButton radKG, radLB;
double weightValue, convertedWeight;
String weightString;
String measurement;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.weightconverter);
initializeVariables();
}
private void initializeVariables() {
convertWeight = (Button) findViewById(R.id.btnConvertWeight);
conversionResults =(TextView) findViewById(R.id.tvWeightConversion);
enterWeight =(EditText) findViewById(R.id.etWeightToConvert);
weightPicker = (RadioGroup) findViewById(R.id.rgWeightType);
radKG = (RadioButton) findViewById(R.id.radKG);
radLB = (RadioButton) findViewById(R.id.radLB);
convertWeight.setOnClickListener(this);
}
#Override
public void onClick(View v) {
;
switch (v.getId()) {
case R.id.btnConvertWeight:
weightValue = Double.parseDouble(enterWeight.getText().toString());
conversionResults.setText(weightValue + " = " + weightString + measurement);
break;
}
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radKG:
convertedWeight = weightValue / 2.2;
measurement = " Kilograms";
break;
case R.id.radLB:
convertedWeight = weightValue * 2.2;
measurement = " Pounds";
break;
}weightString = String.valueOf(convertedWeight);
}
}
I'm not convinced that your onCheckedChanged method is being called at all (have you seen the code entering it using the debugger?).
Try assigning it to your weightPicker radio group as below instead:
weightPicker.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId)
{
weightValue = Integer.parseInt(enterWeight.getText().toString());
switch (checkedId) {
case R.id.radKG:
convertedWeight = weightValue / 2.2;
measurement = " Kilograms";
break;
case R.id.radLB:
convertedWeight = weightValue * 2.2;
measurement = " Pounds";
break;
}
});
You have weightValue declared as a double but trying to parse integer
double weightValue,
Instead use
weightValue = Double.parseDouble(enterWeight.getText().toString());
I would also suggest error checking on your entered value in case the user enters a non digit

Categories