Check all the view's background in an if statement in Android? - android
I have many buttons(81) from the left and right part of my layout. All in all, I have 162 buttons. I put those buttons to Button[] and I handle it properly.
private int[] right_lung = { R.id.btn_right_106, R.id.btn_right_113,
R.id.btn_right_114, R.id.btn_right_115, R.id.btn_right_116, R.id.btn_right_121,
R.id.btn_right_122, R.id.btn_right_123, R.id.btn_right_124, R.id.btn_right_125,
R.id.btn_right_129, R.id.btn_right_130, R.id.btn_right_131, R.id.btn_right_132,
R.id.btn_right_133, R.id.btn_right_134, R.id.btn_right_137, R.id.btn_right_138,
R.id.btn_right_139, R.id.btn_right_140, R.id.btn_right_141, R.id.btn_right_142,
R.id.btn_right_143, R.id.btn_right_145, R.id.btn_right_146, R.id.btn_right_147,
R.id.btn_right_148, R.id.btn_right_149, R.id.btn_right_150, R.id.btn_right_151,
R.id.btn_right_152, R.id.btn_right_153, R.id.btn_right_154, R.id.btn_right_155,
R.id.btn_right_156, R.id.btn_right_157, R.id.btn_right_158, R.id.btn_right_159,
R.id.btn_right_160, R.id.btn_right_161, R.id.btn_right_162, R.id.btn_right_163,
R.id.btn_right_164, R.id.btn_right_165, R.id.btn_right_166, R.id.btn_right_167,
R.id.btn_right_168, R.id.btn_right_169, R.id.btn_right_170, R.id.btn_right_171,
R.id.btn_right_172, R.id.btn_right_173, R.id.btn_right_174, R.id.btn_right_175,
R.id.btn_right_176, R.id.btn_right_177, R.id.btn_right_178, R.id.btn_right_179,
R.id.btn_right_180, R.id.btn_right_181, R.id.btn_right_182, R.id.btn_right_183,
R.id.btn_right_184, R.id.btn_right_185, R.id.btn_right_186, R.id.btn_right_187,
R.id.btn_right_188, R.id.btn_right_189, R.id.btn_right_190, R.id.btn_right_191,
R.id.btn_right_192, R.id.btn_right_194, R.id.btn_right_195, R.id.btn_right_196,
R.id.btn_right_197, R.id.btn_right_198, R.id.btn_right_199, R.id.btn_right_200,
R.id.btn_right_205, R.id.btn_right_206, R.id.btn_right_207 };
private Button[] btn_right = new Button[right_lung.length];
private int[] left_lung = { R.id.btn_left_7, R.id.btn_left_13, R.id.btn_left_14,
R.id.btn_left_15, R.id.btn_left_16, R.id.btn_left_20, R.id.btn_left_21,
R.id.btn_left_22, R.id.btn_left_23, R.id.btn_left_24, R.id.btn_left_27,
R.id.btn_left_28, R.id.btn_left_29, R.id.btn_left_30, R.id.btn_left_31,
R.id.btn_left_32, R.id.btn_left_34, R.id.btn_left_35, R.id.btn_left_36,
R.id.btn_left_37, R.id.btn_left_38, R.id.btn_left_39, R.id.btn_left_40,
R.id.btn_left_41, R.id.btn_left_42, R.id.btn_left_43, R.id.btn_left_44,
R.id.btn_left_45, R.id.btn_left_46, R.id.btn_left_47, R.id.btn_left_48,
R.id.btn_left_49, R.id.btn_left_50, R.id.btn_left_51, R.id.btn_left_52,
R.id.btn_left_53, R.id.btn_left_54, R.id.btn_left_55, R.id.btn_left_56,
R.id.btn_left_57, R.id.btn_left_58, R.id.btn_left_59, R.id.btn_left_60,
R.id.btn_left_61, R.id.btn_left_62, R.id.btn_left_63, R.id.btn_left_64,
R.id.btn_left_65, R.id.btn_left_66, R.id.btn_left_67, R.id.btn_left_68,
R.id.btn_left_69, R.id.btn_left_70, R.id.btn_left_71, R.id.btn_left_72,
R.id.btn_left_73, R.id.btn_left_74, R.id.btn_left_75, R.id.btn_left_76,
R.id.btn_left_77, R.id.btn_left_78, R.id.btn_left_79, R.id.btn_left_80,
R.id.btn_left_81, R.id.btn_left_82, R.id.btn_left_83, R.id.btn_left_84,
R.id.btn_left_85, R.id.btn_left_86, R.id.btn_left_87, R.id.btn_left_88,
R.id.btn_left_89, R.id.btn_left_90, R.id.btn_left_91, R.id.btn_left_92,
R.id.btn_left_93, R.id.btn_left_94, R.id.btn_left_95, R.id.btn_left_98,
R.id.btn_left_99, R.id.btn_left_100, };
private Button[] btn_left = new Button[left_lung.length];
Whenever I click on the button, just like in mine sweeper game, many buttons are randomly opened. And when it is opened, I am changing its background into R.drawable.affected. The goal of the game is to open all the buttons in left and right. My question is this, how can I check if all of the buttons are set in R.drawable.affected? Because after that, I will execute a method that will congratulate the user. Thanks in advance.
EDIT:
for (int i = 0; i < btn_right.length; i++) {
final int a = i;
int counter_total_affected = 0;
btn_right[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (counter == 1) {
right_lung.add(a);
btn_right[a].setBackgroundResource(R.drawable.affected);
counter_total_affected++;
} else if (counter == 2) {
for (int i = 0; i < 2; i++) {
int n = i;
right_lung.add(a + n);
}
try {
for (int i = 0; i < 2; i++) {
int n = i;
btn_right[a + n].setBackgroundResource(R.drawable.affected);
counter_total_affected++;
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (counter == 3) {
right_lung.add(a);
btn_right[a].setBackgroundResource(R.drawable.affected);
counter_total_affected++;
} else if (counter == 4) {
for (int i = 0; i < 25; i++) {
int n = i;
right_lung.add(a + n);
}
try {
for (int i = 0; i < 25; i++) {
int n = i;
btn_right[a + n].setBackgroundResource(R.drawable.affected);
counter_total_affected++;
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (counter == ...) {
//statements...
} else if (counter_total_affected == (btn_left.length + btn_right.length)) {
//CONGRATULATORY METHOD
}
counter++;
}
}
Increment the counter each time you change background of button and compare its value with length of button array. if both are same that means, all button backgrounds are set.
Try this :
for (int i = 0; i < btn_right.length; i++) {
final int b = i;
btn_right[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if btn_right[i].getDrawable().getConstantState().equals
(getResources().getDrawable(R.drawable.affected).getConstantState()))
{
if(counter == btn_right.length){
//Congratulate user...
}
}else{
btn_right[b].setBackgroundResource(R.drawable.affected);
counter++;
}
}
}
U can set Tag:
for (int i = 0; i < btn_right.length; i++) {
final int b = i;
btn_right[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (counter == 1) {
right_affected.add(b);
btn_right[b].setBackgroundResource(R.drawable.affected);
btn_right[b].setTag('1');
} else {
//some stuff here...
}
}
}
after congratulate the user set its Tag to 0.
EDIT:
ArrayList<Integer> arrayofId =new ArrayList<Integer>();
#Override
public void onClick(View v) {
if (counter == 1) {
right_affected.add(b);
btn_right[b].setBackgroundResource(R.drawable.affected);
arrayofId.add(b);//need to convert int to Integer.
} else {
//some stuff here...
}
}
To congratulate:
for(int i=0;i<arrayofId.size();i++)
{
// you can get here id of effected buttons
}
Related
Recursive(Tower Hanoi) UI for android
`[I want to change the UI through the recursive function. I want to implement UI through recursive function. When you run it, you should see the process of changing the UI according to the value, but if you insert hanoi(), the process does not come out and the value is printed at once. I think I need to change the move, but it's the same if I put sleep() in the move, and I tried Thread, Handler, AsyncTask, but the results are the same. I'd appreciate your help. public class Disk3 extends AppCompatActivity { #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); class BackgroundThread extends Thread { boolean running = false; #Override public void run() { running = true; while (running) { runOnUiThread(new Runnable() { #Override public void run() { move(3, 1, 3); } }); try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } btn_move.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { BackgroundThread thread = new BackgroundThread(); thread.start(); } }); public void move(int N, int start, int to) { if (start == 1) { for (int i = 0; i <= 2; i++) { if (list_tv_diskA[i].getVisibility() == View.VISIBLE) { startTv = list_tv_diskA[i]; startTv.setVisibility(View.INVISIBLE); Log.d("TAG", "list_tv_disk A :: " + i); break; } } } if (start == 2) { for (int j = 0; j <= 2; j++) { if (list_tv_diskB[j].getVisibility() == View.VISIBLE) { startTv = list_tv_diskB[j]; startTv.setVisibility(View.INVISIBLE); Log.d("TAG", "list_tv_disk B :: " + j); break; } } } if (start == 3) { for (int k = 0; k <= 2; k++) { if (list_tv_diskC[k].getVisibility() == View.VISIBLE) { startTv.setText(toTv.getText()); startTv = list_tv_diskC[k]; startTv.setVisibility(View.INVISIBLE); Log.d("TAG", "list_tv_disk C :: " + k); break; } } } if (to == 1) { for (int i = 2; i >= 0; i--) { if (list_tv_diskA[i].getVisibility() == View.INVISIBLE) { toTv = list_tv_diskA[i]; toTv.setText(startTv.getText()); toTv.setVisibility(View.VISIBLE); Log.d("TAG", "list_tv_disk B :: " + i); break; } } } if (to == 2) { for (int j = 2; j >= 0; j--) { if (list_tv_diskB[j].getVisibility() == View.INVISIBLE) { toTv = list_tv_diskB[j]; toTv.setText(startTv.getText()); toTv.setVisibility(View.VISIBLE); Log.d("TAG", "list_tv_disk Bda :: " + j); break; } } } if (to == 3) { for (int k = 2; k >= 0; k--) { if (list_tv_diskC[k].getVisibility() == View.INVISIBLE) { toTv = list_tv_diskC[k]; toTv.setText(startTv.getText()); toTv.setVisibility(View.VISIBLE); Log.d("TAG", "list_tv_disk C :: " + k); break; } } } public void Hanoi(int N, int start, int to, int via) { if (N == 1) { move(1, start, to); return; } else { Hanoi(N - 1, start, via, to); move(N, start, to); Hanoi(N - 1, via, to, start); } }
How to call text Watcher when user update any value from edit text
i have button,on button click it create editText with value, value of edit text is depending on count of total edit texts.for example edittext1 = 100, when user create two edit text then the value will be like this edittext1 = 50,edittext2 = 50 and so on.( value = 100/ total no of edittext) which i set equally to each edit text.now the problem is when user want to change/update any value from edittext, i want to update value of each edittext according to user's newly entered value. i want to call textwatcher when value changed by only user,in my case when user click on button it will call. thank you. here is my code public class StageForm extends BaseActivity implements View.OnClickListener { #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.stage_form); spinnerProjectStage = (Spinner) findViewById(R.id.spinnerAddProjectStage); spinnerProjectList = (Spinner) findViewById(R.id.spinnerProjectList); stageLinearLayout = (LinearLayout) findViewById(R.id.stageProjectList); btnAddMoreStage = (Button) findViewById(R.id.btnAddMoreStage); btnAddMoreStage.setOnClickListener(this); getProjectStage(); } public void onClick(View v) { if (v.getId() == R.id.btnAddMoreStage) { public void addMoreFields () { try { k++; flag = k; final LinearLayout.LayoutParams lparams; lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); layout[flag] = new LinearLayout(StageForm.this); layout[flag].setLayoutParams(lparams); layout[flag].setId(flag); txtStageName[flag] = new EditText(StageForm.this); txtStageName[flag].setLayoutParams(lparams); txtStageName[flag].setHint("stage " + k + ""); txtStageName[flag].setId(flag); txtStagePercent[flag] = new EditText(StageForm.this); txtStagePercent[flag].setLayoutParams(lparams); txtStagePercent[flag].setHint("percent"); txtStagePercent[flag].setId(flag); txtStagePercent[flag].addTextChangedListener(stagePercentChangeListener); if (flag == 0) { txtStagePercent[flag].setText(String.valueOf(totalPercent)); } else { countEditText = flag + 1; calculatePercentage(countEditText, flag); } } catch (Exception e) { e.printStackTrace(); } layout[flag].addView(txtStageName[flag]); layout[flag].addView(txtStagePercent[flag]); stageLinearLayout.addView(layout[flag]); } } } private void calculatePercentage(int countEditText, int flag) { k = flag; if (flag == 0) { // countEditText = flag; lastTextBox = countEditText; } else { // countEditText = flag; lastTextBox = countEditText - 1; } result = totalPercent / countEditText; convertFloatResult = Math.round(result); remainingPercent = totalPercent - (convertFloatResult * countEditText); lastTextValue = convertFloatResult + remainingPercent; try { if (remainingPercent == 0) { for (int j = 0; j <= lastTextBox; j++) { txtStagePercent[j].setText(String.valueOf(convertFloatResult)); } txtStagePercent[lastTextBox].setText(String.valueOf(lastTextValue)); } else { for (int j = 0; j < lastTextBox; j++) { txtStagePercent[j].setText(String.valueOf(convertFloatResult)); } txtStagePercent[lastTextBox].setText(String.valueOf(lastTextValue)); } } catch (Exception e) { e.printStackTrace(); } } private TextWatcher stagePercentChangeListener = new TextWatcher() { #Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { if (flag == 0) { } else { String getbeforValue = String.valueOf(s); beforeTextChanged = Integer.parseInt(getbeforValue); } } #Override public void onTextChanged(CharSequence s, int start, int before, int count) { String getchangedValue = String.valueOf(s); afterTextChanged = Integer.parseInt(getchangedValue); } #Override public void afterTextChanged(Editable s) { totalPercent = totalPercent - afterTextChanged; countEditText = countEditText - 1; calculatePercentage(countEditText, flag); } }; }
How to solve this scenario on Android Studio?
Click on red button 2 times and green button 3 times after this click on yellow button 5 times. If this done successfully you go on next screen for next quiz.
Assuming your buttons already connected to corresponding functions in Android Manifest private int redClicks = 0; private int greenClicks = 0; private int yellowClicks = 0; public void redClickCount(View view) { if (redClicks < 2){ redClicks++; } greenClicks = 0; yellowClicks = 0; } public void greenClickCount(View view) { if (redClicks == 2 && greenClicks < 3){ greenClicks++; } else { //start all over again redClicks = 0; greenClicks = 0; yellowClicks = 0; } } public void yellowClickCount(View view) { if (redClicks == 2 && greenClicks == 3 && yellowClicks <5){ yellowClicks++; } else { if (redClicks == 2 && greenClicks == 3 && yellowClicks = 5){ // go to next round } else { //start all over again redClicks = 0; greenClicks = 0; yellowClicks = 0; } } }
Multiple loops not giving desired Result
I am working on a methods in which when I use a single loop with condition it checks both if and else conditions. But when I add more than one loop with condition it only checks else condition I do not know where is problem. please help me for that here is my code public void compareArray() { ArrayList<Boolean> subset = new ArrayList<>(); for (int j = 0; j < (arrayBeef1.length); j++) { for (int i = 0; i < Items.size(); i++) { if ((arrayBeef1[j].equals(Items.get(i)))) { subset.add(true); break; } } } if (subset != null) { if (arrayBeef1.length == subset.size()) { Intent nextClass = new Intent(); nextClass.setClass(AddItem.this, BeefRecipes.class); startActivity(nextClass); finish(); } else { Toast.makeText(getApplicationContext(), "Un-Matched", Toast.LENGTH_LONG).show(); } } for(int j = 0 ; j < (arrayBeef2.length) ; j++) { for (int i = 0; i < Items.size(); i++) { if ((arrayBeef2[j].equals(Items.get(i)))) { subset.add(true); break; } } } if (subset != null) { if (arrayBeef2.length == subset.size()) { Intent nextClass = new Intent(); nextClass.setClass(AddItem.this, BeefRecipes.class); startActivity(nextClass); finish(); } else { Toast.makeText(getApplicationContext(), "Un-Matched", Toast.LENGTH_LONG).show(); } } where Item array is dynamic array which is populated through spinner and beefArray1 and two are String[] arrayBeef1 = { "carrot","ginger", "onion","beef","unsalted butter"}; String[] arrayBeef2 = { "garlic","olive oil", "onion", "Dijon mustard","beef","salt","carrot","rosemary"}; and Items arraList is produced with similar items please help what should I do with this method
Application randomly stops responding.
I am new to programming and I'm making a very simple blackjack game with only basic functions. When I run the program on the emulator it runs maybe for one hand, two, sometimes 5 or more but it always stops responding at some stage when i click on one of the three butons. There is a splash screen that runs for three seconds and the there is a thread comming from that activity that starts this menu activity. Could anyone maybe tell why this is happening? It usually happens when I clcik on one of the buttons even though there is no much comput protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.main); btDeal = (Button) findViewById(R.id.deal); playerCards1 = (TextView) findViewById(R.id.playerCards); playerPoints = (TextView) findViewById(R.id.playerPoints); dealerCards1 = (TextView) findViewById(R.id.dealerCard); mpBusted= MediaPlayer.create(this, R.raw.busted); mpWin = MediaPlayer.create(this, R.raw.win); mpShuffling = MediaPlayer.create(this, R.raw.shuffling); mpEven = MediaPlayer.create(this, R.raw.even); mpHit= MediaPlayer.create(this, R.raw.hit); btDeal.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub deal (); } }); //getTotalDealerCards() //getTotalPlayerCards() btHit = (Button) findViewById(R.id.hit); btHit.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub Boolean busted = isBusted(); if(!busted){ hitPlayer(); playerCards1.setText(getPlayerCardsToString()); if (isBusted()){ mpBusted.start(); }else{ playerCards1.setText(getPlayerCardsToString()); playerPoints.setText(Integer.toString(getTotalPlayerPoints())); } } } }); btStand = (Button) findViewById(R.id.stand); btStand.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub checkWinner(); }// testValue(getTotalPlayerCards()) }); } /*********** Function declarations starts here **********/ //Sum and return the total points for the dealer cards public int getTotalDealerPoints(){ int points = 0; int aceFlag = 0; //flag to deal with Aces int counter; for (counter = 0; counter <= getTotalDealerCards(); counter++){ if (dealerCards [counter].getCard() + 1 == 1){ points += 11; aceFlag++; } else if (dealerCards [counter].getCard() + 1 > 10) points += 10; else points += dealerCards [counter].getCard() + 1; } do { if (points > 21 && aceFlag > 0){ points -= 10; aceFlag--; } } while (aceFlag>0); return points; } //Get the total player points deal public int getTotalPlayerPoints(){ int points = 0; int aceFlag = 0; //flag to deal with Aces int counter; for (counter = 0; counter <= getTotalPlayerCards(); counter++){ if (playerCards [counter].getCard() + 1 == 1){ points += 11; aceFlag++; } else if (playerCards [counter].getCard() + 1 > 10) points += 10; else points += playerCards [counter].getCard() + 1; } do { if (points > 21 && aceFlag > 0){ points -= 10; aceFlag--; } } while (aceFlag>0); return points; } //Deal function to start hand public void deal (){ // If deal is pressed reset all and start over. mpShuffling.start(); totalDealerPoints = 0; totalPlayerPoints = 0; totalCreatedCards = 0; for (int i = 0; i < TOTAL_CARDS; i++){ dealerCards [i] = null; playerCards [i] = null; createdCards [i] = null; } // create dealer & player cards and save them to dealer, player and total arrays. for (int dealcounter = 0; dealcounter <=1 ; dealcounter++){ dealerCards[dealcounter]= createCard(); addCardToCreatedCards(dealerCards[dealcounter]); playerCards[dealcounter] = createCard(); addCardToCreatedCards(playerCards[dealcounter]); } String theCards = getPlayerCardsToString(); String dealerCard = dealerCards[0].toString(); String playerpoints= Integer.toString(getTotalPlayerPoints()); playerCards1.setText(theCards); dealerCards1.setText(dealerCard); playerPoints.setText(playerpoints);//getTotalPlayerPoints() while (getTotalDealerPoints() < 16){ hitDealer(); } } // Create card and validate against existing before returning object. public Card createCard(){ int counter2 = 0; int flag = 0; int value; int suit; do { flag = 0; suit = randomer.nextInt(4); value = randomer.nextInt(13); // validate against permitted values before creating cards while (counter2 <= getTotalPlayerCards()) { if (createdCards[counter2].getSuit() == suit && createdCards[counter2].getCard() == value || suit > 3 || suit < 0 || value > 12 || value < 0){ flag = -1; } counter2++; } } while (flag != 0); Card theCard = new Card (suit, value); return theCard; } // Add card to the records of created cards public void addCardToCreatedCards(Card aCard){ createdCards [totalCreatedCards] = aCard; totalCreatedCards++; } // Add a card to dealers cards public void hitPlayer(){ //If the hand was started add card, else deal to start hand. if (getTotalPlayerCards()+1 != 0){ mpHit.start(); playerCards [getTotalPlayerCards()+1] = createCard(); addCardToCreatedCards(playerCards [getTotalPlayerCards()]); } else deal(); } // Create a new card for the dealer public void hitDealer(){ dealerCards [getTotalDealerCards()+1] = createCard(); addCardToCreatedCards(dealerCards [getTotalDealerCards()]); } public String getPlayerCardsToString(){ String cards = ""; int total = getTotalPlayerCards(); if (getTotalPlayerPoints() <=21){ int counter = 0; while (counter <= total){ cards += playerCards[counter].toString() + " "; counter++; } return cards; }else { int counter=0; while (counter <= total){ cards += playerCards[counter].toString() + " "; counter++; } return cards; } } public int getTotalPlayerCards(){ int initialCount = 0; while (playerCards[initialCount] != null){ initialCount++; } return initialCount-1; } public int getTotalDealerCards(){ int initialCount = 0; while (dealerCards[initialCount] != null){ initialCount++; } return initialCount-1; } public int getTotalCreatedCards(){ int initialCount = 0; while (createdCards[initialCount] != null){ initialCount++; } return initialCount-1; } public Boolean isBusted(){ Boolean busted = false; if (getTotalPlayerPoints()>21){ busted=true; totalDealerPoints = 0; totalPlayerPoints = 0; mpBusted.start(); playerPoints.setText("You were busted!!"); for (int i = 0; i < TOTAL_CARDS; i++){ dealerCards [i] = null; playerCards [i] = null; createdCards [i] = null; } } return busted; } //Check for winner public void checkWinner(){ if (getTotalDealerPoints() <= 21 || getTotalPlayerPoints() <= 21 && !isBusted()){ if (getTotalDealerPoints() > 21 || getTotalDealerPoints() < getTotalPlayerPoints()){ playerPoints.setText("You won!!"); mpWin.start(); } else if(getTotalDealerPoints() > getTotalPlayerPoints()){ mpBusted.start(); playerPoints.setText("You were busted!!"); for (int i = 0; i < TOTAL_CARDS; i++){ dealerCards [i] = null; playerCards [i] = null; createdCards [i] = null; } } else{ mpEven.start(); playerCards1.setText("We have same points!"); } } else { deal (); } } }
Use the debugger in eclipse to find out where it gets frozen. Also the android emulator is very slow even with a fast PC.
Try using the low resolution simulators. open DDMS from the android-sdk\tools and check which method or thread is taking more time to execute. Use AsyncTask or Handler when there is a functional(Computational) things running.