androidAppCrashedBasedOnBookTutorial(Any Advice);

+1 Black Boy · December 18, 2015
I was doing some tutorial on this book

https://www.packtpub.com/sites/default/files/3730_8859OS_Learning%20Java%20by%20Building%20Android%20Games.jpg

In chapter 5 there is a tutorial called memory game, So I copy this game code into notepad++ for printing purposes for studying how the code works and then pasted in android studio.When I started the app the game work fine and then I press the Play Button the app Crashed. I would like to know why it crashed and how could I fix it

some little information:

-my emulator uses android marshmallow 
-minimal software requirement Ice Cream Sandwich
-another thing I realize while doing this android doesn't want me to extends Activity witch they used in this book and let me use AppCompatActivity with is supposedly the same thing
-there a lot of yellow warning can not concatenate in setText() methods and soundpool  method being like this but there are used in this book
-I wonder if this book code still work today because if it don't I gonna have a hard time studying it 


Here the MainActivity code from the project:


package com.example.sibylsystem.memorygame;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

 //for our hiscore (phase 4)
 SharedPreferences prefs;
 String dataName = "MyData";
 String intName = "MyString";
 int defaultInt = 0;
 //both activities can see this
 public static int hiScore;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//for our high score (phase 4)
        //initialize our two SharedPreferences objects
        prefs = getSharedPreferences(dataName,MODE_PRIVATE);

        //Either load our High score or
        //if not available our default of 0
        hiScore = prefs.getInt(intName, defaultInt);

        //Make a reference to the Hiscore textview in our layout
        TextView textHiScore =(TextView) findViewById(R.id.textHiScore);
        //Display the hi score
        textHiScore.setText("Hi: "+ hiScore);






//Make a button from the button in our layout
Button button =(Button) findViewById(R.id.button);


button.setOnClickListener(this);
    }

public void onClick(View v){

Intent i;
         i = new Intent(this, GameActivity.class);
         startActivity(i);

}

}


Here the GameActivity code from the same project:


package com.example.sibylsystem.memorygame;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class GameActivity extends AppCompatActivity implements View.OnClickListener {

 //for our hiscore (phase 4)
 SharedPreferences prefs;
 SharedPreferences.Editor editor;
 String dataName = "MyData";
 String intName = "MyInt";
 int defaultInt = 0;
 int hiScore;


//Prepare objects and sound references

 //initialize sound variables
 private SoundPool soundPool;
 int sample1 = -1;
 int sample2 = -1;
 int sample3 = -1;
 int sample4 = -1;
 
 //for our UI
 TextView textScore;
 TextView textDifficulty;
 TextView textWatchGo;
 
 Button button1;
 Button button2;
 Button button3;
 Button button4;
 Button buttonReplay;
 
 
 //Some variables for our thread
 int difficultyLevel = 3;
 //An array to hold the randomly generated sequence
 int[] sequenceToCopy = new int[100];

 private Handler myHandler;
 //Are we playing a sequence at the moment?
 boolean playSequence = false;
 //And which element of the sequence are we on
 int elementToPlay = 0;

 //For checking the players answer
 int playerResponses;
 int playerScore;
 boolean isResponding;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//phase 4
        //initialize our two SharedPreferences objects
        prefs = getSharedPreferences(dataName,MODE_PRIVATE);
        editor = prefs.edit();
        hiScore = prefs.getInt(intName, defaultInt);





soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC,0);
        try{
        //Create objects of the 2 required classes
        AssetManager assetManager = getAssets();
        AssetFileDescriptor descriptor;

        //create our three fx in memory ready for use
        descriptor = assetManager.openFd("sample1.ogg");
        sample1 = soundPool.load(descriptor, 0);

        descriptor = assetManager.openFd("sample2.ogg");
        sample2 = soundPool.load(descriptor, 0);

        descriptor = assetManager.openFd("sample3.ogg");
        sample3 = soundPool.load(descriptor, 0);

        descriptor = assetManager.openFd("sample4.ogg");
        sample4 = soundPool.load(descriptor, 0);


        }catch(IOException e){
        //catch exceptions here
        }


//Reference all the elements of our UI
        //First the TextViews
        textScore = (TextView)findViewById(R.id.textScore);
        textScore.setText("Score: " + playerScore);
        textDifficulty = (TextView)findViewById(R.id.textDifficulty);

        textDifficulty.setText("Level: " + difficultyLevel);
        textWatchGo = (TextView)findViewById(R.id.textWatchGo);

        //Now the buttons
        button1 = (Button)findViewById(R.id.button);
        button2 = (Button)findViewById(R.id.button2);
        button3 = (Button)findViewById(R.id.button3);
        button4 = (Button)findViewById(R.id.button4);
        buttonReplay = (Button)findViewById(R.id.buttonReplay);

        //Now set all the buttons to listen for clicks
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
        button3.setOnClickListener(this);
        button4.setOnClickListener(this);
        buttonReplay.setOnClickListener(this);


//This is the code which will define our thread
        myHandler = new Handler() {
         public void handleMessage(Message msg) {
          super.handleMessage(msg);
 
                if (playSequence) {
                  //All the thread action will go here
 //make sure all the buttons are made visible
                  button1.setVisibility(View.VISIBLE);
                  button2.setVisibility(View.VISIBLE);
                  button3.setVisibility(View.VISIBLE);
 button4.setVisibility(View.VISIBLE);
 
 
                  switch (sequenceToCopy[elementToPlay]){
                    case 1:
                      //hide a button
                button1.setVisibility(View.INVISIBLE);
                      //play a sound
                      soundPool.play(sample1, 1, 1, 0, 0, 1);
                      break;
    
                    case 2:
                      //hide a button
                button2.setVisibility(View.INVISIBLE);
                      //play a sound
                      soundPool.play(sample2, 1, 1, 0, 0, 1);
                      break;

                    case 3:
                      //hide a button 
   button3.setVisibility(View.INVISIBLE);
                      //play a sound
                      soundPool.play(sample3, 1, 1, 0, 0, 1);
                      break;
 
                    case 4:
                      //hide a button
                button4.setVisibility(View.INVISIBLE);
                      //play a sound
                      soundPool.play(sample4, 1, 1, 0, 0, 1);
                         break;
                   }
 
                   elementToPlay++;
                   if(elementToPlay == difficultyLevel){
                   sequenceFinished();
                   }
 
         }
  
                   myHandler.sendEmptyMessageDelayed(0, 900);
         }


    };//end of thread

         myHandler.sendEmptyMessage(0);



 }
    
   public void createSequence(){
          //For choosing a random button
           Random randInt = new Random();
           int ourRandom;
           for(int i = 0; i < difficultyLevel; i++){
           //get a random number between 1 and 4
           ourRandom = randInt.nextInt(4);
           ourRandom ++;//make sure it is not zero
           //Save that number to our array
           sequenceToCopy = ourRandom;
           }

}

public void playASequence(){
            createSequence();
            isResponding = false;
            elementToPlay = 0;
            playerResponses = 0;
            textWatchGo.setText("WATCH!");
            playSequence = true;
        }

public void sequenceFinished(){
                playSequence = false;
                //make sure all the buttons are made visible
                button1.setVisibility(View.VISIBLE);
                button2.setVisibility(View.VISIBLE);
                button3.setVisibility(View.VISIBLE);
                button4.setVisibility(View.VISIBLE);
                textWatchGo.setText("GO!");
                isResponding = true;
            }


}

public void onClick(View view){

if(!playSequence) {//only accept input if sequence not playing
        switch (view.getId()) {
            //case statements here...

   case R.id.button:
              //play a sound
               soundPool.play(sample1, 1, 1, 0, 0, 1);
               checkElement(1);
      break;
   
   case R.id.button2:
              //play a sound
               soundPool.play(sample2, 1, 1, 0, 0, 1);
               checkElement(2);
               break;

case R.id.button3:
              //play a sound
               soundPool.play(sample3, 1, 1, 0, 0, 1);
               checkElement(3);
               break;
  
            case R.id.button4:
              //play a sound
               soundPool.play(sample4, 1, 1, 0, 0, 1);
               checkElement(4);
               break;
  
case R.id.buttonReplay:
               difficultyLevel = 3;
               playerScore = 0;
               textScore.setText("Score: " + playerScore);
               playASequence();
               break;

            }

        }

}


    public void checkElement(int thisElement){

    if(isResponding) {
    playerResponses++;
     if (sequenceToCopy[playerResponses-1] == thisElement) { //Correct
 
     playerScore = playerScore + ((thisElement + 1) * 2);
     textScore.setText("Score: " + playerScore);
     if (playerResponses == difficultyLevel) {//got the whole sequence
     //don't checkElement anymore
     isResponding = false;
     //now raise the difficulty
     difficultyLevel++;
     //and play another sequence
     playASequence();
      }
 
    } else {//wrong answer
      textWatchGo.setText("FAILED!");
        //don't checkElement anymore
        isResponding = false;

//for our high score (phase 4)
        if(playerScore > hiScore) {
         hiScore = playerScore;
              editor.putInt(intName, hiScore);
              editor.commit();
              Toast.makeText(getApplicationContext(), "New Hi-score", Toast.LENGTH_LONG).show();
  }

}

}

}


if you need some extra info like pages from the book tutorial or the respective MainActivity and GameActivity XML just reply on this post and will put them.


and also can anyone please help me on those posts :


https://www.thenewboston.com/forum/topic.php?id=10257

https://www.thenewboston.com/forum/topic.php?id=10255


any advice on them can help me



Thank you very much.
 


















 

Post a Reply

Replies

Oldest  Newest  Rating
0 Gary Whitney · December 18, 2015
My guess is something in the app gradle.build is missing.

If you want more help you are going to look at the errors generated when compiling and when the app crashes.

Also AppCompat is the activity required to support old version APIs.
0 Black Boy · December 19, 2015
when you mean  ­"errors generated" are you refferring to debug my app, well I don't know how to do it yet I'm just a beginner at androidStudio but from what I read it has something to do with stack trace and log.i after that I know nothing about it I will do my research on it and try to understand
0 Black Boy · January 28, 2016
I found the error in this code, in GameActivity the setContentView is set to activity_main xml and not the activity_game xml. I would never be able to find this if I didn't have the publisher source code to compare, but I wonder how I would find this error if I hadn't though to look at the publisher website? .I tried to debug it myself and look at the logcat tab for stack traces, I didn't understood a thing on those red words or line.
0 Gary Whitney · January 29, 2016
I was not referring to the debug tool. That is helpful for stepping through an app to see when it crashes.
I am referring to adb.log.
When you first run the app you see the usual stuff about using HAXM
Then It tries to install the app on the AVD.
Then it tries to run the app.
When it encounters an error it does a stack trace dump starting at the top i.e. the method it was trying to run when it found the error.
All the lines below that are the methods that were called before the method that failed.

Somewhere in the stack there was a "caused by" line that lists the line in your code that initiated a call to the method above it, which called the method above it ... and so on.
When you find the line that is your code, you look in your code, at that line number, to make sense of the error.
  • 1

Java / Android Development

107,190 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator