Button is not disabling in another activity - java

I'm beginner in android dev and i'm creating a pizza clicker game, just like cookie clicker. I created an activity for upgrades and for upgrading you need some amount of pizza like if you have 10 pizzas you can upgrade. If the amount of pizzas is equals the price the button is enabled, if not, the button is not enabled. When I click the button, the amount of pizza is decreased and the button should disable again, but it's not disabling.
Here's the first activity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
public static int pizza = 0;
public static TextView pizzaContText, helpers;
public static Button add, upgrades, exit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
}
private void initialize() {
add = (Button) findViewById(R.id.makePizza);
exit = (Button) findViewById(R.id.exitButton);
upgrades = (Button) findViewById(R.id.upgrades);
pizzaContText = (TextView) findViewById(R.id.pizzas);
helpers = (TextView) findViewById(R.id.helpers);
pizzaContText.setText("Pizzas: " + pizza);
pizzaContText.setTextColor(Color.BLACK);
pizzaContText.setTextSize(40);
helpers.setText("Helpers: " + Upgrades.contHelper);
helpers.setTextSize(20);
helpers.setTextColor(Color.BLACK);
add.setOnClickListener(this);
upgrades.setOnClickListener(this);
exit.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.makePizza:
pizza++;
pizzaContText.setText("Pizzas: " + pizza);
pizzaContText.setTextColor(Color.BLACK);
pizzaContText.setTextSize(40);
break;
case R.id.upgrades:
Intent i = new Intent(getApplicationContext(), Upgrades.class);
startActivity(i);
break;
case R.id.exitButton:
finish();
System.exit(0);
break;
}
}
}
And here's the second activity (the upgrades):
public class Upgrades extends AppCompatActivity implements View.OnClickListener{
public static int contHelper = 0, priceHelper = 10;
Button addHelper, back;
Handler h = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upgrades);
initialize();
if (MainActivity.pizza >= priceHelper){
//ENABLES THE BUTTON
addHelper.setEnabled(true);
} else{
//DISABLE THE BUTTON
addHelper.setEnabled(false);
}
}
private void initialize() {
addHelper = (Button) findViewById(R.id.addHelper);
addHelper.setText("Helper: " + priceHelper + " pizzas");
back = (Button) findViewById(R.id.back);
addHelper.setOnClickListener(this);
back.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.addHelper:
MainActivity.pizza-=priceHelper;
addHelper.setText("Helper: " + priceHelper + " pizzas");
priceHelper+=4;
contHelper++;
//Auto clicks the make pizza button every 1 sec
final Runnable r = new Runnable() {
#Override
public void run() {
MainActivity.add.performClick();
h.postDelayed(this, 1000);
}
};
h.postDelayed(r, 1000);
break;
case R.id.back:
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
break;
}
}
}

Don't use static objects.. Is the worst thing you could do.. Use bundle to send your variable
Intent activity = new Intent(this, Upgrades.class);
activity.putExtra("pizza", pizza);
startActivity(intent);
And in your Upgrades activity use
Bundle extras = getIntent().getExtras();
int pizza = extras.getInt("pizza");
And check for nulls and that you send the correct things.

Related

Trying to pass EditText value to two different activities with one button in Android Studio using JAVA

I want to pass EditText values to two different activities with "submit" button. So far i've managed to pass on to one of the activities. But when I enter second activity values aren't passed. There's nothing passed. Below there will be four activities: "TwoTeam"(activity where user enters data in textedit.), "Begin"(first activity where I want to pass values.), "BeginAfter"(activity where is one minute timer and after timer reaches 0 it will navigate user to next activity), "Begindup"(second activity where i want to pass those text values. Activity where is the problem. It doesn't shows values.). Here is activity "TwoTeam":
public class TwoTeam extends AppCompatActivity {
EditText first_name, second_name;
String name_first;
String name_second;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two_team);
first_name = findViewById(R.id.first_name);
second_name = findViewById(R.id.second_name);
}
public void submit_button(View view) {
name_first = first_name.getText().toString();
name_second = second_name.getText().toString();
Intent in = new Intent(TwoTeam.this, Begindup.class);{
in.putExtra("name1", name_first);
in.putExtra("name2", name_second);
in.putExtra("turn2", name_second + "'s Turn");
}
Intent intent = new Intent(TwoTeam.this, Begin.class);{
intent.putExtra("name1", name_first);
intent.putExtra("name2", name_second);
intent.putExtra("turn1", name_first + "'s Turn");
startActivity(intent);
}
}
}
Here's activity "Begin":
public class Begin extends AppCompatActivity {
private TextView first_name, second_name, turn, words;
String name_first, name_second, turns;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_begin);
first_name = findViewById(R.id.name_first);
second_name = findViewById(R.id.name_second);
turn = findViewById(R.id.turn1);
name_first = getIntent().getStringExtra("name1");
first_name.setText(name_first);
name_second = getIntent().getStringExtra("name2");
second_name.setText(name_second);
turns = getIntent().getStringExtra("turn1");
turn.setText(turns);
}
public void start_button(View view) {
Intent intent = new Intent(this, BeginAfter.class);{
startActivity(intent);
}
}
}
Here's activity "BeginAfter":
public class BeginAfter extends AppCompatActivity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_begin_after);
textView = findViewById(R.id.timer);
long duration = TimeUnit.MINUTES.toMillis(1);
new CountDownTimer(duration, 1000) {
#Override
public void onTick(long l) {
String sDuration = String.format(Locale.ENGLISH, "%01d", TimeUnit.MILLISECONDS.toSeconds(l) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(l)));
textView.setText(sDuration);
}
#Override
public void onFinish() {
startActivity(new Intent(BeginAfter.this, Begindup.class));
}
}.start();
}
}
Aaand here's activity "Begindup":
public class Begindup extends AppCompatActivity {
private TextView first_name, second_name, turn, words;
String name_first, name_second, turns;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_begindup);
first_name = findViewById(R.id.name_first);
second_name = findViewById(R.id.name_second);
turn = findViewById(R.id.turn2);
name_first = getIntent().getStringExtra("name1");
first_name.setText(name_first);
name_second = getIntent().getStringExtra("name2");
second_name.setText(name_second);
turns = getIntent().getStringExtra("turn2");
turn.setText(turns);
}
}

How to avoid an activity to reload every time i get into it?

Hello I have an activity which shows some listviews, and I want them not to reload/refresh every time I get into it, as it is programmed to show different items every time.
But I want it not to refresh until a button which is in another activity is pushed.
I've not tried anything yet as I don't know what to start with.
Here I leave you the code of the java.class:
public class Comida extends AppCompatActivity implements Adaptador2.OnRecipeListener {
private RecyclerView recyclerView1;
List<Entidad2> listItems;
Adaptador2 adaptor;
private Entidad2 entidad1,entidad2,entidad3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
String myValue = savedInstanceState.getString("key");
}
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_comida);
recyclerView1 = findViewById(R.id.lv_1);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView1.setLayoutManager(layoutManager);
listItems = new ArrayList<>();
entidad1 = new Entidad2(R.drawable.calabacines_3, "Solomillo a la plancha", " 10 min.", 4, 20);
entidad2 = new Entidad2(R.drawable.patatas_deluxe_especiadas_70523_300_150, "Entrecot", " 15 min.", 2, 50);
entidad3 = new Entidad2(R.drawable.tomate, "Hamburguesa", " 2 min.", 5, 100);
listItems.add(entidad1);
listItems.add(entidad2);
listItems.add(entidad3);
adaptor = new Adaptador2(listItems, this);
recyclerView1.setAdapter(adaptor);
adaptor.notifyDataSetChanged();
pickEntidad();
}
#Override
public void OnRecipe(int priority) {
if (priority == 20) {
Intent in = new Intent(this, Solomillo.class);
startActivity(in);
}
if (priority == 50) {
Intent in = new Intent(this, Entrecot.class);
startActivity(in);
}
if (priority == 100) {
Intent in = new Intent(this, Hamburguesa.class);
startActivity(in);
}
}
private void pickEntidad(){
final int random = new Random().nextInt(101);
int priority1 = entidad1.getPriority();
int priority2 = entidad2.getPriority();
int priority3 = entidad3.getPriority();
listItems.clear();
if(random < priority1){
listItems.add(entidad1);
}else if(random < priority2){
listItems.add(entidad2);
}else if (random <= priority3){
listItems.add(entidad3);
}
adaptor.notifyDataSetChanged();
}
}
And then here there is the java.class of the other activity(the one which contains the button that has to refresh the other activity):
The button which I want to use to refresh the activity is the boton_prueba.
public class Menu extends AppCompatActivity {
Button boton_start;
Button boton_refresh;
Button boton_prueba;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
boton_start=(Button) findViewById(R.id.boton_platos);
boton_refresh = (Button) findViewById(R.id.boton_cambiarmenu);
boton_prueba=(Button) findViewById(R.id.boton_menu);
boton_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(Menu.this,Dishes.class);
startActivity(in);
}
});
boton_prueba.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(Menu.this,Comida.class);
startActivity(in);
}
});
boton_refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//What to do?
}
});
}
}
Please if anyone has any idea of how to do it help me and in case you need more code or information just tell me.
Thank you.
If I really understand you then you want to execute pickEntidad() method when pressing in refresh button and go to this activity so you can do that using send any number or data with the intent like:
Intent in = new Intent(currentActivity.this,targetActivity.class);
in.putExtra("number",2);
startActivity(in);
and in target activity use somthing like this:
if(getIntent().getIntExtra("number",-1) ==2)
{
// what do you want to do...
}

Why doesn't the intent of the button work

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 A,B,C,D it was not showing the next one

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

How to implement "turn off music" button Android

I want to add a button in my application that turns off the music but I don't know how to approach it, I have an idea but I'm sure it's far from best so I want to consult with you. The situation is as follows:
public class MainActivity extends Activity implements OnClickListener {
MediaPlayer easysong;
MediaPlayer normalsong;
MediaPlayer hardsong;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.land_main);
mContext = this;
restartButton = (Button)findViewById(R.id.restartButton);
restartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
easysong = MediaPlayer.create(MainActivity.this, R.raw.arideniro);
normalsong = MediaPlayer.create(MainActivity.this, R.raw.junior);
hardsong = MediaPlayer.create(MainActivity.this, R.raw.ketsathis);
counter = 101;
i = 500 - dif;
new Thread(new Runnable() {
public void run() {
if(i==500){
easysong.start();}
else if(i==375){
normalsong.start();
}else if(i==250){
hardsong.start();
}
while (counter > 0) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter--;
runOnUiThread(new Runnable() {
#Override
public void run() {
scoreText.setText(Integer.toString(counter));
}
});
if(i>150){
i/=1.01;}
else if(i>90-(dif/10)){
i-=1;
}
}if (counter==0) {
mChronometer.stop();
if(easysong.isPlaying()) {
easysong.stop();
easysong.release();
easysong = null;
}else if(normalsong.isPlaying()){
normalsong.stop();
normalsong.release();
normalsong = null;
}else if(hardsong.isPlaying()){
hardsong.stop();
hardsong.release();
hardsong = null;
}
This is the main class of my app where the mediaplayer is used, now I deleted much of the code because it was irrelevant to the mediaplayer and the question, so don't look for the missing brackets and such. And this here is the main menu class where the Switch that will turn on and off the music will be located:
public class MainMenu extends Activity{
private Button easy;
private Button normal;
private Button hard;
private Button scores;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
easy = (Button) findViewById(R.id.btn_easy);
scores = (Button) findViewById(R.id.btn_highscores);
easy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dif = 0;
startGame();
}
});
}
public void startGame() {
Intent intent = new Intent(MainMenu.this, MainActivity.class);
startActivity(intent);
}
So my idea is simnple, to add a variable in MainActivity like "int p;" and from the MainMenu class to change it's state between 0 and 1, then I will add around each line that starts music an if(p==1) but is this a good approach ? Also I would like the value of the int to be saved when the app is closed

Categories

Resources