Generating a random number outside of the oncreate method - android

I'm trying to set up my activity so that I can generate a set of random numbers from methods outside of my onCreate method. Here's how my activity is set up...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.optionOne();
this.optionTwo();
this.optionThree();
}
public void optionOne() {
// generate a random number here
int random = Math.random();
// generate more random numbers and do more stuff here
}
The problem is, any random numbers I generate outside of the onCreate method are considered 'static' and the numbers are always 0. If I generate numbers inside the onCreate method, it of course works just fine. How can I fix this?

private static Random ranGenerator=new Random();
Declare it as a member of the class.
then just call ranGenerator.nextInt() any time to get it.

To generate random number use,this will create random between specific range
public void optionOne() {
var=(int)(Math.random() * (max - min) + min) //math.random will return integer values
// use your var wisely
}

use
Random rand = new Random();
int random = rand.nextInt();
or
int random = rand.nextInt(range);
According to doc here
Math.random() Returns a pseudo-random double n, where n >= 0.0 && n < 1.0.

This will help you to create an array list of non repeating random numbers
ArrayList<Integer> indexArray = new ArrayList<Integer>();
for (i = 0; i < 202; ++i) {
number.add(i);
// number.add(num);
}
Collections.shuffle(number);

Related

Creating a random quiz with buttons app for android, but crashes if the first questions displays first

I'm trying to create a random quiz app, but i'm facing a particular problem that i was not able to solve in the last 2 days.
I have all my questions and options inside of 2 different array of Strings. An int called flag which determines the progress of the quiz
int flag=0;
String allQuestions[]={"A","B","C","D","E","F","G","H","I","J"};
String allOptions[]={/*/Primeras opciones /*/"A","I","O",
/*/Segundas opciones/*/"E","O","I",
/*/Terceras opciones/*/"A","I","U",
/*/Cuartas opciones/*/"O","E","U",
*/Quintas opciones/*/"O","U","A",
/*/Sextas opciones/*/"I","U","E",
/*/Septimas opciones/*/"E","I","E"
/*/Octavas opciones/*/"A","I","U",
/*/Novenas opciones/*/"E","U","O",
/*/Decimas opciones/*/"A","O","U"};
This is how i pick the random numbers:
ArrayList<Integer> number = new ArrayList<Integer>();
for (int i = 1; i <= 10; ++i) number.add(i);
Collections.shuffle(number);
I have my buttons linked and make their text change once the quiz activity is created.
question=(TextView)findViewById(R.id.QuizCharacter);
answerA=(Button)findViewById(R.id.answerA);
answerB=(Button)findViewById(R.id.answerB);
answerC=(Button)findViewById(R.id.answerC);
answerD=(Button)findViewById(R.id.answerD);
answerE=(Button)findViewById(R.id.answerE);
answerF=(Button)findViewById(R.id.answerF);
question.setText(number.get(flag)); // <------ having problems here?
answerA.setText(allOptions[0]);
answerB.setText(allOptions[1]);
answerC.setText(allOptions[2]);
answerD.setText(allOptions[3]);
answerE.setText(allOptions[4]);
answerF.setText(allOptions[5]);
Now, the randomizer works, the problem is that if the created random number is the first question A, then the app crashes.
I tried changing what i assume is the problematic line for
question.setText(allQuestions[number.get(0)]);
And instead of having a chance to randomize, it crashes every time.
Why is it happening and how can i fix it?
EDIT:
onCreate method:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz1);
correct = 0;
flag=0;
ArrayList<Integer> number = new ArrayList<Integer>();
for (int i = 0; i < 10; ++i) number.add(i);
Collections.shuffle(number);
String questionCounter = "Question number (flag+1): " + (flag + 1);//+ "\nnumber.get(flag)="+ number.get(flag);
TextView questionNumber;
questionNumber = (TextView) findViewById(R.id.questionNumber);
questionNumber.setText(questionCounter);
question.setText(allQuestions[number.get(0)]);
answerA=(Button)findViewById(R.id.answerA);
answerB=(Button)findViewById(R.id.answerB);
answerC=(Button)findViewById(R.id.answerC);
answerD=(Button)findViewById(R.id.answerD);
answerE=(Button)findViewById(R.id.answerE);
answerF=(Button)findViewById(R.id.answerF);
question.setText(allQuestions[number.get(flag)]);
answerA.setText(allOptions[0]);
answerB.setText(allOptions[1]);
answerC.setText(allOptions[2]);
answerD.setText(allOptions[3]);
answerE.setText(allOptions[4]);
answerF.setText(allOptions[5]);
}
Edit 2:
Thanks to Shadab Ansari for the answer. I forgot to initialize the variable question.
You are not storing anything at 0th index of number.
for (int i = 1; i <= 10; ++i) number.add(i); //Runs from 1 to 10
Your loop should change to -
for (int i = 0; i < 10; ++i) number.add(i); //Runs from 0 to 9
Also, according to the logs, "question" may be null. So please initialize all the views before using it.

Random call name in Android

How to make a 'random call' name in List in database sqlite. How can I call one by one without repeating its value. My layout is one textview, If I click the name it will change. Thank you.
Untested, but should be fine:
Query your database, then use the returned Cursor to populate a LinkedList with whatever options you would like.
LinkedList list = new LinkedList();
if (cursor.getCount() > 0) {
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
list.add(cursor.getString(etc...);
}
}
Create a Random object, and use it to select and remove a random element from list each time:
Random rnd = new Random();
//The below section could be repeated on, for instance, a button click.
int randomValue = rnd.nextInt(list.size());
String result = list.get(randomValue);
list.remove(randomValue);
Each time an element is removed, the LinkedList will adjust in size to accommodate it, so no results will be repeated.
#PPartisan not working.
I add button to test the result from textview. 1 row only detected when I pressed back and back to activity the result is the same value. I clicked the button did not work.
rnd = new Random();
randomValue = rnd.nextInt(list.size());
result =list.get(randomValue).toString();
list.remove(randomValue);
btnClick.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
tv.setText(result);
}
});

Make a random array and print it one by one

I want to make a random array and print it over one by one. But I need to print all of it without make any duplicate. I've try to adding it into list but it seems fail.
My Code :
String quest1 = "5x5#5*10#8/4"
String[] quest = quest1.split("#");
ArrayList <String> question = new ArrayList<String>();
question.add(quest[0]);
question.add(quest[1]);
question.add(quest[2]);
Random rand = new Random();
int id = rand.nextInt(question.size());
System.out.println(question.get(id));
question.remove(id);
I want to print 5x5 5*10 8/4 but in random order and I want to print each of it without print it again.
Make a key value 2d object array or a hashmap of integer and boolean. Against all the numbers keep the boolean value false (implying that the number hasn't been printed yet ). Then generate a random number using Random class. Let this be n. Calculate n%array.length. Now see if for this new index whether you have true/false in the 2dArray/hashmap. If false then print the corresponding number and else don't print anything. I hope it's clear to you
Try following code
ArrayList<Integer> questionPrinted = new ArrayList<Integer>();
int i=0;
while (question.size()>0) {
Random rand = new Random();
int id = rand.nextInt(question.size());
if (questionPrinted.size() > 0) {
if (questionPrinted.contains(id)) {
while (!questionPrinted.contains(id))
id = rand.nextInt(question.size());
}
}
questionPrinted.add(i);
System.out.println(question.get(id));
question.remove(id);
i++;
}

Check if number exists, if it does - get another

I am using a database to show random message at the push of a button.
Every time the button is pushed, a random number is generated and displays a message that corresponds to that number.
Of course, the same message can appear twice as the same number can be generated twice.
So I am creating a string, and I am concatenating each number when the button is pushed.
If the new random number is in the String, then I want to get another number. If that number is in that String, I want to get another number etc etc (Regression?).
I also want to have a global count that I can change, so if the String reaches a size of 9 numbers, it will be reset to "".
String randomList; //global
final int MAX_STRING_LENGTH = 9;
Integer randomNumber = getRandomMessage(messages.size());
if(randomList.length() > 0)
{
if(!randoms.contains(randomNumber.toString()))
{
messageText.setText(messages.get(randomNumber));
}
}
Create a boolean Array of 9 elements
boolean[] check = new boolean[9];
Everytime you use a number, set check[number] to true
void useNumber(int number){
check[number] = true;
}
To check if you already used this number
boolean checkNumber(int number){
return check[number];
}
To reset check
void resetCheck(){
for(int i = 0; i < check.length; i++) check[i] = false;
}
Edit:
Get a string for a given number, resetCheck if necessary;
String getString(int number){
if(usedString == check.length){
resetCheck();
usedString = 0;
}
if(checkNumber(number)){
return getString(getRandomNumber());
}else{
usedString++;
return strings[number];
}
}
I think you can better use a boolean array. You can store the boolean array with the SharedPreferences class. A boolean array is more flexible and you can retrieve the values in constant time. You can also easily make it larger when you have more random messages.
Do a simple trick Hope this works for you
buttonRandom.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Collections.shuffle(messages);
messageText.setText(messages.get(0));
}
});

randomGenerator avoid duplicates in a row

I have a question regarding the following code
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(4);
String wordList[] = new String[4];
{
wordList[0] = "Red";
wordList[1] = "Blue";
wordList[2] = "Green";
wordList[3] = "Orange";
}
String wordToDisplay = wordList[randomInt];
This code works fine however I would like to know if it was possible to get it to not pick the same word two times in a row. For example, if it just selected "Red" then it would not pick "Red" again the next consecutive time. I read something about DISTINCT but I'm not sure if that's along the right path.
Here is the code for the button which uses this
final Button button1 = (Button) findViewById(R.id.button1);
final TextView textView = (TextView) findViewById(R.id.text_random_text);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(9);
String wordToDisplay = wordList[randomInt];
textView.setText(wordToDisplay);
Thankyou for your help
go for list and remove color once used:
private static ArrayList<String> arrayList = new ArrayList<String>();
private static Random random = new Random();
public static void fillList(){
arrayList.add("Red");
arrayList.add("Blue");
arrayList.add("Green");
arrayList.add("Orange");
}
public static String getNextRandomColor(){
if(arrayList.isEmpty()){
fillList();
}
return arrayList.remove(random.nextInt(arrayList.size()));
}
You can do this in two way (probably more but two that I can think of right now):
1) Create a function that uses a global variable to store the last generated random number.
It will look something like this:
int myRand(int i) {
int aux;
Random randomGenerator = new Random();
do {
aux = randomGenerator.nextInt(i);
} while (aux != lastRandGenerated);
lastRandGenerated = aux;
return aux;
}
, where lastRandGenerated is a global variable that you initialize to 0.
Then you use this function to generate random numbers.
2) You can create a class that has a function very similar to the one above and then instantiate an object of that class and use that to generate your random numbers. In the class create a static variable that will remember the last generated random number. Use that instead of the global variable.
The specifics are a bit out of my league but as a math problem there are 24 combinations (4 * 3 * 2 * 1). As heavy handed as this might sound, worst case you could work out all the combos and then pick a one out of 24 random.

Categories

Resources