I'm fairly new to programming and I am learning to develop in Java and building Android applications.
I am trying to create a Dreidel game, on my xml file, I have a button, an imageview, and a TextView (I will be working on keeping the score a little later, I can figure that out on my own easily enough I imagine).
But the objective is that when I push the button, a random number generator produces a number from 0-3,
If 0, I want the TextBox to display "You get nothing"
If 1, I want the TextBox to display something else
If 2, I want the TextBox to display something else
If 3, I want the TextBox to display something else
Here is the code. When I run it in the Android Emulator, it starts up but nothing happens when I click the button
package com.secondtry;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Button spinButton;
TextView display;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
display = (TextView) findViewById(R.id.widget34);
spinButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Random numGen = new Random();
numGen.nextInt(4);
if (numGen.nextInt() == 0)
{
display.setText("You get nothing");
}
else if (numGen.nextInt() == 1)
{
display.setText("You get half!");
}
else if (numGen.nextInt() == 2)
{
display.setText("You get it all");
}
else if (numGen.nextInt() == 3)
{
display.setText("Chip in a coin");
} }
});
}
}
Use numGen.nextInt(4) instead of numGen.nextInt() in your condition. Grab its value inside a variable(say x) and use that value in every condition.
You may try this:
int ran = numGen.nextInt(4);
switch (ran){
case 0:
display.setText("You get nothing");
break;
case 1:
display.setText("You get half!");
break;
case 2:
display.setText("You get it all");
break;
case 3:
display.setText("Chip in a coin");
break;
}
You need to either define your button in onCreate with something like
final Button spinButton = (Button) findViewById(R.id.spinbuttonIdInXML);
Or pull the onClick outside of the onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
...
}
#Override
public void onClick(View v) {
...
}
Define your Button in OnCreate Like this..
spinButton = (Button)findViewById(R.id.urbuttonid);
updated try this
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Button spinButton;
TextView display;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinButton = (Button)findViewById(R.id.ButtonId);
display = (TextView) findViewById(R.id.widget34);
spinButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Random numGen = new Random();
int rNumber = numGen.nextInt(4);
if (rNumber == 0)
{
display.setText("You get nothing");
}
else if (rNumber == 1)
{
display.setText("You get half!");
}
else if (rNumber == 2)
{
display.setText("You get it all");
}
else if (rNumber == 3)
{
display.setText("Chip in a coin");
} }
});
}
}
Related
I have a quiz app that is working properly, but the thing is the user must answer all questions correctly in order to win the game(if the player gets it wrong the game will be over) .
What I wanted to do is have the questions answered and then at the end there will be an activity that will show how many the player has answered then there will be the options to retry and go back to menu
This is the code for the maingameactivity
public class MainGameActivity extends AppCompatActivity {
FButton buttonA, buttonB, buttonC, buttonD;
TextView questionText, triviaQuizText, timeText, resultText, coinText;
TriviaQuizHelper triviaQuizHelper;
TriviaQuestion currentQuestion;
List<TriviaQuestion> list;
int qid = 0;
int timeValue = 20;
int coinValue = 0;
CountDownTimer countDownTimer;
Typeface tb, sb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_main);
//Initializing variables
questionText = (TextView) findViewById(R.id.triviaQuestion);
buttonA = (FButton) findViewById(R.id.buttonA);
buttonB = (FButton) findViewById(R.id.buttonB);
buttonC = (FButton) findViewById(R.id.buttonC);
buttonD = (FButton) findViewById(R.id.buttonD);
triviaQuizText = (TextView) findViewById(R.id.triviaQuizText);
timeText = (TextView) findViewById(R.id.timeText);
resultText = (TextView) findViewById(R.id.resultText);
coinText = (TextView) findViewById(R.id.coinText);
//Setting typefaces for textview and buttons - this will give stylish fonts on textview and button etc
tb = Typeface.createFromAsset(getAssets(), "fonts/TitilliumWeb-Bold.ttf");
sb = Typeface.createFromAsset(getAssets(), "fonts/shablagooital.ttf");
triviaQuizText.setTypeface(sb);
questionText.setTypeface(tb);
buttonA.setTypeface(tb);
buttonB.setTypeface(tb);
buttonC.setTypeface(tb);
buttonD.setTypeface(tb);
timeText.setTypeface(tb);
resultText.setTypeface(sb);
coinText.setTypeface(tb);
//Our database helper class
triviaQuizHelper = new TriviaQuizHelper(this);
//Make db writable
triviaQuizHelper.getWritableDatabase();
//It will check if the ques,options are already added in table or not
//If they are not added then the getAllOfTheQuestions() will return a list of size zero
if (triviaQuizHelper.getAllOfTheQuestions().size() == 0) {
//If not added then add the ques,options in table
triviaQuizHelper.allQuestion();
}
//This will return us a list of data type TriviaQuestion
list = triviaQuizHelper.getAllOfTheQuestions();
//Now we gonna shuffle the elements of the list so that we will get questions randomly
Collections.shuffle(list);
//currentQuestion will hold the que, 4 option and ans for particular id
currentQuestion = list.get(qid);
//countDownTimer
countDownTimer = new CountDownTimer(22000, 1000) {
public void onTick(long millisUntilFinished) {
//here you can have your logic to set text to timeText
timeText.setText(String.valueOf(timeValue) + "\"");
//With each iteration decrement the time by 1 sec
timeValue -= 1;
//This means the user is out of time so onFinished will called after this iteration
if (timeValue == -1) {
//Since user is out of time setText as time up
resultText.setText(getString(R.string.timeup));
//Since user is out of time he won't be able to click any buttons
//therefore we will disable all four options buttons using this method
disableButton();
}
}
//Now user is out of time
public void onFinish() {
//We will navigate him to the time up activity using below method
timeUp();
}
}.start();
//This method will set the que and four options
updateQueAndOptions();
}
public void updateQueAndOptions() {
//This method will setText for que and options
questionText.setText(currentQuestion.getQuestion());
buttonA.setText(currentQuestion.getOptA());
buttonB.setText(currentQuestion.getOptB());
buttonC.setText(currentQuestion.getOptC());
buttonD.setText(currentQuestion.getOptD());
timeValue = 20;
//Now since the user has ans correct just reset timer back for another que- by cancel and start
countDownTimer.cancel();
countDownTimer.start();
//set the value of coin text
coinText.setText(String.valueOf(coinValue));
//Now since user has ans correct increment the coinvalue
coinValue++;
}
//Onclick listener for first button
public void buttonA(View view) {
//compare the option with the ans if yes then make button color green
if (currentQuestion.getOptA().equals(currentQuestion.getAnswer())) {
buttonA.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
//Check if user has not exceeds the que limit
if (qid < list.size() - 1) {
//Now disable all the option button since user ans is correct so
//user won't be able to press another option button after pressing one button
disableButton();
//Show the dialog that ans is correct
correctDialog();
}
//If user has exceeds the que limit just navigate him to GameWon activity
else {
gameWon();
}
}
//User ans is wrong then just navigate him to the PlayAgain activity
else {
gameLostPlayAgain();
}
}
//Onclick listener for sec button
public void buttonB(View view) {
if (currentQuestion.getOptB().equals(currentQuestion.getAnswer())) {
buttonB.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
correctDialog();
} else {
gameWon();
}
} else {
gameLostPlayAgain();
}
}
//Onclick listener for third button
public void buttonC(View view) {
if (currentQuestion.getOptC().equals(currentQuestion.getAnswer())) {
buttonC.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
correctDialog();
} else {
gameWon();
}
} else {
gameLostPlayAgain();
}
}
//Onclick listener for fourth button
public void buttonD(View view) {
if (currentQuestion.getOptD().equals(currentQuestion.getAnswer())) {
buttonD.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
correctDialog();
} else {
gameWon();
}
} else {
gameLostPlayAgain();
}
}
//This method will navigate from current activity to GameWon
public void gameWon() {
Intent intent = new Intent(this, GameWon.class);
startActivity(intent);
finish();
}
//This method is called when user ans is wrong
//this method will navigate user to the activity PlayAgain
public void gameLostPlayAgain() {
Intent intent = new Intent(this, PlayAgain.class);
startActivity(intent);
finish();
}
//This method is called when time is up
//this method will navigate user to the activity Time_Up
public void timeUp() {
Intent intent = new Intent(this, Time_Up.class);
startActivity(intent);
finish();
}
//If user press home button and come in the game from memory then this
//method will continue the timer from the previous time it left
#Override
protected void onRestart() {
super.onRestart();
countDownTimer.start();
}
//When activity is destroyed then this will cancel the timer
#Override
protected void onStop() {
super.onStop();
countDownTimer.cancel();
}
//This will pause the time
#Override
protected void onPause() {
super.onPause();
countDownTimer.cancel();
}
//On BackPressed
#Override
public void onBackPressed() {
Intent intent = new Intent(this, HomeScreen.class);
startActivity(intent);
finish();
}
//This dialog is show to the user after he ans correct
public void correctDialog() {
final Dialog dialogCorrect = new Dialog(MainGameActivity.this);
dialogCorrect.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (dialogCorrect.getWindow() != null) {
ColorDrawable colorDrawable = new ColorDrawable(Color.TRANSPARENT);
dialogCorrect.getWindow().setBackgroundDrawable(colorDrawable);
}
dialogCorrect.setContentView(R.layout.dialog_correct);
dialogCorrect.setCancelable(false);
dialogCorrect.show();
//Since the dialog is show to user just pause the timer in background
onPause();
TextView correctText = (TextView) dialogCorrect.findViewById(R.id.correctText);
FButton buttonNext = (FButton) dialogCorrect.findViewById(R.id.dialogNext);
//Setting type faces
correctText.setTypeface(sb);
buttonNext.setTypeface(sb);
//OnCLick listener to go next que
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//This will dismiss the dialog
dialogCorrect.dismiss();
//it will increment the question number
qid++;
//get the que and 4 option and store in the currentQuestion
currentQuestion = list.get(qid);
//Now this method will set the new que and 4 options
updateQueAndOptions();
//reset the color of buttons back to white
resetColor();
//Enable button - remember we had disable them when user ans was correct in there particular button methods
enableButton();
}
});
}
//This method will make button color white again since our one button color was turned green
public void resetColor() {
buttonA.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
buttonB.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
buttonC.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
buttonD.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
}
//This method will disable all the option button
public void disableButton() {
buttonA.setEnabled(false);
buttonB.setEnabled(false);
buttonC.setEnabled(false);
buttonD.setEnabled(false);
}
//This method will all enable the option buttons
public void enableButton() {
buttonA.setEnabled(true);
buttonB.setEnabled(true);
buttonC.setEnabled(true);
buttonD.setEnabled(true);
}
}
Edited
Just remove the wrapper if else inside all the buttons better to keep it as, don't repeat the code. I am assuming the screen that shows result is handled inside gameWon and you have implemented functionality for inCorrectDialog
public void buttonA(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonB(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonC(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonD(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonPressed(Button button) {
button.setButtonColor(ContextCompat.getColor(getApplicationContext(), R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
if (currentQuestion.getOptA().equals(currentQuestion.getAnswer())) {
correctDialog();
} else {
inCorrectDialog();
}
} else {
gameWon();
}
}
I would like to know how to set an if else condition where the next button have to be disabled if none of the buttons are being clicked. Otherwise, they are able to proceed to next question?
private AdvancedQuestion nAdvancedQuestion = new AdvancedQuestion();
private TextView nScoresView;
private TextView nQuestionsView;
private TextView tvTime;
private Button nButtonChoices1;
private Button nButtonChoices2;
private Button nButtonChoices3;
private Button nButtonChoices4;
private String nAnswers;
private int nScores = 0;
private int nQuestionNumbers = 0;
Button btnNextz;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_advanced_quiz);
updateQuestions();
nButtonChoices1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (nButtonChoices1.getText() == nAnswers) {
correctSound.start();
nScores = nScores + 1;
nButtonChoices1.setEnabled(false);
nButtonChoices2.setEnabled(false);
nButtonChoices3.setEnabled(false);
nButtonChoices4.setEnabled(false);
nButtonChoices1.getBackground().setColorFilter(Color.GREEN, PorterDuff.Mode.MULTIPLY);
Toast.makeText(advancedQuiz.this, "correct", Toast.LENGTH_SHORT).show();
} else {
wrongSound.start();
Toast.makeText(advancedQuiz.this, "wrong", Toast.LENGTH_SHORT).show();
nButtonChoices1.setEnabled(false);
nButtonChoices2.setEnabled(false);
nButtonChoices3.setEnabled(false);
nButtonChoices4.setEnabled(false);
}
}
});
btnNextz.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nextSound.start();
updateQuestions();
nButtonChoices1.setEnabled(true);
nButtonChoices2.setEnabled(true);
nButtonChoices3.setEnabled(true);
nButtonChoices4.setEnabled(true);
nButtonChoices1.getBackground().setColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY);
nButtonChoices2.getBackground().setColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY);
nButtonChoices3.getBackground().setColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY);
nButtonChoices4.getBackground().setColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY);
}
private void updateQuestions() {
nQuestionsView.setText(nAdvancedQuestion.getQuestions(nQuestionNumbers));
nButtonChoices1.setText(nAdvancedQuestion.getChoices1(nQuestionNumbers));
nButtonChoices2.setText(nAdvancedQuestion.getChoices2(nQuestionNumbers));
nButtonChoices3.setText(nAdvancedQuestion.getChoices3(nQuestionNumbers));
nButtonChoices4.setText(nAdvancedQuestion.getChoices4(nQuestionNumbers));
nAnswers = nAdvancedQuestion.getCorrectAnswers(nQuestionNumbers);
nQuestionNumbers++;
}
private void updateScore(int points) {
nScoresView.setText("" + nScores);
}
Please note there is 4 possible answers. If none of them are selected, they cannot proceed to the next question until one button is press so they can go to the next question. The updateQuestions() is the part where i believe it will show next question.
This is a simple example on how to disable/enable a button based on an if condition -
int count = 0;
if (count == 0) {
NextButton.setEnabled(false);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.otherButtons:
count++;
NextButton.setEnabled(true);
Toast.makeText(this, "Button Disabled", Toast.LENGTH_LONG).show();
break;
case R.id.nextButton:
//Move the user to the next question
break;
}
}
Also check out this link
You will need to add a button element in the view of the activity you want it to appear on, then add an event listener to it either in the activity code or specify which function to call on click in the activities XML layout file.
See: https://developer.android.com/reference/android/widget/Button.html
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
i finally figured out where to find most of this.
but now i need to know how to test one part of this program for a username.
My goal is if the user doesn't put anything in the program then don't allow anything to continue.
This is a big app. I have like 3 layout files and 3 java files.
Any help would be good if you need me to send the file i can.
package edu.jones.demogamestartarrayadaptor;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
//import android.view.KeyEvent;
import android.view.View;
//import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
//import android.widget.Toast;
public class GameControlMainActivity extends ListActivity
{
//Class-wide variables for data passed/returned
private String userName = "";
//Use an int for gameLevel,naturally...but, this requires
//use of various methods to convert to String and back!
private int gameLevel = 1;
private EditText nameEntryET;
private TextView gameLevelAnnouncerTV;
private TextView gameLevelTV;
Button doneButton;
//This TV prompts user to enter name in the EditText
//Then, it is made invisible
private TextView namePromptTV;
//These two start out invisible and then show the name
private TextView nameSetTV;
private TextView nameEntTV;
//Array of choices for user
static final String[] CHOICES = new String[]
{
"Read directions",
"Play Game",
"Quit"
};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Set up View ids
nameEntryET = (EditText)findViewById(R.id.enter_nameET);
gameLevelAnnouncerTV = (TextView) findViewById(R.id.game_level_announcer_TV);
gameLevelTV = (TextView) findViewById(R.id.game_level_TV);
//Set the game level in the TextView
gameLevelTV.setText(Integer.toString(gameLevel));
namePromptTV = (TextView)findViewById(R.id.name_prompt_tv);
nameSetTV = (TextView)findViewById(R.id.name_set_tv);
nameEntTV = (TextView)findViewById(R.id.name_entered_tv);
//Set Done button listener to get user's name
doneButton = (Button) findViewById(R.id.doneBtn);
setDoneButtonListener();
//Set up ArrayAdaptor for the options
setListAdapter(new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, CHOICES));
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setTextFilterEnabled(true);
//Set up the listener for user clicks on the list
setListClickListener();
//this toast is for when it opens
Toast.makeText(this, "yo whats up", Toast.LENGTH_SHORT).show();
}//END onCreate
private void setDoneButtonListener()
{
doneButton.setOnClickListener
(
new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Get user's name when button is clicked
//Call method to set text and hide button
setUserNameAndHideButton();
}
}
);//END setOnClickListener
}//END setDoneButtonListener
//Sets up username in its TextView, and game level Views,
//then hides the other Views & button
private void setUserNameAndHideButton()
{
userName = nameEntryET.getText().toString();
doneButton.setVisibility(View.GONE);
Toast.makeText(this, "Your name has been entered", Toast.LENGTH_SHORT).show();
//After getting the input, hide the EditText
//VISIBLE(0), INVISIBLE(4) or GONE(8)
nameEntryET.setVisibility(View.INVISIBLE);
namePromptTV.setVisibility(View.GONE);
nameEntTV.setText(userName);
nameSetTV.setVisibility(View.VISIBLE);
nameEntTV.setVisibility(View.VISIBLE);
gameLevelAnnouncerTV.setVisibility(View.VISIBLE);
gameLevelTV.setVisibility(View.VISIBLE);
}//END setUserNameAndHideButton
//Set up the listener for the ListView to interpret user clicks
private void setListClickListener()
{
//Set up the click listener for the options
getListView().setOnItemClickListener
(
new OnItemClickListener()
{
//#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
switch(arg2)
{
case 0: launchDirectionsPage();
break;
case 1: startGame();
break;
case 2: finish();
break;
default: break;
}
}
}//END OnItemClickListener
);//END setOnItemClickListener
}//END setListClickListener
//Launch a simple activity to show a scroll view of directions
protected void launchDirectionsPage()
{
//Set up Intent
Intent launchDirections = new Intent(this, DirectionsPageActivity.class);
startActivity(launchDirections);
}//END launchDirectionsPage
//Launch the activity that allows user to input new game value
//Upon return the onActivityResult method is called
protected void startGame()
{
//Set up Intent to launch other activity: PlayGame
Intent launchGame = new Intent(this, PlayGameActivity.class);
//Info added to the Intent's Bundle to pass to PlayGameActivity
launchGame.putExtra("bdl_username", userName);
launchGame.putExtra("bdl_gamelevel", gameLevel);
startActivityForResult(launchGame, 0);
}//END startGame
//This method will be called when the startGame activity terminates
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 0 && resultCode == RESULT_OK)
{
//Reset the views to possibly updated info returned in the Intent
//First, access the Bundle's values
userName = data.getExtras().getString("bdl_returnUserName");
gameLevel = data.getExtras().getInt("bdl_returnGameLevel");
//Update the user name & game level with values from other activity
nameEntTV.setText(userName);
gameLevelTV.setText(Integer.toString(gameLevel));
}
}//END onActivityResult
#Override
protected void onSaveInstanceState (Bundle outState)
{
super.onSaveInstanceState(outState);
//Add the username and game level to the Bundle
outState.putString("bdl_savedusername", userName);
outState.putInt("bdl_savedgamelevel", gameLevel);
}//END onSaveInstanceState
#Override
public void onRestoreInstanceState (Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
//Restore the username and game level from the Bundle
userName = savedInstanceState.getString("bdl_savedusername");
gameLevel = savedInstanceState.getInt("bdl_savedgamelevel");
}//END onRestoreInstanceState
}//END GameControlMainActivity
If you are asking to stop if the username is not entered, just do this:
private void setDoneButtonListener()
{
doneButton.setOnClickListener
(
new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (nameEntryET.getText().toString().equals("")) {
Toast.makeText(this, "Enter a username", Toast.LENGTH_LONG).show();
} else {
//Get user's name when button is clicked
//Call method to set text and hide button
setUserNameAndHideButton();
}
}
}
);//END setOnClickListener
}//END setDoneButtonListener
if nameEntryET does not have a value entered, nameEntryET.getText().toString() will return an empty string.
I want to display the complete input and output of my app.
For example:
2+2=4 needs to be displayed after clicking "=" in the calculator.
My problem is that app closes unexpectedly.
package com.scientific.calculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ToggleButton;
public class Calculator extends Activity{
EditText display;
Button btn,btnop,add,sub,mul,div;
ToggleButton shift;
String operator,result;
float value=0;
Character op = 'q';
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator);
display = (EditText)findViewById(R.id.etDisplay);
shift = (ToggleButton)findViewById(R.id.tbShift);
}
public void set_number(View v) {
// TODO Auto-generated method stub
btn = (Button)findViewById(v.getId());
result = display.getText().toString();
display.setText(result+btn.getText().toString());
}
public void btnplusclicked(View v){
perform(v);
op = '+';
}
public void btnminusclicked(View v){
perform(v);
op = '-';
}
public void btndivideclicked(View v){
perform(v);
op = '÷';
}
public void btnmulticlicked(View v){
perform(v);
op = '×';
}
public void btnequalClicked(View v){
evaluate();
}
public void perform(View v) {
// TODO Auto-generated method stub
btnop=(Button)findViewById(v.getId());
result=display.getText().toString();
operator=btnop.getText().toString();
display.setText(result+operator);
}
private void evaluate() {
// TODO Auto-generated method stub
value=Float.valueOf(display.getText().toString());
if(op == '+')
value=Float.valueOf(display.getText().toString())+value;
else if(op == '-')
value=Float.valueOf(display.getText().toString())-value;
else if(op == '/')
value=Float.valueOf(display.getText().toString())/value;
else if(op == '*')
value=Float.valueOf(display.getText().toString())*value;
display.setText(String.valueOf(value));
}
}
It seems you are trying to parse '123+25' to float. so it will give error.
And what if user presses '1+2-3*4' what would be your operator '*' . so it might not work properly. please check here for a good example on calculator for android..
Try to understand this way. When you click equal to evaluate() is called.
In which the first line is value=Float.valueOf(display.getText().toString());
That is converting what is the display to Float.
Though computer is able to convert the first digits but when it come and reads the operator in between. It can't convert that. Hence the crash. Just to be assured.
Type 2 and then press equal I bet it won't crash.
Now either you can do is. When ever a operator ( + - * / ) is called. Use a float variable and calculate it and keep it in the memory. Once the user presses Equal to. Display that Value. Simple as it is.
For more reference Have a look at simple cal or complex calc
I want to display an image on button click, but I have three errors in my code. What's wrong?
class name "SequencerActivity"
The type SequencerActivity must implement the inherited abstract method DialogInterface.OnClickListener.onClick(DialogInterface, int).
next.setOnClickListener(this);
The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (SequencerActivity).
onClick(View v)
The method onClick(View) of type SequencerActivity must override or implement a supertype method.
Here's the code giving those errors:
public class SequencerActivity extends Activity implements OnClickListener
{
private int imageCounter = 0;
private ImageView imageLoader;
private int[] imageList = {R.drawable.f03, R.drawable.f04, R.drawable.f05, R.drawable.f06};
#Override
public void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.main);//this one is the common parent layout for all image views
super.onCreate(savedInstanceState);
/*requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);*/
//int image1 = R.drawable.image_w_lbl_0;
imageLoader = (ImageView) findViewById(R.id.imageLoader);
//imageLoader.setImageResource(image1);
Button next = (Button) findViewById(R.id.next);
Button back = (Button) findViewById(R.id.back);
next.setOnClickListener(this);
back.setOnClickListener(this);
back.setEnabled(false);
//show the default image
this.loadImage(imageList[imageCounter]);
}
#Override
public void onClick(View v)
{
int imagePath = 0;
// TODO Auto-generated method stub
switch (v.getId())
{
case R.id.next:
Log.i("Tag","tag");
if(imageCounter < imageList.length)
{
imageCounter++;
imagePath = imageList[imageCounter];
if (imageCounter==(imageList.length)-1)
{
{
ImageButton next=(ImageButton)findViewById(R.id.next);
next.setEnabled(false);
}
}
else
{
ImageButton back=(ImageButton)findViewById(R.id.back);
back.setEnabled(true);
}
}
break;
case R.id.back:
if(imageCounter > 0)
{
imageCounter--;
imagePath = imageList[imageCounter];
if (imageCounter==0)
{
ImageButton back=(ImageButton)findViewById(R.id.back);
back.setEnabled(false);
}
else
{
ImageButton next=(ImageButton)findViewById(R.id.next);
next.setEnabled(true);
}
}
break;
}
this.loadImage(imagePath);
}
private void loadImage(int imagePath)
{
imageLoader.setImageResource(imagePath);
}
}
The OnClickListener that you implement is not correct,
try to implement View.OnClickListener and not DialogInterface.OnClickListener.
You can see that in your import
import View.OnClickListener
instead of
import DialogInterface.OnClickListener
you need to import import android.view.View.OnClickListener;
So your code look like
import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener{
// Your oncreate() and rest of all code
}
// you should have method as below
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.editText1) // just for instance
{
.. your onclick handle code
}
}
Still you are not able to resolve the error type import View.OnClickListener; then move the cursor on the View in import View.OnClickListener; It will open up pop-up then choose the Organize imports option.
Use simply import View.OnClickListener; at the top.
The OnClickListener you're implementing is the wrong one. It says it's DialogInterface.OnClickListener, while you probably want View.OnClickListener. You can correct that in the corresponding import statement.
Just do only One thing. Use "import android.view.View.OnClickListener" statement at the top of the program.
Do one thing
remove import android.content.DialogInterface.OnClickListener;
and import
android.View.View.OnClickListener
this will solve the problem
Happy Coding
Implement View.view.onClickListener