Search code examples
androidarrayscanvasrandomdrawtext

how to create array of numbers in range 1 to 100 in view class


everyone, Please help me!

I want to show an array of numbers in a shape.

What I did

1) I draw a shape with canvas in View class.

2) I create a single random number.

3) I've searched a lot & find out that should use Drawtext to show a text or number.

4) I've read the documentation of Random, Drawtext, etc.

5) I've tried for loop but it didn't work outside of canvas class & inside, also will repeat that single number infinite times.

my Problem

I don't know how to put that number in an array & how to show array with drawtext in view class.

at the moment, I can show only one random number, but a want to show an array of random numbers.

I'm very new in Android & my English is not so good. I'll be very grateful if anybody can Help me through this.

Thank You.

Here's the part of my code that I used for creating a single random number (this is outside of class, constructor & onDraw method) :

Random rand = new Random();
        int number = rand.nextInt(100) + 1;
        String mystring = String.valueOf(number);

& in onDraw method for showing this number i used below code :

@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);
canvas.drawText(mystring,130,480,black_paintbrushstroke);
}

Solution

  • Please try to use ArrayList to hold your random data, like:

    ArrayList<Integer> arrayList = new ArrayList<>(100); 
    Random r = new Random(System.currentTimeMillis());
    for(int i = 0; i < 100; i++) {
        arrayList.add(r.nextInt());
    }
    

    Then:

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int yOffset = 10;
        int yStartPosition = 480;
        for (int i = 0; i < arrayList.size(); i++) {
            Integer integer = arrayList.get(i);
            canvas.drawText(String.valueOf(integer), 130, yStartPosition+(i*yOffset), black_paintbrushstroke);
        }
    }
    

    Looks like you are drawing all your items into the same postion (x,y), you need to add some vertical offset to draw new value bellow previous one.

    If you want to draw all you numbers as comma-separted string, you need to convert your array into String using StringBuilder:

    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < arrayList.size(); i++) {
        sb.append(arrayList.get(i)).append(",");
    }
    
    String myRandomNumbersArray = sb.toString();
    sb.setLength(0);