views:

336

answers:

3

Ok, im fairly new to android but i have managed to teach myself the basics, i am making an app where you press a button , and a new screen opens and it shows a randomly generated number, the only problem is i dont know how to generate and display the random number, i have been searching the web for ages and have only found little snippets of information , that dosent really make sense to me. :/

If someone could help me , or even give me just a little bit of info that should guide me in the right direction it would be great

EDIT: (for the comment below)

    super.onCreate(savedInstanceState);
    TextView tv = new TextView(this);
    tv.setText("Random Number : " + Math.random());
    int random = (int)Math.ceil(Math.random()*100);
    setContentView(tv);

Thats the code i have , where have i gone wrong ^^^^ :/

A: 

Actually, you could easily use :

yourVariable = Math.random();

Should work in Android. Gives you a number between 0 and 1. Then you give yourVariable to a TextView with the method .setText(yourVariable) for instance...

Sephy
A: 

Here is your documentation for Random. Beyond that I'm not sure if you want to launch an Activity or update a TextView or what have you. However, I strongly recommend reading the documentation for Activity as well as common tasks in android and User Interface. These should help you understand what you are trying to do.

jqpubliq
+2  A: 

Android's documentation is excellent. Here's a hello world app:

http://developer.android.com/guide/tutorials/hello-world.html

Just change

tv.setText("Hello, Android");

to

tv.setText("Random Number: " + Math.random());

and make sure to import the Math library (if you're using eclipse, hit Ctrl+Shift+O).

Ralphleon
Thankyou so much !!!! you are a life saver :DJust one extra question though , is there a way to set a boundary for the random number , i would like it to be between 0 and 100 :)
Dan
Sure, the normal trick is to take the number (from 0->1) and multiply it by the max then round:int random = (int)Math.ceil(Math.random()*100);
Ralphleon