0

I am currently working on my finals project on android. the project is about a SimonSays game: in my Simon Says game a have a section where the application is supposed to sleep but it does , i think its because my teacher added all of these try and catch

functions, how do i fix it?

    package com.gabie212.simonsays;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

public class GameActivity extends AppCompatActivity implements View.OnClickListener,View.OnLongClickListener {

    private int i = 0, pNum = 0, pIndex = 0,score;
    private Thread t = new Thread();
    private Thread bt = new Thread();
    private Button greenButton;
    private Button redButton;
    private Button blueButton;
    private Button yellowButton;
    private Button startButton;
    private TextView Score;
    private boolean startActivated = false;
    private MediaPlayer greenBeep;
    private MediaPlayer redBeep;
    private MediaPlayer blueBeep;
    private MediaPlayer yellowBeep;

    private ArrayList<Integer> userColors = new ArrayList<Integer>();
    // change backgroud
    final String imagefile = "savedImageLocation";//for background
    private ImageButton btPhoto;  // for background
    private android.support.constraint.ConstraintLayout background; // for background
    private int yellowish = Color.rgb(0, 191, 255);// for background
    private Handler handler = new Handler();

    final int SECOND_ACTIVITY = 10;

    // game manager
    private GameManger gm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_game);

        Score = (TextView) findViewById(R.id.ScoreNum);
        greenButton = (Button) findViewById(R.id.btnGreen);
        redButton = (Button) findViewById(R.id.btnRed);
        blueButton = (Button) findViewById(R.id.btnBlue);
        yellowButton = (Button) findViewById(R.id.btnYellow);
        startButton = (Button) findViewById(R.id.btnStart);
        greenButton.setOnClickListener(this);
        redButton.setOnClickListener(this);
        blueButton.setOnClickListener(this);
        yellowButton.setOnClickListener(this);
        startButton.setOnClickListener(this);
        greenBeep = MediaPlayer.create(this, R.raw.greenbeep);
        redBeep  = MediaPlayer.create(this, R.raw.redbeep);
        blueBeep =   MediaPlayer.create(this, R.raw.bluebeep);
        yellowBeep =  MediaPlayer.create(this, R.raw.yellowbeep);
        greenButton.setOnLongClickListener(this);
        redButton.setOnLongClickListener(this);
        blueButton.setOnClickListener(this);
        yellowButton.setOnClickListener(this);
     /*
        SharedPreferences sp = getSharedPreferences("score", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        editor.apply();

     */


        // for change background
        btPhoto = (ImageButton) findViewById(R.id.btPhoto);
        btPhoto.setOnLongClickListener(this);
        background = (android.support.constraint.ConstraintLayout) findViewById(R.id.background);
    }

    public void start() {
        startActivated=true;
        gm = new GameManger(this);
        Score.setText("0");
        lightUp(0);
    }

    public void beepStop(){
        greenBeep.stop();
        redBeep.stop();
        blueBeep.stop();
        yellowBeep.stop();

    }


    public void lightUp(final int i) {

        android.os.Handler handler = new android.os.Handler();
        if (i < gm.getRandomColors().size())  //light up code
        {
            switch (gm.getRandomColors().get(i)) {
                case 1:
                    greenButton.setBackgroundResource(R.drawable.greenlightup);
                    greenBeep.start();
                    handler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            greenButton.setBackgroundResource(R.drawable.green);
                            lightUp(i+1);
                        }
                    }, 500);


                    break;
                case 2:
                    redButton.setBackgroundResource(R.drawable.redlightup);
                    redBeep.start();
                    handler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            redButton.setBackgroundResource(R.drawable.red);
                            lightUp(i+1);
                        }
                    }, 500);


                    break;
                case 3:
                    blueButton.setBackgroundResource(R.drawable.bluelightup);
                    blueBeep.start();
                    handler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            blueButton.setBackgroundResource(R.drawable.blue);
                            lightUp(i+1);
                        }
                    }, 500);


                    break;
                case 4:
                    yellowButton.setBackgroundResource(R.drawable.yellowlightup);
                    yellowBeep.start();
                    handler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            yellowButton.setBackgroundResource(R.drawable.yellow);
                            lightUp(i+1);
                        }
                    }, 500);


                    break;
            }

        }
        pIndex = 0;
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == startButton.getId()) {
            start();
        } else {
            if (startActivated) {
                if (v.getId() == greenButton.getId()) {
                    greenBeep.start();
                    pNum = 1;
                }
                if (v.getId() == redButton.getId()) {
                    redBeep.start();
                    pNum = 2;
                }
                if (v.getId() == blueButton.getId()) {
                    blueBeep.start();
                    pNum = 3;
                }
                if (v.getId() == yellowButton.getId()) {
                    yellowBeep.start();
                    pNum = 4;

                }
                if (!gm.check(pNum, pIndex)) {
                    beepStop();
                    SharedPreferences sp = getSharedPreferences("score", Context.MODE_PRIVATE);
                    Intent i = null;
                    score = gm.getRandomColors().size()-1;
                    if(score > sp.getInt("scoreP3",0)) {
                         i = new Intent(GameActivity.this, InsertScoreActivity.class);
                        i.putExtra("score", gm.getRandomColors().size() - 1);
                        startActivity(i);
                    }
                    else {
                        i = new Intent(GameActivity.this, GameOverActivity.class);
                        i.putExtra("score", gm.getRandomColors().size() - 1);
                        startActivity(i);
                    }
                }
                pIndex++;
                if (pIndex == gm.getRandomColors().size()) {
                    Score.setText("" + gm.getRandomColors().size() + "");
                    gm.addColor();
                    //this is the sleep that doesn't work
                    try {                              
                        t.sleep(500);
                        // Do some stuff                 
                    } catch (Exception e) {
                        e.getLocalizedMessage();
                    }
                    //this is the sleep that doesn't work
                    lightUp(0);
                }
            }

        }

    }
    // for background
    public void getPhoto(View v)
    {
        //brings user to gallery to select image for background of screen
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"),0);
    }
    //for background
    @Override
    public boolean onLongClick(View view)
    {
        AlertDialog.Builder info = new AlertDialog.Builder(this);
        info.setTitle("Remove Background Image?");
        info.setMessage("Are you sure you wish to revert to the default background?");
        info.setCancelable(true);
        info.setPositiveButton("Yes", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int id)
            {   //erases current background image location

                try {
                    FileOutputStream fos = openFileOutput(imagefile, Context.MODE_PRIVATE);
                    OutputStreamWriter osw = new OutputStreamWriter(fos);
                    BufferedWriter writer = new BufferedWriter(osw);

                    writer.close();
                    osw.close();
                    fos.close();

                    background.setBackgroundColor(yellowish);
                }
                catch (Exception e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        info.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int id)
            {
                dialog.cancel();
            }
        });

        info.show();

        return false;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if(requestCode == 0 && resultCode == RESULT_OK)
        {
            try
            {
                Uri selectedImage = data.getData();

                grantUriPermission("com.example.memorygame", selectedImage,
                        Intent.FLAG_GRANT_READ_URI_PERMISSION);

                InputStream imageStream;
                imageStream = getContentResolver().openInputStream(selectedImage);
                Bitmap bitmap = BitmapFactory.decodeStream(imageStream);
                Drawable image = new BitmapDrawable(getResources(), bitmap);
                background.setBackground(image);

                //saves location of background image
                try
                {

                    FileOutputStream fos = openFileOutput(imagefile, Context.MODE_PRIVATE);
                    OutputStreamWriter osw = new OutputStreamWriter(fos);
                    BufferedWriter writer = new BufferedWriter(osw);

                    String imageUri = selectedImage.toString();
                    writer.append(imageUri);

                    writer.close();
                    osw.close();
                    fos.close();

                }
                catch (Exception e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            catch (FileNotFoundException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }



        }
    }

}

so this is my code and the i will put two notes on the thread.sleep that doesn't work for me. basically i have this function that lights up a series of buttons (switches their color in a certain order) , then i have a function which receives the user input ( what buttons the user pressed and in what order). what i want to do by that sleep is to put a little break between the end of the color input(when the user finishes to press stuff), and the beginning of the light up ( when the buttons lightup/change their color). i think the problem comes with all of the these try and catch functions or however they're called (sorry i am a beginner) however i don't know hwo to overcome this.

3 Answers3

0

In android, you can use Handler to wait for as much as you want, here's an example of 2 seconds (2000 milliseconds) delay:

Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() {
         @Override 
         public void run() { 
              // this code will run after 2 seconds
         } 
    }, 2000); 

Just insert this code anywhere you need to wait/sleep your thread.

Sergey Emeliyanov
  • 5,158
  • 6
  • 29
  • 52
  • hey , thank you for commenting , doesn't the handler interfere with the toother post delayed handler or something, because this is what happened the tother time – gabie dubin Mar 21 '18 at 10:29
  • @gabiedubin - If you put this Handler in your code (on UI thread) it will just freeze your app for the amount of time set. – Sergey Emeliyanov Mar 21 '18 at 10:31
  • hey , this code doesn't work for me, i don't know why but it interferes with the other handler.postDelayed i have. do you have any other suggestions , the thread.sleep worked before the other try and catch were added. – gabie dubin Mar 21 '18 at 10:33
0

You should avoid Thread.sleep(). Use handler for doing UI related operation.

new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
    @Override
    public void run() {
        //Do something here
    }
}, 5000);

If you get some time please go through the below link. This will give an idea of handler and thread. Android, Handler is running in main thread or other thread?

Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147
0

It's better to use Handler instead to Thread.sleep();

Just Replace this

 //this is the sleep that doesn't work
                    try {
                        t.sleep(500);
                        // Do some stuff
                    } catch (Exception e) {
                        e.getLocalizedMessage();
                    }
                    //this is the sleep that doesn't work

With

  Handler handler1=new Handler();
                    handler1.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            lightUp(0);
                        }
                    },500);
Pankaj Bansal
  • 23
  • 1
  • 5