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.
Related
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
}
I want to hide a WebView object (txtCode) if the code property of a custom object Arraylist (arrQues) contains nothing.
if (arrQues.get(count).code.isEmpty())
txtCode.setVisibility(View.GONE);
Its an ArrayList of custom objects fetched from a database table which is shown below
And if the code property does contains code then I have dynamically added rules to layout as shown below:
if (!(arrQues.get(count).code.isEmpty())) {
submit_params.removeRule(RelativeLayout.BELOW);
submit_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.bottomMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 15));
main_params.addRule(RelativeLayout.ABOVE, submitContainer.getId());
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
}
The issue is when I load the second question and so on... the layout gets messed up and the current question number does not shows as 2 even if its 2 as shown in below:
Both of these issues only arises whenever I use...
arrQues.get(count).code.isEmpty() in the code
I have also tried using "" instead of isEmpty() and even null, but the result was same.
Also what I have noticed is only those questions are loaded from database which have something in the code column.
Below is the complete code for Java file
public class QuestionsFragment extends Fragment implements View.OnClickListener {
TextView txtTimer, txtStatus;
LinearLayout boxA, boxB, boxC, boxD, mainContainer;
RelativeLayout submitContainer;
RelativeLayout.LayoutParams submit_params;
RelativeLayout.LayoutParams main_params;
ScrollView scrollView;
Button btnSubmit;
DBHelper dbHelper;
SharedPreferences sharedPreferences;
TextView txtQues;
WebView txtCode;
TextView txtOptA, txtOptB, txtOptC, txtOptD;
String ans;
ArrayList<QuestionModal> arrQues = new ArrayList<>();
ArrayList<String> arrAnswers = new ArrayList<>();
CountDownTimer countDownTimer;
boolean timerSwitch;
int selectedVal, id;
int curr_quesNo = 0;
int count = 0;
int right = 0;
int non_attempted = 0;
public QuestionsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_questions, container, false);
txtQues = view.findViewById(R.id.txtQues);
txtOptA = view.findViewById(R.id.txtOptionA);
txtOptB = view.findViewById(R.id.txtOptionB);
txtOptC = view.findViewById(R.id.txtOptionC);
txtOptD = view.findViewById(R.id.txtOptionD);
txtCode = view.findViewById(R.id.txtCode);
txtStatus = view.findViewById(R.id.txtStatus);
boxA = view.findViewById(R.id.boxA);
boxB = view.findViewById(R.id.boxB);
boxC = view.findViewById(R.id.boxC);
boxD = view.findViewById(R.id.boxD);
scrollView = view.findViewById(R.id.scrollView);
btnSubmit = view.findViewById(R.id.btnSubmit);
submitContainer = view.findViewById(R.id.submitContainer);
mainContainer = view.findViewById(R.id.mainContainer);
submit_params = new RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT);
main_params = new RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT);
sharedPreferences = getActivity().getSharedPreferences("PrefFile", MODE_PRIVATE);
timerSwitch = sharedPreferences.getBoolean("timer_switch", true);
selectedVal = sharedPreferences.getInt("selectedVal", 10);
dbHelper = DBHelper.getDB(getActivity(), sharedPreferences.getString("db_name", null));
if (!dbHelper.checkDB()) {
dbHelper.createDB(getActivity());
}
dbHelper.openDB();
String levelKey = sharedPreferences.getString("level_key", null);
arrQues = dbHelper.getQues(levelKey, selectedVal);
loadQues(timerSwitch);
txtTimer = view.findViewById(R.id.txtTimer);
switch (sharedPreferences.getString("db_name", null)) {
case "Android":
((MainActivity) getActivity()).setFragTitle("Android Quiz");
// topicLogo.setImageResource(R.drawable.ic_nature_people_black_24dp);
break;
case "Java":
((MainActivity) getActivity()).setFragTitle("Java Quiz");
// topicLogo.setImageResource(R.drawable.ic_nature_people_black_24dp);
break;
case "C":
((MainActivity) getActivity()).setFragTitle("C Quiz");
((MainActivity) getActivity()).setFragLogo(R.drawable.ic_home_black_24dp);
break;
case "C++":
((MainActivity) getActivity()).setFragTitle("C++ Quiz");
break;
case "Python":
((MainActivity) getActivity()).setFragTitle("Python Quiz");
break;
case "Kotlin":
((MainActivity) getActivity()).setFragTitle("Kotlin Quiz");
break;
}
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (timerSwitch)
countDownTimer.cancel();
if (id == 0) {
non_attempted++;
arrAnswers.add("NotAttempted");
Toast.makeText(getActivity(), "Not Attempted!", Toast.LENGTH_SHORT).show();
}
switch (id) {
case R.id.boxA:
arrAnswers.add("A");
break;
case R.id.boxB:
arrAnswers.add("B");
break;
case R.id.boxC:
arrAnswers.add("C");
break;
case R.id.boxD:
arrAnswers.add("D");
break;
}
if ((id == R.id.boxA && ans.equals("A"))
|| (id == R.id.boxB && ans.equals("B"))
|| (id == R.id.boxC && ans.equals("C"))
|| (id == R.id.boxD && ans.equals("D"))) {
right++;
count++;
Toast.makeText(getActivity(), "RIGHT!", Toast.LENGTH_SHORT).show();
if (count < arrQues.size()) {
loadQues(timerSwitch);
} else {
sendResult();
}
} else {
count++;
if (count < arrQues.size()) {
loadQues(timerSwitch);
} else {
sendResult();
}
}
}
});
return view;
}
public void setBtnDefault() {
boxA.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxB.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxC.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxD.setBackgroundColor(getResources().getColor(android.R.color.transparent));
}
public void sendResult() {
int attempted = selectedVal - non_attempted;
Gson gson = new Gson();
String jsonAnswers = gson.toJson(arrAnswers);
String jsonQues = gson.toJson(arrQues);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("right_key", right);
editor.putInt("wrong_key", attempted - right);
editor.putInt("total_key", selectedVal);
editor.putInt("attempted_key", attempted);
editor.putString("arr_answers", jsonAnswers);
editor.putString("arr_ques", jsonQues);
editor.commit();
((MainActivity) getActivity()).AddFrag(new ResultFragment(), 1);
}
public void LoadTimer() {
countDownTimer = new CountDownTimer(60000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
txtTimer.setText("0:" + millisUntilFinished / 1000);
}
#SuppressLint("SetTextI18n")
#Override
public void onFinish() {
txtTimer.setText("Time Over");
}
};
}
#SuppressLint("NewApi")
public void loadQues(boolean timer_switch) {
try {
id = 0;
setBtnDefault();
if (timer_switch) {
LoadTimer();
countDownTimer.start();
}
curr_quesNo++;
txtStatus.setText(curr_quesNo + "/" + selectedVal);
txtOptC.setVisibility(View.VISIBLE);
txtOptD.setVisibility(View.VISIBLE);
txtCode.setVisibility(View.VISIBLE);
main_params.removeRule(RelativeLayout.ABOVE);
submit_params.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.addRule(RelativeLayout.BELOW, mainContainer.getId());
submit_params.topMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 70));
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
txtQues.setText(arrQues.get(count).ques);
txtOptA.setText(arrQues.get(count).optionA);
txtOptB.setText(arrQues.get(count).optionB);
txtOptC.setText(arrQues.get(count).optionC);
txtOptD.setText(arrQues.get(count).optionD);
txtCode.loadDataWithBaseURL(null, arrQues.get(count).code, "text/html", null, null);
if (txtOptC.getText().toString().isEmpty())
txtOptC.setVisibility(View.GONE);
if (txtOptD.getText().toString().isEmpty())
txtOptD.setVisibility(View.GONE);
if (arrQues.get(count).code.isEmpty())
txtCode.setVisibility(View.GONE);
if (!(arrQues.get(count).code.isEmpty())) {
submit_params.removeRule(RelativeLayout.BELOW);
submit_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.bottomMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 15));
main_params.addRule(RelativeLayout.ABOVE, submitContainer.getId());
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
scrollView.arrowScroll(View.FOCUS_DOWN);
}
}, 1000);
}
ans = arrQues.get(count).answer;
boxA.setOnClickListener(this);
boxB.setOnClickListener(this);
boxC.setOnClickListener(this);
boxD.setOnClickListener(this);
} catch (Exception e) {
((MainActivity) getActivity()).AddFrag(new QuestionsFragment(), 1);
}
}
#Override
public void onClick(View v) {
setBtnDefault();
id = v.getId();
v.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
}
public float convertDpToPx(Context context, float dp) {
return dp * context.getResources().getDisplayMetrics().density;
}
public float convertPxToDp(Context context, float px) {
return px / context.getResources().getDisplayMetrics().density;
}
}
I solved it, all issues were happening because arrQues.get(count).code was fetching null values from the database(The column "Code" had null values). As soon as I replaced null values with empty strings "" isEmpty() worked perfectly. I guess isEmpty() doesn't work with null values and is only intended for empty strings.
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)
}
I have developed an app that has two buttons (left and right) and a Textview that will pop up on the screen.Each button has it's corresponding word.
The user has to click the button that corresponds to TextView's word as quickly as possible when it shows. I want to calculate it's reaction time on clicking the button.
Below is my code.
public class Place_to_go_1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_to_go_1);
placeone = Global_variables.getFirst_choice_label();
placetwo = Global_variables.getSecond_choice_label();
p_one = (TextView)findViewById(R.id.p_one);
p_two = (TextView)findViewById(R.id.p_two);
btnleft = (ImageButton)findViewById(R.id.btnleft);
btnright = (ImageButton)findViewById(R.id.btnright);
next = (ImageButton)findViewById(R.id.Next);
lblmaintext = (TextView)findViewById(R.id.lblmaintext);
lblprompt = (TextView)findViewById(R.id.lblprompt);
lblreact = (TextView)findViewById(R.id.lblreact);
imgmain = (ImageView)findViewById(R.id.imgmain);
//prac = (ImageView) findViewById(R.id.prac);
Intent intent = getIntent();
final String randomId = intent.getStringExtra("Info_id");
//============ validate image if not empty
setImage_onLaunch();
//==== populate left and right choices===
populate_headers(placeone, placetwo);
//==== populate attributes=====
populate_attributes();
//============== instruction ======
setInstruction();
//=============media
wrong_press = MediaPlayer.create(this, R.raw.wrong_press);
react_fast = MediaPlayer.create(this, R.raw.react_faster);
//=== left button click trigger
btnleft.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String position = "H";
if (tanan[counter].equals(p_one.getText().toString())) {
lblprompt.setVisibility(View.INVISIBLE);
HashMap<String,String> queryValues = new HashMap<String, String>();
queryValues.put("Info_id",randomId);
queryValues.put("Choice",p_one.getText().toString());
queryValues.put("Reaction_time",String.valueOf(elapsedTime));
queryValues.put("Position",position);
queryValues.put("Main",main);
queryValues.put("Error",error);
mydb.insertTest(queryValues);
counter++;
if (counter < tanan.length) {
btnleft.setEnabled(false);
btnright.setEnabled(false);
timeStamp = System.currentTimeMillis();
//Toast.makeText(Place_to_go_1.this, ""+timeStamp, Toast.LENGTH_SHORT).show();
getreactionTime(p_one.getText().toString(), String.valueOf((((timeStamp) / 1000.0) - ((timeRun) / 1000.0))));
setIntervalTime();
} else {
//======end sa data
postEnd();
}
} else {
// Toast.makeText(Place_to_go_1.this, "Wrong pressed", Toast.LENGTH_SHORT).show();
//wrong_press.start();
wrong_click_audio();
error = "1";
lblprompt.setVisibility(View.VISIBLE);
}
}
});
//==== right button click trigger
btnright.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String position = "A";
if (tanan[counter].equals(p_two.getText().toString())) {
lblprompt.setVisibility(View.INVISIBLE);
HashMap<String,String> queryValues = new HashMap<String, String>();
queryValues.put("Info_id",randomId);
queryValues.put("Choice",p_two.getText().toString());
queryValues.put("Reaction_time", String.valueOf(elapsedTime));
queryValues.put("Position",position);
queryValues.put("Main",main);
queryValues.put("Error",error);
mydb.insertTest(queryValues);
counter++;
if (counter < tanan.length) {
btnleft.setEnabled(false);
btnright.setEnabled(false);
timeStamp = System.currentTimeMillis();
//Toast.makeText(Place_to_go_1.this, ""+timeStamp, Toast.LENGTH_SHORT).show();
getreactionTime(p_two.getText().toString(), String.valueOf((((timeStamp) / 1000.0) - ((timeRun) / 1000.0))));
setIntervalTime();
} else {
//======end sa data
postEnd();
}
} else {
// Toast.makeText(Place_to_go_1.this, "Wrong pressed", Toast.LENGTH_SHORT).show();
// wrong_press.start();
wrong_click_audio();
error = "1";
lblprompt.setVisibility(View.VISIBLE);
}
}
});
// ==== next button for the next activity (Place to go 2)
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getIntent();
String randomId = intent.getStringExtra("Info_id");
//============= launch activity 2 for place to go
if (instruct == true) {
next.setVisibility(View.INVISIBLE);
// prac.setVisibility(View.VISIBLE);
CountDownTimer();
} else {
//Toast.makeText(getApplication(),"Saved Successfully.",Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), Place_to_go_2.class);
i.putExtra("Info_id", randomId);
startActivity(i);
}
}
});
}
public void interval(){
if(counter < tanan.length){
lblmaintext.setVisibility(View.VISIBLE);
timeRun = System.currentTimeMillis();
btnleft.setEnabled(true);
btnright.setEnabled(true);
lblmaintext.setText(tanan[counter]);
setImage();
imgmain.setVisibility(View.VISIBLE);
react = true;
reacFaster();
}else{
//======end sa data
Toast.makeText(Place_to_go_1.this, "End data", Toast.LENGTH_SHORT).show();
lblmaintext.setVisibility(View.VISIBLE);
lblmaintext.setText("Ok for now");
}
}
public void setIntervalTime(){
react = false;
lblreact.setVisibility(View.INVISIBLE);
reactFaster_timer.cancel();
lblmaintext.setVisibility(View.INVISIBLE);
lblreact.setVisibility(View.INVISIBLE);
imgmain.setVisibility(View.INVISIBLE);
timer = new CountDownTimer(Global_variables.interval_time_before_choices_will_show,Global_variables.interval_time_before_choices_will_show) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
interval();
}
}.start();
}
int counter_countdown = 0;
int drawwable_amber = R.drawable.amber;
String arr[] = {"Ready...","Set...","Start."};
public void CountDownTimer(){
btnleft.setVisibility(View.INVISIBLE);
btnright.setVisibility(View.INVISIBLE);
lblmaintext.setBackgroundResource(0);
timer = new CountDownTimer(4000,1000) {
#Override
public void onTick(long millisUntilFinished) {
lblmaintext.setTextSize(35);
lblmaintext.setText(arr[counter_countdown]);
counter_countdown++;
}
#Override
public void onFinish() {
btnleft.setVisibility(View.VISIBLE);
btnright.setVisibility(View.VISIBLE);
lblmaintext.setBackgroundResource(drawwable_amber);
// lblmaintext.setText(tanan[counter]);
//setImage();
val_first_launch();
timeRun = System.currentTimeMillis();
react = true;
reacFaster();
}
}.start();
}
public void reacFaster(){
reactFaster_timer = new CountDownTimer(Global_variables.reaction_time_first_param,Global_variables.reaction_time_second_param) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
if(react == true){
//Toast.makeText(Place_to_go_1.this, "please react faster", Toast.LENGTH_SHORT).show();
react_fast.start();
lblreact.setVisibility(View.VISIBLE);
}
}
}.start();
}
public void populate_headers(String one,String two){
//== this methos sets headers as random==//
headers = new ArrayList<String>();
headers.add(one);
headers.add(two);
Collections.shuffle(headers);
p_one.setText(headers.get(0));
p_two.setText(headers.get(1));
}
public void populate_attributes(){
attributes = new ArrayList<String>();
for(int h =0;h < 5;h++){
attributes.add(placeone);
attributes.add(placetwo);
}
Collections.shuffle(attributes);
tanan = new String[attributes.size()];
for(int k = 0; k < tanan.length;k++ ){
tanan[k] = attributes.get(k);
}
}
public void postEnd(){
instruct = false;
lblprompt.setVisibility(View.INVISIBLE);
btnright.setVisibility(View.INVISIBLE);
btnleft.setVisibility(View.INVISIBLE);
next.setVisibility(View.VISIBLE);
lblmaintext.setBackgroundResource(0);
lblmaintext.setTextSize(20);
p_one.setVisibility(View.INVISIBLE);
p_two.setVisibility(View.INVISIBLE);
imgmain.setVisibility(View.INVISIBLE);
reactFaster_timer.cancel();
lblreact.setVisibility(View.INVISIBLE);
lblmaintext.setText("Well done!\nNext, is the main task. It is exactly the same as before but this time words will appear on the screen that might distract you. \nPlease respond as quickly as you can.\n Press Next to begin");
}
//=========== validate if image is enabled/ disble if not set
public void setImage_onLaunch(){
if(Global_variables.getFirst_choice_image().equals("") || Global_variables.getSecond_choice_image().equals("")){
disbaleImage();
}else{
}
}
public void setImage(){
/* if(tanan[counter].equals(p_one.getText().toString())){
imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getFirst_choice_image()));
}else{
imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getSecond_choice_image()));
}*/
if(placeone.equals(tanan[counter])){
imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getFirst_choice_image()));
}else{
imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getSecond_choice_image()));
}
}
public void val_first_launch(){
if(Global_variables.getFirst_choice_image().equals("") || Global_variables.getSecond_choice_image().equals("")){
lblmaintext.setVisibility(View.VISIBLE);
lblmaintext.setText(tanan[counter]);
}else{
imgmain.setVisibility(View.VISIBLE);
if(placeone.equals(tanan[counter])){
imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getFirst_choice_image()));
}else{
imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getSecond_choice_image()));
}
}
}
public void disbaleImage(){
imgmain.setBackgroundResource(0);
imgmain.setVisibility(View.GONE);
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(getApplication(), MainActivity.class));
finish();
}
public String getreactionTime(String domain, String time){
// Toast.makeText(Place_to_go_1.this, time, Toast.LENGTH_SHORT).show();
//== get reaction time to every activity
Global_variables.set_timeStamps(domain, time);
return domain;
}
//===== prompt instruction====
public void setInstruction(){
btnleft.setVisibility(View.INVISIBLE);
btnright.setVisibility(View.INVISIBLE);
lblmaintext.setBackgroundResource(0);
lblmaintext.setTextSize(20);
lblmaintext.setText("Instruction:\n\nIf " + p_one.getText().toString() + " appears, press arrow left.\n If " + p_two.getText().toString() +
" appears, press arrow right.\n\nRespond as quickly as you can.");
next.setVisibility(View.VISIBLE);
}
//===== prompt instruction====
public void wrong_click_audio(){
wrong_press.start();
}
//=============end class====================
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
// Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
//Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
}
Here a simple logic to calculate reaction time is to create a variable which hold a time when a question is popped up to user and the time when a user show a click reaction to question and calculate the time difference between these two action.
long timeWhenQuestionShowed = System.currentTimeMillis();
long timeWhenUserReacted = System.currentTimeMillis();
long reactionTime = timeWhenQuestionShowed - timeWhenUserReacted;
This should help:
Try using onTouch instead of onClick.
long timeBefor=0;
long timeReaction=0;
btnleft.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: // when pressed
timeBefore=System.currentTimeMillis();
break;
case MotionEvent.ACTION_UP: // when released
timeReaction=System.currentTimeMillis() - timeBefore; // calculate difference
break;
}
}
timeReaction is your desired value.
The idea is to calculate the difference between 2 points in time. I will write 2 examples of calculating time difference in Java / measuring reaction time in Java:
System.nanoTime() or System.currentTimeMillis()
Differences are discussed here: Time measuring overhead in Java
long endTimeNanoSec = 0;
long startTimeNanoSec = System.nanoTime();
myWorkThatNeedsTiming(); // wait for user button press here
endTimeNanoSec = System.nanoTime();
long totalWorkTimeNanos = endTimeNanoSec - startTimeNanoSec;
Java StopWatch
JavaDoc: StopWatch
Stopwatch stopwatch = Stopwatch.createStarted();
myWorkThatNeedsTiming(); // wait for user button press here
stopwatch.stop();
long totalWorkTimeMillis = stopwatch.elapsedMillis();
I am making a game in which you can click on a card to change it randomly to another card. The image file for one card is 370x512 png and it size is more or less 200 kb. My problem is the process in which the imageView changes its picture from one card to another is very slow and lasts almost two seconds. The other problem is that if you click too fast on the card the class crashes. I've tried it already with an ImageButton, with a button and an ImageView and I tried it with 11 ImageViews (there are 11 different cards in the game) who are always there but only one of it is visible. I don't have any clue why the card changing process takes so much time. Here is my code to change the card. This code is with a button and an ImageView:
public class MainActivity extends Activity {
public static String dampfhammerData = "dampfhammerData";
SharedPreferences DampfhammerData;
public int nextCard;
public int lastCard = 0;
public int all=3;
public int buddy=3;
public int dampfhammer=3;
public int frauen=3;
public int links=3;
public int rechts=3;
public int maenner=3;
public int questionmaster=3;
public int regel=3;
public int themenrunde=3;
public int zaehlen=3;
public int deck = 44;
public String version;
ImageView Karte;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void changeCard(View view) {
selectCard();
}
public void selectCard(){
lastCard = nextCard;
if(deck > 0) {
Random rand = new Random();
nextCard = (rand.nextInt(10));
if(nextCard != lastCard) {
checkCardDeck();
}else {
selectCard();
}
}else {
Intent intent = new Intent(this, End.class);
startActivity(intent);
}
}
public void checkCardDeck(){
Karte = (ImageView) findViewById(R.id.karte);
switch (nextCard) {
case 0:
if(all > 0){
all--;
deck--;
Karte.setBackgroundResource(R.drawable.all);
}else {
selectCard();
}
break;
case 1:
if(zaehlen > 0){
zaehlen--;
deck--;
Karte.setBackgroundResource(R.drawable.zaehlen);
}else {
selectCard();
}
break;
case 2:
if(buddy > 0){
buddy--;
deck--;
Karte.setBackgroundResource(R.drawable.buddie);
}else {
selectCard();
}
break;
case 3:
if(themenrunde > 0){
themenrunde--;
deck--;
Karte.setBackgroundResource(R.drawable.themenrunde);
}else {
selectCard();
}
break;
case 4:
if(dampfhammer > 0){
dampfhammer--;
deck--;
Karte.setBackgroundResource(R.drawable.dampfhammer);
}else {
selectCard();
}
break;
case 5:
if(links > 0){
links--;
deck--;
Karte.setBackgroundResource(R.drawable.links);
}else {
selectCard();
}
break;
case 6:
if(rechts > 0){
rechts--;
deck--;
Karte.setBackgroundResource(R.drawable.rechts);
}else {
selectCard();
}
break;
case 7:
if(frauen > 0){
frauen--;
deck--;
Karte.setBackgroundResource(R.drawable.frauen);
}else {
selectCard();
}
break;
case 8:
if(maenner > 0){
maenner--;
deck--;
Karte.setBackgroundResource(R.drawable.maenner);
}else {
selectCard();
}
break;
case 9:
if(questionmaster > 0){
questionmaster--;
deck--;
Karte.setBackgroundResource(R.drawable.questionmaster);
}else {
selectCard();
}
break;
case 10:
if(regel > 0){
regel--;
deck--;
Karte.setBackgroundResource(R.drawable.regel);
}else {
selectCard();
}
break;
}
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Wollen sie das Spiel verlassen?") //
.setMessage("Das aktuelle Spiel wird abgebrochen und sie kehren zum Startbildschirm zurück, wollen sie das wirklich?") //
.setPositiveButton(("Ja"), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton(("Nein"), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.show();
}
}
Thanks for your help!
If your deck of cards consists of 11 cards that each appear four times (I think that's right based on looking at the code), you can create a random shuffle like this:
ArrayList<Integer> deckList = new ArrayList<Integer>();
for (int i=0; i<11; i++) {
deckList.add(i); deckList.add(i); deckList.add(i); deckList.add(i);
}
Collections.shuffle(deckList);
By instead picking a random next card and retrying when it's a repeat, you're using a very inefficient and unpredictable process, especially since the retries are recursive, increasing the size of the call stack.
You will of course have to make other changes to use my deck in your code, but it should be quite a bit faster.