Search code examples
javaandroidoncreate

I want to create buttons on random times - Android


I'm trying to make a simple bubbles game, I'm supposed to make 10 bubbles appear randomly on the screen for 3 seconds each. Whenever the user touches a bubble he has made it disappear and earns a point. The problem now is that I can t show the bubbles randomly in time, I've tried to use Thred.sleep() in a for loop but it make all the application wait until looping ends and then it shows all the 10 bubbles. Here is the java code:
NB: please check the 'generateButtons' methode

package com.adil.bullegame;


import android.app.ActivityManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;

import android.view.View;
import android.widget.Button;

import android.widget.RelativeLayout;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static java.lang.Integer.parseInt;
import static java.lang.Thread.sleep;
import java.util.*;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

public class MainActivity extends AppCompatActivity {

    private int bubblesNumber ;
    static int clickedBubbles=0;
    TextView text1;
    private static String in;
    private static final String FORMAT = "%02d:%02d:%02d";

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

        text1=(TextView)findViewById(R.id.textView3);

        CountDownTimer start = new CountDownTimer(10000, 1000) { // adjust the milli seconds here

            public void onTick(long millisUntilFinished) {

                text1.setText("" + String.format(FORMAT,
                        TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
                        TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
                                TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
                        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
                                TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
            }

            public void onFinish() {
                showSimplePopUp();
                clickedBubbles=0;
            }
        }.start();


        // dynamic number of bubbles
        in =null;
        try{
            InputStream is = getAssets().open("file.txt");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            in = new String(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // bubblesNumber = parseInt(in);

        generateButtons(10);
    }

    private void generateButtons(int nbr)
    {
        for(int i = 0; i< nbr ; i++)
        {
            createButton();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }





            private void createButton() {

        RelativeLayout layout = (RelativeLayout)findViewById(R.id.activity_main);

            final Button myButton = new Button(this);
            layout.addView(myButton); ;

        RelativeLayout.LayoutParams absParams =
                (RelativeLayout.LayoutParams)myButton.getLayoutParams();

        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int width = displaymetrics.widthPixels;
        int height = displaymetrics.heightPixels;


        Random r = new Random();


        absParams.leftMargin =  r.nextInt(width-150) ;
        absParams.topMargin =  r.nextInt(height-150);
        myButton.setLayoutParams(absParams);


        myButton.postDelayed(new Runnable()
                                { public void run()
                                    { myButton.setVisibility(View.GONE); } }, 3000);

        //new Timer().schedule(new TimerTask() {
         //  @Override
       //     public void run() {
           //       ((LinearLayout)myButton.getParent()).removeView(myButton);
         //      myButton.setVisibility(View.GONE);
       //     }
     //   }, 3000);

        myButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                clickedBubbles++;
                v.setVisibility(View.GONE);

            }
        });



    }

    private void showSimplePopUp() {

        AlertDialog.Builder gameOver = new AlertDialog.Builder(this);
        gameOver.setTitle("GameOver");
        gameOver.setMessage("You clicked "+ clickedBubbles + " bubbles");
        gameOver.setPositiveButton("restart",
                new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(MainActivity.this,  MainActivity.class);
                        startActivity(intent);

                    }

                });


        AlertDialog dialog = gameOver.create();
        dialog.show();
    }

}

NB: please check the 'generateButtons' methode


Solution

  • Your application if freezing because your are calling sleep function on main UI thread. there are number of ways to solve this issue.

    try the following method

    private void generateButton(final int numberOfButtons) {
             new android.os.Handler().postDelayed(new Runnable() {
                 @Override
                 public void run() {
                     createButton();
                     if((numberOfButtons-1)>0){
                         generateButton(numberOfButtons-1);
                     }
                 }
             }, 2000);
        }