I am making this beer/drink app as a fun project. I checked around the site and couldn't find anything specific to my problem. I would greatly appreciate help at two things;
I would like a button to reset whatever the count gets to in this code, I can't seem to figure out what I need..
The countButton is for beer and the drinkButton is for, well yeah, drinks.
public class Activity2 extends AppCompatActivity {
// Private member field to keep track of the count
private int mCount = 0;
private int mSum = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
final TextView countTextView = (TextView) findViewById(R.id.TextViewCount);
final TextView sumTextView = (TextView) findViewById(R.id.textSum);
final ImageButton countButton = (ImageButton) findViewById(R.id.beerCount);
final ImageButton drinkButton = (ImageButton) findViewById(R.id.drinkCount);
countButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCount++;
mSum += 72;
countTextView.setText("You have been drinking " + mCount + " units!");
sumTextView.setText("Sum:" + mSum + "!");
}
});
drinkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCount++;
mSum += 96;
countTextView.setText("You have been drinking " + mCount + " units!");
sumTextView.setText("Sum:" + mSum + "!");
}
});
Also, the count does remove itself when I toggle through tabs in the app, any ideas to make it stay, and only removing by the reset button?
Greatly appreciate any help!
For what you require, simply add a third button to your activity and in its onCLickListener, set the values to 0.
Something like this.
resetButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
this.mSum = 0;
}
});
Related
In my Code I have an Intent to an other Activity but when I use my Phone to test it nothing appears. The program doesn't crashes or something like that. It simply does nothing. I have another Intent and this works perfectly. I don't know what the problem is.
I am using the onClick feature on the xml file
On the Main Activity:
public class MainActivity extends AppCompatActivity {
private Object TextView;
int eggcounter;
Button b1;
android.widget.TextView textClicks;
private Object SafeBrowsingResponse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button b1 = findViewById(R.id.b1);
eggcounter = 100;
final ImageButton ImgButton = findViewById(R.id.eggBtn);
ImgButton.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
eggcounter = eggcounter - 1;
updateEgg();
if (eggcounter < 80) {
ImgButton.setImageResource(R.drawable.egg_2);
if (eggcounter < 60){
ImgButton.setImageResource(R.drawable.egg_3);
if (eggcounter < 40) {
ImgButton.setImageResource(R.drawable.egg_4);
if (eggcounter < 15) { ImgButton.setImageResource(R.drawable.egg_5);
if (eggcounter <= 0) {
b1.setVisibility(View.VISIBLE);
ImgButton.setImageResource(R.drawable.egg_ende);
b1.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
}
}
);
}
}
}
}
}
}
}
);
}
public void updateEgg() {
textClicks = (TextView) findViewById(R.id.textScore);
textClicks.setText(eggcounter + " ");
}
public void backstartseite(View view) {
Intent back = new Intent(this, Startseite.class);
startActivity(back);
}
public void ende (View view) {
Intent e = new Intent(this, Ende.class);
startActivity(e);
}
}
You are never calling backStartSeite or ende therefore no Intent fires.
Also don't set the onClickListener of b1 inside another onClickListener (your listener for b1 will only be able to handle click events once the other button has been clicked already - this would confuse users).
If you want your Intent to work, call either startSeite or ende in the outer onClickListener.
I am making a quiz app when I pressing the answer it was not showing the next question directly it was going to done activity where the score of the quiz will be displayed. Please tell me what to do and the changes i have to made for it. Please tell me in detail and which line the problem causes, because I am still learning, plz And also suggest me some improvements.
public class Playing extends AppCompatActivity implements View.OnClickListener {
final static long INTERVAL = 1000; // 1sec = 1000
final static long TIMEOUT = 7000; // 7000 = 7sec
int progressValue = 0;
CountDownTimer mCountDown;
int index = 0, score = 0, thisQuestion = 0, totalQuestion, correctAnswer;
ProgressBar progressBar;
ImageView question_image;
Button btnA, btnB, btnC, btnD;
TextView txtScore, txtQuestionNum, question_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playing);
//View
txtScore = (TextView) findViewById(R.id.txtScore);
txtQuestionNum = (TextView) findViewById(R.id.txtTotalQuestion);
question_text = (TextView) findViewById(R.id.question_text);
question_image = (ImageView) findViewById(R.id.question_image);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnA = (Button) findViewById(R.id.btnAnswerA);
btnB = (Button) findViewById(R.id.btnAnswerB);
btnC = (Button) findViewById(R.id.btnAnswerC);
btnD = (Button) findViewById(R.id.btnAnswerD);
btnA.setOnClickListener(this);
btnB.setOnClickListener(this);
btnC.setOnClickListener(this);
btnD.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mCountDown.cancel();
if (index < totalQuestion) //still have question in List
{
Button clickedButton = (Button) view;
if (clickedButton.getText().equals(Common.questionList.get(index).getCorrectAnswer())) {
//Choose correct answer
score += 10;
correctAnswer++;
showQuestion(++index); //next question
} else {
//Choose wrong answer
Intent intent = new Intent(this, Done.class);
Bundle dataSend = new Bundle();
dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
}
private void showQuestion(int index) {
if (index < totalQuestion) {
thisQuestion++;
txtQuestionNum.setText(String.format(Locale.getDefault(), "%d / %d", thisQuestion, totalQuestion));
progressBar.setProgress(0);
progressValue = 0;
if (Common.questionList.get(index).getIsImageQuestion().equals("true")) {
//if is image
Picasso.get().load(Common.questionList.get(index).getQuestion()).into(question_image);
question_image.setVisibility(View.VISIBLE);
question_text.setVisibility(View.INVISIBLE);
} else {
question_text.setText(Common.questionList.get(index).getQuestion());
//If question is text,we will set image to invisible
question_image.setVisibility(View.INVISIBLE);
question_text.setVisibility(View.VISIBLE);
}
btnA.setText(Common.questionList.get(index).getAnswerA());
btnB.setText(Common.questionList.get(index).getAnswerB());
btnC.setText(Common.questionList.get(index).getAnswerC());
btnD.setText(Common.questionList.get(index).getAnswerD());
mCountDown.start(); //Start timer
} else {
//If it is final question
Intent intent = new Intent(this, Done.class);
Bundle dataSend = new Bundle();
dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
#Override
protected void onResume() {
super.onResume();
totalQuestion = Common.questionList.size();
mCountDown = new CountDownTimer(TIMEOUT, INTERVAL) {
#Override
public void onTick(long minisec) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
mCountDown.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
}
There is no onClickListener within your Activity. I would recommend creating a "next()" function, and then, for each of the buttons, do something along the lines of:
btn.setOnClickListener(new View.OnClickListener(){
next()
})
In an Android Studio app, I have following code:
boolean clicked = true;
Button btnumb1 = (Button) this.findViewById(R.id.numb1);
Button btnumb2 = (Button) this.findViewById(R.id.numb2);
Button btnumb3 = (Button) this.findViewById(R.id.numb3);
Button btnumb4 = (Button) this.findViewById(R.id.numb4);
btnumb1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicked = false;
}
});
Button Start = (Button) this.findViewById(R.id.Start);
Start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (clicked == false) {
Random rand = new Random();
int n = rand.nextInt(4) + 1;
TextView textView = (TextView) findViewById(R.id.randOutput);
textView.setText("" + n);
}
else{
Toast.makeText(getApplicationContext(), "You have to choose a number", Toast.LENGTH_LONG).show();
}
}
});
The idea is that when one of the 4 buttons is clicked, the int clicked is set to 1 and so the final button can only be clicked when it is 1.
But the code doesn't work like this; int clicked = 0; can't be accessed in other public void.
If one of the numbers 1,2,3,4 is clicked then final button can be clicked
The fix: Put public static boolean clicked = false;
under your public class YourClassName { line.
Reasoning: You need to learn how to scope your variables properly. You declared boolean clicked inside the onCreate() function, so the variable is gone after onCreate() is done running.
You should have put the clicked variable inside the class scope level, via public boolean clicked or public static boolean clicked so that even after the function returns, the value is saved.
I highly recommend a beginners java course or textbook before continuing on with your project(s).
Java does not have any concept of global variables. There is either an instance variable or a class variable. To define Global Variable you can make use of static Keyword.
static boolean clicked = true;
Button btnumb1 = (Button) this.findViewById(R.id.numb1);
Button btnumb2 = (Button) this.findViewById(R.id.numb2);
Button btnumb3 = (Button) this.findViewById(R.id.numb3);
Button btnumb4 = (Button) this.findViewById(R.id.numb4);
btnumb1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicked = false;
}
});
Button Start = (Button) this.findViewById(R.id.Start);
Start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (clicked == false) {
Random rand = new Random();
int n = rand.nextInt(4) + 1;
TextView textView = (TextView) findViewById(R.id.randOutput);
textView.setText("" + n);
}
else{
Toast.makeText(getApplicationContext(), "You have to choose a number", Toast.LENGTH_LONG).show();
}
}
});
Yes the variable int clicked = 0; has to be declared final before it is accessible in the other public void functions.
Try this declared a class say ClassClicked
public class ClassClicked {
int clicked;
public int getClicked() {
return clicked;
}
public void setClicked(int clicked) {
this.clicked = clicked;
}
}
Then changed
int clicked = 0;
to
final ClassClicked clicked = new ClassClicked();
clicked.setClicked(0);
And
clicked = 1;
to
clicked.setClicked(1);
Finally
clicked == 1
to
clicked.getClicked() == 1
so I started some Android programming with Java 7. I have Eclipse Juno (I think that's 4.2).
The problem is that it gives me an error "Multiple markers at this line
- Syntax error on token ")", ;
expected
- Syntax error on token ")", ;
expected
On the line with the sendMessage method. Here is the code:
public class MainActivity extends ActionBarActivity {
int counter;
Button login;
EditText username, password;
String success;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0;
username = (EditText)findViewById(R.id.getEmail);
password = (EditText)findViewById(R.id.getPassword);
login.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {
if(username.getText().toString().equals("admin") && password.getText().toString().equals("admin")){
success = "Successful";
counter = 0;
public void sendMessage (View view){
Intent intent = new Intent("com.example.linked1n.SCREENAFTLOG");
startActivity(intent);
};
} else {
counter++;
login.setText("Unsuccessful. Try again. " + 3-counter + " tries left.");
}
}
});
}
I haven't found a solution anywhere and I did exactly as the tutorial told me. I tried to clean the project thrice and restart eclipse/computer nothing worked.
Your calling method inside onclick is wrong so try below way :-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0;
username = (EditText)findViewById(R.id.getEmail);
password = (EditText)findViewById(R.id.getPassword);
login.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {
if(username.getText().toString().equals("admin") && password.getText().toString().equals("admin")){
success = "Successful";
counter = 0;
sendMessage(v);
} else {
counter++;
login.setText("Unsuccessful. Try again. " + 3-counter + " tries left.");
}
}
});
public void sendMessage (View view){
Intent intent = new Intent("com.example.linked1n.SCREENAFTLOG");
startActivity(intent);
}
You have 2 problems in your code :
You are not calling the function, just defining it, that too inside the onClick method, which you should not do.This problem can be resolved by calling the method inside the onClick and defining it outside the onClickListener.
You shouldn't terminate your sendMessage method declaration with a semi colon after the ending curly brace.This problem can be resolved by removing the semicolon from there.
So your code finally looks as below :
public class MainActivity extends ActionBarActivity {
int counter;
Button login;
EditText username, password;
String success;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0;
username = (EditText)findViewById(R.id.getEmail);
password = (EditText)findViewById(R.id.getPassword);
login.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {
if(username.getText().toString().equals("admin") && password.getText().toString().equals("admin")){
success = "Successful";
counter = 0;
sendMessage(v);//Method sendMesaage is called inside onClick
} else {
counter++;
login.setText("Unsuccessful. Try again. " + 3-counter + " tries left.");
}
}
});
//Definition of method sendMessage
public void sendMessage (View view){
Intent intent = new Intent("com.example.linked1n.SCREENAFTLOG");
startActivity(intent);
}//Removed semicolon from the method sendMessage
}
1.first a random number is selected.
2.the random number corresponds to a case (trivia question) in a switch statement.
3.the case has an onClick() for every possible answer.
4.when the correct answer (and it's corresponding onClick) is selected
I want the dice to roll again and progress the game to the next question.
5.My debug log says tells me the value of this dice rolled. However, I cannot get the view to change for the corresponding case in the switch.
`public class BeginGame extends Activity {
Random generator = new Random();
private static final String TAG = "MyActivity";
boolean dupe = true;
boolean done = false;
int intitializedQuestionValue = -2;
final int rows = 3;
final int columns = 25;
final int RIGHT = -2000;
final int WRONG = -1000;
int score = 0;
int num;
//define array of three rows and 25 columns
int[][] questionArray = new int [rows][columns];
int[] questionNumber = new int [25];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
final Button button0 = (Button) findViewById(R.id.button0);
final Button button1 = (Button) findViewById(R.id.button1);
final Button button2 = (Button) findViewById(R.id.button2);
final Button button3 = (Button) findViewById(R.id.button3);
final TextView text = (TextView) findViewById(R.id.TextView01);
//initialize "dice"
for (int i=0; i<25; i++){
questionNumber[i] = -1;
}
for(int i=0; i < columns; i++)
questionArray[0][i] = intitializedQuestionValue;
//set all questions to answered WRONG
for (int i=0; i <columns; i++)
questionArray[1][i] = WRONG;
rollDice();
loop: while (!done)
switch (num) {
case 0:
text.setText("press Virginia0:");
button0.setText("Alabama");
button0.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(BeginGame.this, "fail", Toast.LENGTH_SHORT).show(); rollDice();
//questionArray[2][0]= score -2;
}
});
button1.setText("Mississippi");
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(BeginGame.this, "fail", Toast.LENGTH_SHORT).show(); rollDice();
//questionArray[2][0]= score - 2;
}
});
button2.setText("Philadelphia");
button2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(BeginGame.this, "fail", Toast.LENGTH_SHORT).show(); rollDice();
//questionArray[2][0]= score -2;
}
});
button3.setText("Virginia");
button3.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(BeginGame.this, "success", Toast.LENGTH_SHORT).show(); rollDice();
//questionArray[1][0]=RIGHT;
//questionArray[2][0]= score + 5;
}
});
break loop;
case 1:
text.setText("press alabama1:");
button0.setText("Alabama");
button0.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(BeginGame.this, "success", Toast.LENGTH_SHORT).show(); rollDice();
}
});
button1.setText("Mississippi");
button1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
}
});
button2.setText("Philadelphia");
button2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
}
});
button3.setText("Virginia");
button3.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
}
});
break loop;
`
your program won't work this way. You have to understand more of android.
The onCreate method is called when an activity is created. ie : when it comes to front. It is executed on the UI thread : a thread that interacts with the user and should never be blocked. So, you are basically blocking the UI thread with your loop (does num ever change by the way ?).
What you should do is remove your while loop from the onCreate method. Just use it to initialize your activity, maybe data structures like questions and widgets and their listeners.
And now give more logic to your listeners : when a button is clicked then change your question and refresh the interface so that the new questions display. Do that until there is no more question to ask.
Do never block the UI Thread, make it free so users can use your app.