Saturday, 29 October 2011

Generate Random number, Random()

java.util.Random is a class provides methods that return pseudo-random values.

Normally (in other language/system), we will generate random number with seek of current time, to try to make the pseudo-random un-predictable. But in case of Android, it's not necessary and not recommended - Because "It is dangerous to seed Random with the current time because that value is more predictable to an attacker than the default seed." - refer to Android document java.util.Random.

The default constructs, Random(), already come with an initial state that is unlikely to be duplicated by a subsequent instantiation.

Here is a example to generate 10 integer using Random().

Generate Random number, Random()

package com.exercise.AndroidRandom;

import java.util.Random;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class AndroidRandomActivity extends Activity {

Button generateRandom;
TextView randomResult;
Random myRandom;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
generateRandom = (Button)findViewById(R.id.generate);
randomResult = (TextView)findViewById(R.id.randomresult);

generateRandom.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String result = "";
myRandom = new Random();

for(int i = 0; i < 10; i++){
result += String.valueOf(myRandom.nextInt()) + "\n";
}

randomResult.setText(result);
}});

}
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/generate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Generate Random Number"
/>
<TextView
android:id="@+id/randomresult"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

No comments:

Post a Comment