Random call name in Android - 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);
}
});

Related

How to change Random in to Sequence Order

I am developing word scramble android app. I want to display the String of word in Sequence order but in below code it get random word from the dictionary. My question is how to change my code to get words from Dictionary in Sequence Order?
String[] dictionary=
{"One","Server","Terminate","Analyze","Finish","Start","Wonder","Slow"};
r = new Random(System.currentTimeMillis());
newGame();
// shuffle algorithm
private String shuffleWord(String word){
List<String> letters = Arrays.asList(word.split(""));
Collections.shuffle(letters);
String Shuffled="";
for (String letter : letters ){
Shuffled += letter;
}
return Shuffled;
}
private void newGame(){
// get random word from dictionary
currentWord= dictionary[r.nextInt(dictionary.length)];
// show the shuffled word
tv_word.setText(shuffleWord(currentWord));
// clear the textfield
et_guess.setText("");
// switch buttons
b_new.setEnabled(false);
b_check.setEnabled(true);
}
}
Actually you pick your word with a random position
r = new Random(System.currentTimeMillis());
using an integer random from 0 to ArrayOfWords lenght.
currentWord= dictionary[r.nextInt(dictionary.length)];
Why you dont try to make a counter instead?
int r = 0;
while (r<dictionary.length()) {
currentWord = dictionary[r];
r++;
}
Or I don't understand your answer. But there is the pseudo of what I understand.

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.

Dynamic Button Onclick Listener

I am trying to create dynamic buttons. When clicking a button it should go to the specified url assigned to the text of the button.
For testing, first I tried to get that ID, if it is equal it prints the value of i. But whenever I clicked any one button, instead of telling that particular i value, it enters into whole loop, and prints all the values of i starting from 1 to 19 (the number of buttons that are dynamically created)
And after printing all values from 1 to 19, the program is getting force closed saying Null pointer exception.
I even tried by placing the handler code outside onCreate(), but I'm still getting the same error.
for ( i = 0; i <itemList.getTitle().size()-1; i++) {
title[i] = new TextView(this);
title[i].setTextColor( -16711936 );
title[i].setTextSize(18);
title[i].setText("Title = "+itemList.getTitle().get(i));
description[i] = new TextView(this);
description[i].setTextColor(-16776961);
description[i].setText("Description = "+itemList.getDescription().get(i)+"......");
more[i]=new Button(this);
more[i].setText(itemList.getLink().get(i));
layout.addView(title[i]);
System.out.println("Title view is set");
layout.addView(description[i]);
//System.out.println("Description view is set");
layout.addView(more[i]);
more[i].setOnClickListener(listener);
}
private OnClickListener listener=new OnClickListener(){
public void onClick(View arg) {
int index = 0;
for (i = 0; i < more.length; i++)
{
if (more[i].getId() == arg.getId())
{
index = i;
System.out.println("Value of i onclick is"+i);
}
}
//System.out.println("Vlaue of I in onclick"+i);
//Uri uri=Uri.parse(itemList.getLink().get(i));
//startActivity(new Intent(Intent.ACTION_VIEW,uri));
//Toast.makeText(getApplicationContext(), "This button is clicked"+i+more[i].getText()+itemList.getLink().get(i),Toast.LENGTH_LONG).show();
}
}
You can use setTag() and getTag() method of View to identify different button.
for (i = 0; i < itemList.getTitle().size()-1; i++) {
...
more[i].setTag(i); // Use index of itemList as the tag
}
In onClick:
int index = (Integer)arg.getTag();
you can also set the id of button
more[i].setid(i);
int index = 0;
for (i = 0; i < more.length; i++)
{
if (more[i].getId() == arg.getId())
{
index = i;
System.out.println("Value of i onclick is"+i);
}
}
As you can see here, i is still in your for loop.
Put the System.out.println("Value of i onclick is"+i); outside of your for loop and it should work
PS: format your code, it's easier to read that way and you'll notice small mistakes like these more easily
I think this will help you..
set button tag also dynamic like
more[i].setId(i);
and also changed condition like
if (more[i].getId() == i) {
index = i;
}
hope this will help you...

Categories

Resources