I have an application where I set up the user interface completely programmatically, meaning I didn't draw the objects in XML. It works perfectly fine, but since I drew the objects in the content with different classes, I need to establish communication between the two classes. For example, if I press a button in Class1, I want to write the text on the button in Class2 and trigger the button in Class2 based on that. I think using an interface is the most logical solution for this, but I'm unable to transfer the data from Class1 to Class2 using the interface. I'm getting an error saying 'cannot be cast to...'
My GameInterface:
public interface GameInterface {
void seciliHucreyiDoldur(String seciliHucreyiDoldur);
}
Class1:
private class Cell implements GameInterface {
int value;
boolean fixed;
Button btn;
String hucreyiDolduracakVeri;
Context THIS;
public Cell(int initValue, Context THIS) {
this.THIS = THIS;
value = initValue;
if (value != 0) {
fixed = true;
} else {
fixed = false;
}
btn = new Button(THIS);
btn.setTextSize(16);
if (fixed) {
btn.setText(String.valueOf(value));
}
txtSayac.setGravity(Gravity.CENTER);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (fixed) {
Toast.makeText(THIS, "Bu hücreyi değiştiremezsiniz!", Toast.LENGTH_SHORT).show();
return;
}
/*value++;
if (value > 9) {
value = 1;
}*/
btn.setBackgroundResource(R.drawable.hucre_arkaplani_kirmizimsi);
btn.setTextColor(Color.BLACK);
btn.setText(hucreyiDolduracakVeri);
btn.setTextColor(Color.RED);
if (correct()) {
textView.setText("");
} else {
textView.setText("Tekrar eden rakamlar var, kontrol etmelisin!");
}
}
});
}
#Override
public void seciliHucreyiDoldur(String seciliHucreyiDoldur) {
this.hucreyiDolduracakVeri = seciliHucreyiDoldur;
Toast.makeText(THIS, hucreyiDolduracakVeri, Toast.LENGTH_SHORT).show();
if (fixed) {
//Toast.makeText(THIS, "Bu hücreyi değiştiremezsiniz!", Toast.LENGTH_SHORT).show();
return;
}
/*value++;
if (value > 9) {
value = 1;
}*/
btn.setTextColor(Color.BLACK);
btn.setText(seciliHucreyiDoldur);
btn.setTextColor(Color.RED);
btn.setBackgroundResource(R.drawable.hucre_arkaplani_mavi_acik);
if (correct()) {
textView.setText("");
} else {
textView.setText("Tekrar eden rakamlar var, kontrol etmelisin!");
}
}
#Override
public void hucreSeciliMi(boolean hucreSecilimi) {
}
}
Class2:
public class AltBolumNumericTablo implements GameInterface{
Button btnClick;
boolean onClicked;
int value;
Activity activity;
GameInterface gameInterface;
public AltBolumNumericTablo(int value, Context THIS, Activity activity) {
this.activity = activity;
this.value = value;
btnClick = new Button(THIS);
btnClick.setTextSize(24f);
gameInterface = (GameInterface) activity;
switch (value) {
case 0:
btnClick.setText("1");
break;
case 1:
btnClick.setText("2");
break;
case 2:
btnClick.setText("3");
break;
case 3:
btnClick.setText("4");
break;
case 4:
btnClick.setText("5");
break;
case 5:
btnClick.setText("6");
break;
case 6:
btnClick.setText("7");
break;
case 7:
btnClick.setText("8");
break;
case 8:
btnClick.setText("9");
break;
case 9:
btnClick.setBackgroundResource(R.drawable.sil_icon);
break;
}
btnClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickIslemleri(value);
}
});
}
public void clickIslemleri(int value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
gameInterface.seciliHucreyiDoldur(String.valueOf(value+1));
break;
case 9:
gameInterface.seciliHucreyiDoldur("");
break;
}
}
public void kayitliOyunuGuncelle() {
misafirOyunKaydiDB = new MisafirOyunKaydiDB(MainActivity.this);
new MisafirGirisliOyunKaydiDAO().misafirgirisiKaydiGuncelle(misafirOyunKaydiDB,
1, input + " s", 0, "00:45", kayitZamanini());
misafirKaydiListesi = new MisafirGirisliOyunKaydiDAO().tumOyunKayitlari(misafirOyunKaydiDB);
for (int i = 0; i < misafirKaydiListesi.size(); i++) {
Log.e("saved game", misafirKaydiListesi.get(i).getTimestamp());
}
}
public void gecmisOyunlarGuest() {
misafirOyunKaydiDB = new MisafirOyunKaydiDB(MainActivity.this);
misafirKaydiListesi = new MisafirGirisliOyunKaydiDAO().tumOyunKayitlari(misafirOyunKaydiDB);
for (int i = 0; i < misafirKaydiListesi.size(); i++) {
Log.e("saved game", misafirKaydiListesi.get(i).getId() + "");
}
}
#Override
public void seciliHucreyiDoldur(String seciliHucreyiDoldur) {
}
#Override
public void hucreSeciliMi(Boolean hucreSecilimi) {
}
}
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.devapost.mysudoku, PID: 4945
java.lang.ClassCastException: com.devapost.mysudoku.MainActivity cannot be cast to com.devapost.mysudoku.utils.GameInterface
at com.devapost.mysudoku.MainActivity$AltBolumNumericTablo.<init>(MainActivity.java:514)
at com.devapost.mysudoku.MainActivity.altNumericDoldur(MainActivity.java:297)
MainActivity.java:
public class MainActivity extends AppCompatActivity implements GameInterface{
Cell[][] table;
AltBolumNumericTablo[][] tableAltNumeric;
MisafirGirisEkrani[] tableMisafir;
UyeMenuEkrani[] tableUyeMenusu;
String input;
TableLayout tableLayout;
TextView textView, txtSayac;
Button buttonGenerate;
LinearLayout linearLayout;
Button btnGoogleLoginMainScreen, btnMisafirMainScreen;
int hangiEkranda = 0;
MisafirOyunKaydiDB misafirOyunKaydiDB;
ArrayList<MisafirGirisliOyunKaydiModel> misafirKaydiListesi;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
girisSecenekleriEkrani();
}
#Override
public void onBackPressed() {
switch (hangiEkranda) {
case 0:
case 2://üye menusundeyse
super.onBackPressed();
linearLayout.removeAllViews();
onBackPressed();
break;
case 1://misafir menusundeyse
girisSecenekleriEkrani();
break;
case 3://misafir oyun ekranındaysa
misafirOyunKaydiDB = new MisafirOyunKaydiDB(MainActivity.this);
new MisafirGirisliOyunKaydiDAO().saveGame(misafirOyunKaydiDB, input, input, 5, txtSayac.getText().toString(), 1, kayitZamanini());
misafirEkraniniDoldur();
break;
case 4://misafir ayarlardaysa
case 5://misafirden nasıl oynanıra gittiyse
misafirEkraniniDoldur();
break;
case 6://serüvene gittiyse
case 7://rastgele oyun kurma ekranına gittiyse
case 8://skorboard ekranına gittiyse
case 9://üye ekranından ayarlara gittiyse
case 10://üye ekranından nasıl oynanır ekranına gittiyse
uyelerinMenusu();
break;
}
}
public String kayitZamanini() {
Calendar anlikSaatDakika = Calendar.getInstance();
int yil = anlikSaatDakika.get(Calendar.HOUR_OF_DAY);
int ay = anlikSaatDakika.get(Calendar.MINUTE);
int gun = anlikSaatDakika.get(Calendar.SECOND);
int saat = anlikSaatDakika.get(Calendar.HOUR_OF_DAY);
int dakika = anlikSaatDakika.get(Calendar.MINUTE);
int saniye = anlikSaatDakika.get(Calendar.SECOND);
return gun + "." + ay + "." + yil + " - " + saat + ":" + dakika + ":" + saniye;
}
public void girisSecenekleriEkrani() {//giriş seçenekleri ekranı
hangiEkranda = 0;
linearLayout = new LinearLayout(MainActivity.this);
btnGoogleLoginMainScreen = new Button(MainActivity.this);
btnMisafirMainScreen = new Button(MainActivity.this);
btnGoogleLoginMainScreen.setText("Google İle Giriş Yap");
btnMisafirMainScreen.setText("Misafir Girişi");
btnGoogleLoginMainScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uyelerinMenusu();
}
});
btnMisafirMainScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
linearLayout.removeAllViews();
misafirEkraniniDoldur();
}
});
linearLayout.addView(btnGoogleLoginMainScreen);
linearLayout.addView(btnMisafirMainScreen);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT
);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setGravity(Gravity.CENTER);
linearLayout.setLayoutParams(layoutParams);
setContentView(linearLayout);
}
public void yeniOyunMisafirIcin() {
hangiEkranda = 3;
linearLayout.removeAllViews();
int N = 9, K = 25;
Sudoku sudoku = new Sudoku(N, K);
sudoku.fillValues();
txtSayac = new TextView(MainActivity.this);
input = sudoku.printSudoku();
String[] split = input.split(" ");
table = new Cell[9][9];
tableLayout = new TableLayout(MainActivity.this);
for (int i = 0; i < 9; i++) {
TableRow tableRow = new TableRow(MainActivity.this);
for (int j = 0; j < 9; j++) {
String s = split[i * 9 + j];
char c = s.charAt(0);
table[i][j] = new Cell(c == '?' ? 0 : c - '0', MainActivity.this);
paintCellBackground(i, j, table[i][j].btn);
tableRow.addView(table[i][j].btn);
}
tableLayout.addView(tableRow);
}
tableLayout.setShrinkAllColumns(true);
tableLayout.setStretchAllColumns(true);
textView = new TextView(MainActivity.this);
buttonGenerate = new Button(MainActivity.this);
linearLayout = new LinearLayout(MainActivity.this);
linearLayout.addView(txtSayac);
LinearLayout linearLayoutEkMetin = new LinearLayout(MainActivity.this);
linearLayoutEkMetin.setLayoutParams(
new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
linearLayoutEkMetin.setOrientation(LinearLayout.VERTICAL);
linearLayoutEkMetin.setGravity(Gravity.CENTER_HORIZONTAL);
buttonGenerate.setText("Generate");
buttonGenerate.setVisibility(View.GONE);
buttonGenerate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
misafirEkraniniDoldur();
progressDialog.dismiss();
}
});
linearLayoutEkMetin.addView(buttonGenerate);
linearLayout.addView(tableLayout);
linearLayout.addView(textView);
linearLayout.addView(linearLayoutEkMetin);
linearLayout.setOrientation(LinearLayout.VERTICAL);
altNumericDoldur();
setContentView(linearLayout);
}
public void paintCellBackground(int i, int j, Button button) {
switch (i) {
case 0:
case 1:
case 2:
case 6:
case 7:
case 8:
switch (j) {
case 0:
case 1:
case 2:
case 6:
case 7:
case 8:
button.setBackgroundResource(R.drawable.hucre_arkaplani_gri);
break;
case 3:
case 4:
case 5:
button.setBackgroundResource(R.drawable.hucre_arkaplani_beyaz);
break;
}
break;
case 3:
case 4:
case 5:
switch (j) {
case 0:
case 1:
case 2:
case 6:
case 7:
case 8:
button.setBackgroundResource(R.drawable.hucre_arkaplani_beyaz);
break;
case 3:
case 4:
case 5:
button.setBackgroundResource(R.drawable.hucre_arkaplani_gri);
break;
}
break;
}
}
public void misafirEkraniniDoldur() {//misafir ekranını doldurur
hangiEkranda = 1;
tableMisafir = new MisafirGirisEkrani[5];
tableLayout = new TableLayout(MainActivity.this);
for (int i = 0; i < 5; i++) {
TableRow tableRow = new TableRow(MainActivity.this);
tableMisafir[i] = new MisafirGirisEkrani(i, MainActivity.this);
tableRow.addView(tableMisafir[i].btnClick);
tableLayout.addView(tableRow);
}
tableLayout.setShrinkAllColumns(true);
tableLayout.setStretchAllColumns(true);
linearLayout = new LinearLayout(MainActivity.this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT
);
layoutParams.setMarginStart(16);
layoutParams.setMarginEnd(16);
tableLayout.setLayoutParams(layoutParams);
linearLayout.setGravity(Gravity.CENTER);
linearLayout.addView(tableLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);
setContentView(linearLayout);
}
public void altNumericDoldur() {//alt numerik tabloyu doldurur
tableAltNumeric = new AltBolumNumericTablo[2][5];
tableLayout = new TableLayout(MainActivity.this);
int butonID = 0;
for (int i = 0; i < 2; i++) {
TableRow tableRow = new TableRow(MainActivity.this);
for (int j = 0; j < 5; j++) {
tableAltNumeric[i][j] = new AltBolumNumericTablo(butonID, MainActivity.this,MainActivity.this);
tableRow.addView(tableAltNumeric[i][j].btnClick);
butonID++;
}
tableLayout.addView(tableRow);
}
tableLayout.setShrinkAllColumns(true);
tableLayout.setStretchAllColumns(true);
//linearLayout = new LinearLayout(MainActivity.this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT
);
layoutParams.setMarginStart(16);
layoutParams.setMarginEnd(16);
tableLayout.setLayoutParams(layoutParams);
linearLayout.addView(tableLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);
setContentView(linearLayout);
}
private void uyelerinMenusu() {//google ile giriş yapanlar için serüven ekranı
hangiEkranda = 2;
tableUyeMenusu = new UyeMenuEkrani[5];
tableLayout = new TableLayout(MainActivity.this);
for (int i = 0; i < 5; i++) {
TableRow tableRow = new TableRow(MainActivity.this);
tableUyeMenusu[i] = new UyeMenuEkrani(i, MainActivity.this);
tableRow.addView(tableUyeMenusu[i].btnClick);
tableLayout.addView(tableRow);
}
tableLayout.setShrinkAllColumns(true);
tableLayout.setStretchAllColumns(true);
linearLayout = new LinearLayout(MainActivity.this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT
);
layoutParams.setMarginStart(16);
layoutParams.setMarginEnd(16);
tableLayout.setLayoutParams(layoutParams);
linearLayout.setGravity(Gravity.CENTER);
linearLayout.addView(tableLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);
setContentView(linearLayout);
}
#Override
public void seciliHucreyiDoldur(String seciliHucreyiDoldur) {
}
#Override
public void hucreSeciliMi(boolean hucreSecilimi) {
}
public class UyeMenuEkrani {
Button btnClick;
boolean onClicked;
int value;
public UyeMenuEkrani(int value, Context THIS) {
this.value = value;
btnClick = new Button(THIS);
switch (value) {
case 0:
btnClick.setText("Serüven");
break;
case 1:
btnClick.setText("Rastgele Oyna");
break;
case 2:
btnClick.setText("Skor Tablosu");
break;
case 3:
btnClick.setText("Ayarlar");
break;
case 4:
btnClick.setText("Nasıl Oynanır");
break;
}
btnClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickIslemleri(value);
}
});
}
public void clickIslemleri(int value) {
switch (value) {
case 0://seruven
Toast.makeText(MainActivity.this, "serüvene gider", Toast.LENGTH_SHORT).show();
break;
case 1://rastgele
yeniOyunMisafirIcin();//rastgele ekranı misafir giriş ekranına gider, çok benzer zaten
break;
case 2://skorboard
Toast.makeText(MainActivity.this, "skorboard", Toast.LENGTH_SHORT).show();
break;
case 3://ayarlar
Toast.makeText(MainActivity.this, "ayarlar", Toast.LENGTH_SHORT).show();
break;
case 4://nasıl oynanır
Toast.makeText(MainActivity.this, "nasıl oynanır", Toast.LENGTH_SHORT).show();
break;
case 5:
break;
}
}
}
public class MisafirGirisEkrani {
Button btnClick;
boolean onClicked;
int value;
public MisafirGirisEkrani(int value, Context THIS) {
this.value = value;
btnClick = new Button(THIS);
switch (value) {
case 0:
btnClick.setText("Yeni Oyun");
break;
case 1:
btnClick.setText("Devam Et");
break;
case 2:
btnClick.setText("Ayarlar");
break;
case 3:
btnClick.setText("Giriş Yap");
break;
case 4:
btnClick.setText("Nasıl Oynanır");
break;
}
btnClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickIslemleri(value);
}
});
}
public void clickIslemleri(int value) {
switch (value) {
case 0:
yeniOyunMisafirIcin();
break;
case 1://eski oyunları listele ve onlardan seçip devam et
gecmisOyunlarGuest();
break;
case 2:
kayitliOyunuGuncelle();
Toast.makeText(MainActivity.this, "ayarlar", Toast.LENGTH_SHORT).show();
break;
case 3:
girisSecenekleriEkrani();
break;
case 4:
Toast.makeText(MainActivity.this, "nasıl oynanır", Toast.LENGTH_SHORT).show();
break;
}
}
public void kayitliOyunuGuncelle() {
misafirOyunKaydiDB = new MisafirOyunKaydiDB(MainActivity.this);
new MisafirGirisliOyunKaydiDAO().misafirgirisiKaydiGuncelle(misafirOyunKaydiDB,
1, input + " s", 0, "00:45", kayitZamanini());
misafirKaydiListesi = new MisafirGirisliOyunKaydiDAO().tumOyunKayitlari(misafirOyunKaydiDB);
for (int i = 0; i < misafirKaydiListesi.size(); i++) {
Log.e("saved game", misafirKaydiListesi.get(i).getTimestamp());
}
}
public void gecmisOyunlarGuest() {
misafirOyunKaydiDB = new MisafirOyunKaydiDB(MainActivity.this);
misafirKaydiListesi = new MisafirGirisliOyunKaydiDAO().tumOyunKayitlari(misafirOyunKaydiDB);
for (int i = 0; i < misafirKaydiListesi.size(); i++) {
Log.e("saved game", misafirKaydiListesi.get(i).getId() + "");
}
}
}
boolean complated() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (table[i][j].value == 0) {
return false;
}
}
}
return true;
}
boolean correct(int i1, int j1, int i2, int j2) {
boolean[] seen = new boolean[10];
for (int i = 1; i <= 9; i++) {
seen[i] = false;
}
for (int i = i1; i < i2; i++) {
for (int j = j1; j < j2; j++) {
int value = table[i][j].value;
if (value != 0) {
if (seen[value]) {
return false;
}
seen[value] = true;
}
}
}
return true;
}
boolean correct() {
for (int i = 0; i < 9; i++) {
if (!correct(i, 0, i + 1, 9)) {
return false;
}
}
for (int j = 0; j < 9; j++) {
if (!correct(0, j, 9, j + 1)) {
return false;
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (!correct(3 * i, 3 * j, 3 * i + 3, 3 * j + 3)) {
return false;
}
}
}
return true;
}
}
Got the issue .
Issue is at below mentioned line in AltBolumNumericTablo class
gameInterface = (GameInterface) activity;
you just need to change as mentioned below
From
public AltBolumNumericTablo(int value, Context THIS, Activity activity)
To
public AltBolumNumericTablo(int value, Context THIS, GameInterface gameInterfaceParam){
gameInterface = gameInterfaceParam
.. existing code
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.true_button:
checkAnswer(true);
break;
case R.id.false_button:
checkAnswer(false);
break;
case R.id.image_next:
currentIndex = (currentIndex + 1) % questions.length;
updateQuestion();
break;
case R.id.image_back:
if (currentIndex > 0){
currentIndex = (currentIndex - 1) % questions.length;
updateQuestion();
}else{
Toast.makeText(MainActivity.this,"No Back Qouestions....",Toast.LENGTH_SHORT).show();
}
}
}
private void updateQuestion() {
textView.setText(questions[currentIndex].getText());
}
private void checkAnswer(boolean userchoosen) {
boolean answerIsTrue = questions[currentIndex].isAnswer();
int toastMessageId = 0;
if (userchoosen == answerIsTrue) {
toastMessageId = R.string.correct_answer;
if (userchoosen == true){
trueButton.setVisibility(View.INVISIBLE);
} else{
falseButton.setVisibility(View.INVISIBLE);
}
} else {
toastMessageId = R.string.wrong_answer;
}
Toast.makeText(MainActivity.this, toastMessageId, Toast.LENGTH_SHORT).show();
}}
Now i need when i click on true button and the right answer is true the false button be hidden untill the user click back or forward , i'm trying to add visibility is visible in back and forward button but it not working well , and i need if any notes of my code ,thank you alot..
In this, I want to change the images in the order. i.e on 1st click of dice1 itself, dice1 should change then dice2, dice3, dice4, and then again dice1 and soo on till the end of the loop. but whenever I click any image only the image in dice2 changes. The image I click only that should change that too in the predefined order. Can someone please help fix the code.
JAVA FILE
public class MainActivity extends AppCompatActivity{
private ImageView dice1,dice2,dice3,dice4;
private ImageView[] dice = { dice1, dice2, dice3, dice4 };
private Random rng = new Random();
public int i=0,j=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dice[0] = findViewById(R.id.imageView3);
dice[1]= findViewById(R.id.imageView7);
dice[2] = findViewById(R.id.imageView9);
dice[3] = findViewById(R.id.imageView5);
while(j<5){
if(i==4){
i=0;}
dice[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
rollDice();
}
});
j++;
i++;
}
}
private void rollDice(){
int randomNo = rng.nextInt(6)+1;
switch (randomNo){
case 1:
dice[i].setImageResource(R.drawable.one);
break;
case 2:
dice[i].setImageResource(R.drawable.two);
break;
case 3:
dice[i].setImageResource(R.drawable.three);
break;
case 4:
dice[i].setImageResource(R.drawable.four);
break;
case 5:
dice[i].setImageResource(R.drawable.five);
break;
case 6:
dice[i].setImageResource(R.drawable.six);
break;
}
}
So, I tried to call all the methods from overView but is not working, I tried with "view" in the parentheses and then is constantly crashing when I start the app.... Can someone help, this is the whole code. I tried not to include the first four methods but then is not working the way it's suppose to.
public class MainActivity extends AppCompatActivity {
int health = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void checkQuestionOne(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.question_one_yes:
if(checked)
health += 1;
break;
case R.id.question_one_no:
if(checked)
health -= 1;
break;
}
}
public void checkQuestionTwo(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.question_two_yes:
if(checked)
health += 1;
break;
case R.id.question_two_no:
if(checked)
health -= 1;
break;
}
}
public void checkQuestionThree(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.question_three_yes:
if(checked)
health += 1;
break;
case R.id.question_three_no:
if(checked)
health -= 1;
break;
}
}
public void checkQuestionFour(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.question_four_yes:
if(checked)
health += 1;
break;
case R.id.question_four_no:
if(checked)
health -= 1;
break;
}
}
public void checkQuestionFive() {
EditText gettingQuestionFive = findViewById(R.id.sleep_hours);
int answerQuestionFive = Integer.parseInt(gettingQuestionFive.getText().toString());
if (answerQuestionFive > 7) {
health += 1;
} else if (answerQuestionFive == 7) {
health += 1;
} else {
health -=1;
}
}
private void displayMessage(String message) {
TextView orderSummaryTextView = (TextView) findViewById(R.id.summary);
orderSummaryTextView.setText(message);
}
public void overView(View view){
checkQuestionOne();
checkQuestionTwo();
checkQuestionThree();
checkQuestionFour();
checkQuestionFive();
String Message = health + " is your score. If is 3 or above, you have a healthy life";
displayMessage(Message);
}
}
I think you have forgot to call the overView() method in the onCreate() method of activity. You can call it like this.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Pass your view in argument
overView(View view)
}
So I'm having an issue with my code when using the android emulator. I get the same error: Throwing OutOfMemoryError "Failed to allocate a 4776816 byte allocation with 2473998 free bytes and 2MB until OOM"
I have a feeling this is due to memory leak as I create objects for each class within each other class and I imagine it's causing some kind of loop error. Is this disallowed in Java? Any help would be much appreciated..
Here is the code:
public class BoardActivity extends AppCompatActivity {
Move move = new Move();
Button buttons[] = new Button[16];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_board);
move.newGame();
buttons[0] = (Button)findViewById(R.id.button1);buttons[0].setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
move.makeMove(move.cups.get(0));
updateButtons();
}});
buttons[1] = (Button)findViewById(R.id.button2);buttons[1].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(1));
updateButtons();
}
});
buttons[2] = (Button)findViewById(R.id.button3);buttons[2].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(2));
updateButtons();
}
});
buttons[3] = (Button)findViewById(R.id.button4);buttons[3].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(3));
updateButtons();
}
});
buttons[4] = (Button)findViewById(R.id.button5);buttons[4].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(4));
updateButtons();
}
});
buttons[5] = (Button)findViewById(R.id.button6);buttons[5].setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
move.makeMove(move.cups.get(5));
updateButtons();
}
});
buttons[6] = (Button)findViewById(R.id.button7);buttons[6].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(6));
updateButtons();
}
});
buttons[7] = (Button)findViewById(R.id.button8);buttons[7].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
updateButtons();
}
});
buttons[8] = (Button)findViewById(R.id.button9);buttons[8].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(8));
updateButtons();
}
});
buttons[9] = (Button)findViewById(R.id.button10);buttons[9].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(9));
updateButtons();
}
});
buttons[10] = (Button)findViewById(R.id.button11);buttons[10].setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
move.makeMove(move.cups.get(10));
updateButtons();
}
});
buttons[11] = (Button)findViewById(R.id.button12);buttons[11].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(11));
updateButtons();
}
});
buttons[12] = (Button)findViewById(R.id.button13);buttons[12].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(12));
updateButtons();
}
});
buttons[13] = (Button)findViewById(R.id.button14);buttons[13].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(13));
updateButtons();
}
});
buttons[14] = (Button)findViewById(R.id.button15);buttons[14].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(14));
updateButtons();
}
});
// Still have bug with this button - needs to be sorted
buttons[15] = (Button)findViewById(R.id.button16);buttons[15].setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
updateButtons();
}
});
updateButtons();
}
public void updateButtons(){
for(int i=0; i<buttons.length; i++){
buttons[i].setText(move.cups.get(i).toString());
}
}
}
Player class:
public class Player extends Move{
Random rand = new Random();
BoardActivity board = new BoardActivity();
/**public void setScoreCups(){
if(returnCurrentPlayer()==1){
oppositionScoreCup = cups.get(16);
scoreCup = cups.get(8);
}else{
oppositionScoreCup = cups.get(8);
scoreCup = cups.get(16);
}
}**/
public void setNextPlayer(){
if(returnCurrentPlayer()==1) {
setTurnPlayer(2);
}else if(returnCurrentPlayer()==2){
setTurnPlayer(1);
}
}
public int returnCurrentPlayer(){
if(board.buttons[5].isEnabled()){
return 1;
}else{
return 2;
}
}
public void setRandomPlayer(){
boolean b = rand.nextBoolean();
if(b){
setTurnPlayer(1);
}else{
setTurnPlayer(2);
}
}
public void setTurnPlayer(int n){
if(n==1) {
for (int i = 1; i < 8; i++) {
board.buttons[i].setEnabled(true);
}
for (int i = 9; i < 16; i++) {
board.buttons[i].setEnabled(false);
}
}else if(n==2){
for(int i=1; i<8; i++){
board.buttons[i].setEnabled(false);
}
for(int i=9; i<16; i++){
board.buttons[i].setEnabled(true);
}
}
}
public void setPlayer() {
if ((move.currentCup.pebbleCount == 0) && (move.currentCup != move.scoreCup)) {
Log.d("makeMove.java", "print cup index" + move.cups.indexOf(move.currentCup));
//emptyCupSwitch(currentCup);
move.currentCup.increasePebbleCount();
}
if (move.currentCup == move.scoreCup) {
move.currentCup.increasePebbleCount();
setTurnPlayer(move.currentPlayer);
} else if (move.currentCup != move.scoreCup) {
move.currentCup.increasePebbleCount();
setNextPlayer();
}
}
//needs to be changed
public static int score=0;
public void setScore(int n){
score = n;
}
}
And Move class:
public class Move extends Game{
Player player = new Player();
public Cup oppositionScoreCup; public Cup scoreCup;
int i; int currentPlayer; int cupValue;
int currentIndex; int lastCupIndex = currentIndex + cupValue - 1;
Cup currentCup;
public List<Cup> cups;
public void newGame() {
cups = new ArrayList<>();
//Reset all cups
for (int i = 0; i < 16; i++) {
Cup cup = new Cup(7);
cups.add(i, cup);
}
}
//Returns the cup following the one entered in the parameters
public Cup getNextCup(Cup cup) {
if (cups.indexOf(cup) == 15) {
return cups.get(0);
} else {
return cups.get(cups.indexOf(cup) + 1);
}
}
//Emptys current cup and switches pebbles to opposite side
public void emptyCupSwitch(Cup cup) {
Cup oppCup;
int index = cups.indexOf(cup);
switch(index) {
case 1:
oppCup = cups.get(15);
cups.get(1).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
break;
case 2:
oppCup = cups.get(14);
cups.get(2).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
break;
case 3:
oppCup = cups.get(13);
cups.get(3).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
break;
case 4:
oppCup = cups.get(12);
cups.get(4).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 5:
oppCup = cups.get(11);
cups.get(5).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 6:
oppCup = cups.get(10);
cups.get(6).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 7:
oppCup = cups.get(9);
cups.get(7).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 9:
oppCup = cups.get(7);
cups.get(9).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 10:
oppCup = cups.get(6);
cups.get(10).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 11:
oppCup = cups.get(5);
cups.get(11).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 12:
oppCup = cups.get(4);
cups.get(12).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 13:
oppCup = cups.get(3);
cups.get(13).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 14:
oppCup = cups.get(2);
cups.get(7).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 15:
oppCup = cups.get(1);
cups.get(7).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
}
}
//Method for Clicking Cup - Basic move - Skips oppositonScoreCup
public void makeMove(Cup cup) {
cupValue = cup.returnPebbleCount();
currentIndex = cups.indexOf(cup);
currentCup = getNextCup(cup);
cup.emptyCup();
for (i = currentIndex; i < currentIndex + cupValue; i++) {
if (i == lastCupIndex) {
player.setPlayer();
} else if (currentCup == oppositionScoreCup) {
currentCup = getNextCup(currentCup);
} else if (currentCup != oppositionScoreCup) {
currentCup.increasePebbleCount();
currentCup = getNextCup(currentCup);
}
}
if(checkGameOver()){
gameOver();
}
}
}
You are running out of memory because your code will run recursively and create an infinite number of objects of BoardActivity, Move and Player.
How? Well, when the BoardActivity class is initialized, the line
Move move = new Move();
will create new Move object. This, in turn will result in the execution of the line
Player player = new Player();
from inside the Move class. This will spawn a new Player object which contains the line
BoardActivity board = new BoardActivity();
Now this will create another BoardActivity object and this takes us back to the beginning creating an endless cycle of object spawning.
Simply put, BoardActivity->Move->Player->BoardActivity->Move->Player....
I'm guessing the AppCompatActivity is an android activity. Android activities are pretty heavy and allocates some good amount of heap memory when initialized. This is basically why you are running out of memory so quickly.
You shouldn't be creating an activity this way. Either create one and start from the main activity or load it as the default activity using the AndroidManifest
Also instead of creating a separate OnClickListener for each button, it would be better to create a single OnClickListener and check button ids using if statements to determine which button was clicked.